test.cc 957 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476
  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(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1470. Server svr;
  1471. std::string file_names;
  1472. svr.Post("/upload", [&](const Request &req, Response &res) {
  1473. for (const auto &file : req.form.files) {
  1474. file_names += file.first + "|" + file.second.filename + " ";
  1475. }
  1476. res.set_content("ok", "text/plain");
  1477. });
  1478. auto port = svr.bind_to_any_port(HOST);
  1479. thread t = thread([&] { svr.listen_after_bind(); });
  1480. auto se = detail::scope_exit([&] {
  1481. svr.stop();
  1482. t.join();
  1483. ASSERT_FALSE(svr.is_running());
  1484. });
  1485. svr.wait_until_ready();
  1486. // A trailing backslash would otherwise escape the closing quote.
  1487. UploadFormDataItems items = {
  1488. {"dir\\", "x", "a.txt", "text/plain"},
  1489. {"b", "y", "a\\\\b.txt", "text/plain"},
  1490. };
  1491. Client cli(HOST, port);
  1492. auto res = cli.Post("/upload", items);
  1493. ASSERT_TRUE(res);
  1494. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1495. }
  1496. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1497. // Server::read_content() keeps a FormFields::iterator alive across the
  1498. // content callbacks that fill the part it points at. The container is
  1499. // vector-backed, so a later emplace can reallocate and invalidate an older
  1500. // iterator; 64 parts grow the vector through seven reallocations, which
  1501. // checks that every part's content still lands in its own entry.
  1502. const size_t part_count = 64;
  1503. // One formula for both the parts sent and the values expected back, so the
  1504. // two cannot drift apart.
  1505. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1506. auto content_of = [](size_t i) {
  1507. return std::string(64, static_cast<char>('a' + (i % 26)));
  1508. };
  1509. Server svr;
  1510. std::vector<std::pair<std::string, std::string>> received;
  1511. svr.Post("/many", [&](const Request &req, Response &res) {
  1512. for (const auto &field : req.form.fields) {
  1513. received.emplace_back(field.first, field.second.content);
  1514. }
  1515. res.set_content("ok", "text/plain");
  1516. });
  1517. auto port = svr.bind_to_any_port(HOST);
  1518. thread t = thread([&] { svr.listen_after_bind(); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. t.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. UploadFormDataItems items;
  1526. for (size_t i = 0; i < part_count; i++) {
  1527. items.push_back({name_of(i), content_of(i), "", ""});
  1528. }
  1529. Client cli(HOST, port);
  1530. auto res = cli.Post("/many", items);
  1531. ASSERT_TRUE(res);
  1532. ASSERT_EQ(part_count, received.size());
  1533. for (size_t i = 0; i < part_count; i++) {
  1534. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1535. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1536. }
  1537. }
  1538. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1539. string content_type = "multipart/form-data; boundary=something";
  1540. string boundary;
  1541. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1542. EXPECT_TRUE(ret);
  1543. EXPECT_EQ(boundary, "something");
  1544. }
  1545. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1546. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1547. string boundary;
  1548. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1549. EXPECT_TRUE(ret);
  1550. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1551. }
  1552. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1553. string content_type =
  1554. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1555. string boundary;
  1556. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1557. EXPECT_TRUE(ret);
  1558. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1559. }
  1560. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1561. string content_type =
  1562. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1563. string boundary;
  1564. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1565. EXPECT_TRUE(ret);
  1566. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1567. }
  1568. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1569. const string boundary(70, 'a');
  1570. string content_type = "multipart/form-data; boundary=" + boundary;
  1571. string parsed;
  1572. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1573. EXPECT_TRUE(ret);
  1574. EXPECT_EQ(parsed, boundary);
  1575. }
  1576. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1577. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1578. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1579. string parsed;
  1580. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1581. EXPECT_FALSE(ret);
  1582. }
  1583. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1584. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1585. // is 72 characters on the wire and still valid.
  1586. const string boundary(70, 'a');
  1587. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1588. string parsed;
  1589. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1590. EXPECT_EQ(parsed, boundary);
  1591. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1592. parsed.clear();
  1593. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1594. }
  1595. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1596. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1597. // The parameter parser must not treat that '=' as the key/value separator.
  1598. string content_type =
  1599. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1600. "charset=UTF-8";
  1601. string parsed;
  1602. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1603. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1604. }
  1605. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1606. // A ';' inside the quoted-string is part of the value, not a parameter
  1607. // separator, so it must not truncate the boundary.
  1608. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1609. string parsed;
  1610. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1611. EXPECT_EQ(parsed, "a;b");
  1612. }
  1613. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1614. string parsed;
  1615. EXPECT_TRUE(detail::parse_multipart_boundary(
  1616. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1617. EXPECT_EQ("a\\b", parsed);
  1618. EXPECT_TRUE(detail::parse_multipart_boundary(
  1619. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1620. EXPECT_EQ("a\"b", parsed);
  1621. }
  1622. TEST(ParseDispositionParamsTest, QuotedValues) {
  1623. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1624. // ';' and '=' are ordinary characters inside one.
  1625. struct {
  1626. const char *value;
  1627. std::vector<std::pair<const char *, const char *>> expected;
  1628. } cases[] = {
  1629. {"name=\"file1\"; filename=\"a.txt\"",
  1630. {{"name", "file1"}, {"filename", "a.txt"}}},
  1631. // Whitespace around '=' and ';' is still trimmed
  1632. {"name=\"file2\" ;filename = \"a.html\"",
  1633. {{"name", "file2"}, {"filename", "a.html"}}},
  1634. // '=' inside the value used to leave only the text after the last one
  1635. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1636. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1637. {"name=\"x=y\"", {{"name", "x=y"}}},
  1638. // ';' inside the value used to truncate the pair and leave a bogus one
  1639. {"name=\"file3\"; filename=\"a;b.txt\"",
  1640. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1641. // An unquoted value keeps working, and so does filename*
  1642. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1643. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1644. // A parameter with no key is dropped rather than turned into one whose
  1645. // key is the value
  1646. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1647. // An escaped quote does not end the value
  1648. {"name=\"a\\\"; filename=evil.php\"",
  1649. {{"name", "a\"; filename=evil.php"}}},
  1650. // Other backslashes, as in a Windows path, are kept
  1651. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1652. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1653. };
  1654. for (const auto &c : cases) {
  1655. Params params;
  1656. detail::parse_disposition_params(c.value, params);
  1657. for (const auto &kv : c.expected) {
  1658. auto it = params.find(kv.first);
  1659. ASSERT_NE(it, params.end())
  1660. << "value: " << c.value << ", key: " << kv.first;
  1661. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1662. }
  1663. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1664. }
  1665. }
  1666. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1667. Server svr;
  1668. std::string filename;
  1669. std::string content;
  1670. svr.Post("/upload", [&](const Request &req, Response &) {
  1671. const auto &file = req.form.get_file("file");
  1672. filename = file.filename;
  1673. content = file.content;
  1674. });
  1675. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1676. auto se = detail::scope_exit([&] {
  1677. svr.stop();
  1678. thread.join();
  1679. ASSERT_FALSE(svr.is_running());
  1680. });
  1681. svr.wait_until_ready();
  1682. std::string body = "--B\r\n"
  1683. "Content-Disposition: form-data; name=\"file\"; "
  1684. "filename=\"a.txt\"\r\n"
  1685. "Content-Type: text/plain\r\n"
  1686. "\r\n"
  1687. "hello\r\n"
  1688. "--B--\r\n";
  1689. Client cli(HOST, PORT);
  1690. auto res = cli.Post(
  1691. "/upload",
  1692. [&](size_t offset, DataSink &sink) {
  1693. if (offset < body.size()) {
  1694. sink.write(&body[offset], 1);
  1695. } else {
  1696. sink.done();
  1697. }
  1698. return true;
  1699. },
  1700. "multipart/form-data; boundary=B");
  1701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1702. EXPECT_EQ(StatusCode::OK_200, res->status);
  1703. EXPECT_EQ("a.txt", filename);
  1704. EXPECT_EQ("hello", content);
  1705. }
  1706. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1707. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1708. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1709. Server svr;
  1710. std::string field_value, file_name, file_filename;
  1711. bool has_field = false, has_file = false;
  1712. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1713. has_field = req.form.has_field("x=y");
  1714. field_value = req.form.get_field("x=y");
  1715. has_file = req.form.has_file("file1");
  1716. const auto &file = req.form.get_file("file1");
  1717. file_name = file.name;
  1718. file_filename = file.filename;
  1719. res.set_content("ok", "text/plain");
  1720. });
  1721. auto port = svr.bind_to_any_port(HOST);
  1722. thread t = thread([&] { svr.listen_after_bind(); });
  1723. auto se = detail::scope_exit([&] {
  1724. svr.stop();
  1725. t.join();
  1726. ASSERT_FALSE(svr.is_running());
  1727. });
  1728. svr.wait_until_ready();
  1729. UploadFormDataItems items = {
  1730. {"x=y", "field-value", "", ""},
  1731. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1732. };
  1733. Client cli(HOST, port);
  1734. auto res = cli.Post("/quoted", items);
  1735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1736. ASSERT_EQ(StatusCode::OK_200, res->status);
  1737. EXPECT_TRUE(has_field);
  1738. EXPECT_EQ("field-value", field_value);
  1739. EXPECT_TRUE(has_file);
  1740. EXPECT_EQ("file1", file_name);
  1741. EXPECT_EQ("a;b=report.pdf", file_filename);
  1742. }
  1743. TEST(GetHeaderValueTest, DefaultValue) {
  1744. Headers headers = {{"Dummy", "Dummy"}};
  1745. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1746. EXPECT_STREQ("text/plain", val);
  1747. }
  1748. TEST(GetHeaderValueTest, DefaultValueInt) {
  1749. Headers headers = {{"Dummy", "Dummy"}};
  1750. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1751. EXPECT_EQ(100ull, val);
  1752. }
  1753. TEST(GetHeaderValueTest, RegularValue) {
  1754. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1755. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1756. EXPECT_STREQ("text/html", val);
  1757. }
  1758. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1759. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1760. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1761. EXPECT_STREQ("text/html", val);
  1762. }
  1763. TEST(GetHeaderValueTest, SetContent) {
  1764. Response res;
  1765. res.set_content("html", "text/html");
  1766. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1767. res.set_content("text", "text/plain");
  1768. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1769. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1770. }
  1771. TEST(GetHeaderValueTest, RegularValueInt) {
  1772. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1773. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1774. EXPECT_EQ(100ull, val);
  1775. }
  1776. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1777. Headers headers = {{"Content-Length", "x"}};
  1778. auto is_invalid_value = false;
  1779. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1780. is_invalid_value);
  1781. EXPECT_EQ(0ull, val);
  1782. EXPECT_TRUE(is_invalid_value);
  1783. }
  1784. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1785. // An all-digit value that overflows size_t must be reported as invalid, not
  1786. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1787. // a large length to a small one on 32-bit builds, leaving the framing length
  1788. // wrong while is_invalid_value stayed false.
  1789. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1790. auto is_invalid_value = false;
  1791. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1792. is_invalid_value);
  1793. EXPECT_TRUE(is_invalid_value);
  1794. // A well-formed length is unaffected.
  1795. Headers ok = {{"Content-Length", "1234"}};
  1796. is_invalid_value = false;
  1797. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1798. is_invalid_value);
  1799. EXPECT_EQ(1234ull, val);
  1800. EXPECT_FALSE(is_invalid_value);
  1801. }
  1802. TEST(GetHeaderValueTest, Range) {
  1803. {
  1804. Headers headers = {make_range_header({{1, -1}})};
  1805. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1806. EXPECT_STREQ("bytes=1-", val);
  1807. }
  1808. {
  1809. Headers headers = {make_range_header({{-1, 1}})};
  1810. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1811. EXPECT_STREQ("bytes=-1", val);
  1812. }
  1813. {
  1814. Headers headers = {make_range_header({{1, 10}})};
  1815. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1816. EXPECT_STREQ("bytes=1-10", val);
  1817. }
  1818. {
  1819. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1820. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1821. EXPECT_STREQ("bytes=1-10, 100-", val);
  1822. }
  1823. {
  1824. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1825. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1826. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1827. }
  1828. {
  1829. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1830. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1831. EXPECT_STREQ("bytes=0-0, -1", val);
  1832. }
  1833. }
  1834. TEST(BearerTokenAuthTest, SchemeValidation) {
  1835. // A value shorter than "Bearer " must not throw from the fixed-length
  1836. // substr, and a non-Bearer scheme must not be reported as a token.
  1837. struct {
  1838. const char *value;
  1839. const char *expected;
  1840. } cases[] = {
  1841. {"x", ""},
  1842. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1843. {"Bearer abc123", "abc123"},
  1844. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1845. };
  1846. for (const auto &c : cases) {
  1847. Request req;
  1848. req.set_header("Authorization", c.value);
  1849. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1850. }
  1851. }
  1852. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1853. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1854. // to depend on the standard library (libstdc++ handed back duplicates in
  1855. // reverse insertion order, libc++ in insertion order).
  1856. Request req;
  1857. req.set_header("Accept-Encoding", "gzip");
  1858. req.set_header("Accept-Encoding", "deflate");
  1859. req.set_header("Accept-Encoding", "br");
  1860. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1861. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1862. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1863. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1864. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1865. }
  1866. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1867. Request req;
  1868. req.set_header("X-Test", "only");
  1869. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1870. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1871. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1872. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1873. }
  1874. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1875. Request req;
  1876. req.set_header("X-First", "1");
  1877. req.set_header("X-Test", "2");
  1878. req.params.emplace("first", "1");
  1879. req.params.emplace("test", "2");
  1880. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1881. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1882. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1883. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1884. // The second one is negative when read as a signed value
  1885. const auto max_id = (std::numeric_limits<size_t>::max)();
  1886. for (auto id : {max_id / 2, max_id}) {
  1887. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1888. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1889. EXPECT_EQ("", req.get_param_value("test", id));
  1890. EXPECT_EQ("", req.form.get_field("test", id));
  1891. EXPECT_EQ("", req.form.get_file("test", id).content);
  1892. }
  1893. }
  1894. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1895. Headers headers;
  1896. headers.emplace("Host", "example.com");
  1897. headers.emplace("Accept-Encoding", "gzip");
  1898. headers.emplace("User-Agent", "test");
  1899. headers.emplace("Accept-Encoding", "deflate");
  1900. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1901. "Accept-Encoding=deflate ",
  1902. entries_to_string(headers));
  1903. }
  1904. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1905. Headers headers = {{"Content-Type", "text/html"},
  1906. {"CONTENT-TYPE", "text/xml"}};
  1907. EXPECT_EQ(2U, headers.count("content-type"));
  1908. auto it = headers.find("content-type");
  1909. ASSERT_TRUE(it != headers.end());
  1910. EXPECT_EQ("text/html", it->second);
  1911. }
  1912. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1913. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1914. // drop only those fields and leave everything positioned between them.
  1915. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1916. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1917. auto rng = headers.equal_range("a");
  1918. headers.erase(rng.first, rng.second);
  1919. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1920. }
  1921. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1922. Headers headers = {
  1923. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1924. EXPECT_EQ(3U, headers.erase("A"));
  1925. EXPECT_EQ(0U, headers.count("A"));
  1926. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1927. }
  1928. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1929. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1930. headers.emplace_front("Host", "example.com");
  1931. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1932. entries_to_string(headers));
  1933. }
  1934. TEST(ParseHeaderValueTest, Range) {
  1935. {
  1936. Ranges ranges;
  1937. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1938. EXPECT_TRUE(ret);
  1939. EXPECT_EQ(1u, ranges.size());
  1940. EXPECT_EQ(1u, ranges[0].first);
  1941. EXPECT_EQ(-1, ranges[0].second);
  1942. }
  1943. {
  1944. Ranges ranges;
  1945. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1946. EXPECT_TRUE(ret);
  1947. EXPECT_EQ(1u, ranges.size());
  1948. EXPECT_EQ(-1, ranges[0].first);
  1949. EXPECT_EQ(1u, ranges[0].second);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ(1u, ranges.size());
  1956. EXPECT_EQ(1u, ranges[0].first);
  1957. EXPECT_EQ(10u, ranges[0].second);
  1958. }
  1959. {
  1960. Ranges ranges;
  1961. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1962. EXPECT_FALSE(ret);
  1963. }
  1964. {
  1965. Ranges ranges;
  1966. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1967. EXPECT_TRUE(ret);
  1968. EXPECT_EQ(2u, ranges.size());
  1969. EXPECT_EQ(1u, ranges[0].first);
  1970. EXPECT_EQ(10u, ranges[0].second);
  1971. EXPECT_EQ(100u, ranges[1].first);
  1972. EXPECT_EQ(-1, ranges[1].second);
  1973. }
  1974. {
  1975. Ranges ranges;
  1976. auto ret =
  1977. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1978. EXPECT_TRUE(ret);
  1979. EXPECT_EQ(3u, ranges.size());
  1980. EXPECT_EQ(1u, ranges[0].first);
  1981. EXPECT_EQ(10u, ranges[0].second);
  1982. EXPECT_EQ(100u, ranges[1].first);
  1983. EXPECT_EQ(200u, ranges[1].second);
  1984. EXPECT_EQ(300u, ranges[2].first);
  1985. EXPECT_EQ(400u, ranges[2].second);
  1986. }
  1987. {
  1988. Ranges ranges;
  1989. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1990. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1992. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1996. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1997. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1998. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2002. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2003. EXPECT_FALSE(
  2004. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2005. EXPECT_TRUE(ranges.empty());
  2006. }
  2007. {
  2008. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2009. // remainder of the representation, so it stays accepted.
  2010. Ranges ranges;
  2011. auto ret =
  2012. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2013. EXPECT_TRUE(ret);
  2014. ASSERT_EQ(1u, ranges.size());
  2015. EXPECT_EQ(0, ranges[0].first);
  2016. EXPECT_EQ(-1, ranges[0].second);
  2017. }
  2018. // RFC 9110 14.1: range unit names are case-insensitive.
  2019. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2020. Ranges ranges;
  2021. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2022. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2023. }
  2024. }
  2025. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "gzip");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2032. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2033. #else
  2034. EXPECT_TRUE(ret == detail::EncodingType::None);
  2035. #endif
  2036. }
  2037. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2038. Request req;
  2039. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2040. Response res;
  2041. res.set_header("Content-Type", "text/plain");
  2042. auto ret = detail::encoding_type(req, res);
  2043. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2044. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2045. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2046. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2047. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2048. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2049. #else
  2050. EXPECT_TRUE(ret == detail::EncodingType::None);
  2051. #endif
  2052. }
  2053. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2054. Request req;
  2055. req.set_header("Accept-Encoding",
  2056. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2057. Response res;
  2058. res.set_header("Content-Type", "text/plain");
  2059. auto ret = detail::encoding_type(req, res);
  2060. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2061. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2062. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2063. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2064. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2065. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2066. #else
  2067. EXPECT_TRUE(ret == detail::EncodingType::None);
  2068. #endif
  2069. }
  2070. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2071. // All supported encodings rejected with q=0 should return None
  2072. Request req;
  2073. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2074. Response res;
  2075. res.set_header("Content-Type", "text/plain");
  2076. auto ret = detail::encoding_type(req, res);
  2077. EXPECT_TRUE(ret == detail::EncodingType::None);
  2078. }
  2079. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2080. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2081. Request req;
  2082. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2083. Response res;
  2084. res.set_header("Content-Type", "text/plain");
  2085. auto ret = detail::encoding_type(req, res);
  2086. EXPECT_TRUE(ret == detail::EncodingType::None);
  2087. }
  2088. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2089. Request req;
  2090. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2091. Response res;
  2092. res.set_header("Content-Type", "text/plain");
  2093. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2094. }
  2095. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2096. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2097. Request req;
  2098. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2099. Response res;
  2100. res.set_header("Content-Type", "text/plain");
  2101. auto ret = detail::encoding_type(req, res);
  2102. EXPECT_TRUE(ret == detail::EncodingType::None);
  2103. }
  2104. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2105. // RFC 7231: Accept-Encoding values are case-insensitive
  2106. Request req;
  2107. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2108. Response res;
  2109. res.set_header("Content-Type", "text/plain");
  2110. auto ret = detail::encoding_type(req, res);
  2111. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2112. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2113. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2114. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2115. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2116. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2117. #else
  2118. EXPECT_TRUE(ret == detail::EncodingType::None);
  2119. #endif
  2120. }
  2121. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2122. // q value should determine priority, not hardcoded order
  2123. Request req;
  2124. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2125. Response res;
  2126. res.set_header("Content-Type", "text/plain");
  2127. auto ret = detail::encoding_type(req, res);
  2128. // gzip has highest q=1.0, so it should be selected even though
  2129. // br and zstd are also supported
  2130. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2131. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2132. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2133. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2134. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2135. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2136. #else
  2137. EXPECT_TRUE(ret == detail::EncodingType::None);
  2138. #endif
  2139. }
  2140. TEST(BufferStreamTest, read) {
  2141. detail::BufferStream strm1;
  2142. Stream &strm = strm1;
  2143. EXPECT_EQ(5, strm.write("hello"));
  2144. char buf[512];
  2145. EXPECT_EQ(2, strm.read(buf, 2));
  2146. EXPECT_EQ('h', buf[0]);
  2147. EXPECT_EQ('e', buf[1]);
  2148. EXPECT_EQ(2, strm.read(buf, 2));
  2149. EXPECT_EQ('l', buf[0]);
  2150. EXPECT_EQ('l', buf[1]);
  2151. EXPECT_EQ(1, strm.read(buf, 1));
  2152. EXPECT_EQ('o', buf[0]);
  2153. EXPECT_EQ(0, strm.read(buf, 1));
  2154. }
  2155. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2156. auto host = "www.httpwatch.com";
  2157. auto ip = hosted_at(host);
  2158. EXPECT_EQ("23.96.13.243", ip);
  2159. std::vector<std::string> addrs;
  2160. hosted_at(host, addrs);
  2161. EXPECT_EQ(1u, addrs.size());
  2162. }
  2163. #if 0 // It depends on each test environment...
  2164. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2165. auto host = "www.youtube.com";
  2166. std::vector<std::string> addrs;
  2167. hosted_at(host, addrs);
  2168. EXPECT_EQ(20u, addrs.size());
  2169. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2170. EXPECT_TRUE(it != addrs.end());
  2171. }
  2172. #endif
  2173. class ChunkedEncodingTest : public ::testing::Test {
  2174. protected:
  2175. ChunkedEncodingTest()
  2176. : cli_(HOST, PORT)
  2177. #ifdef CPPHTTPLIB_SSL_ENABLED
  2178. ,
  2179. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2180. #endif
  2181. {
  2182. cli_.set_connection_timeout(2);
  2183. #ifdef CPPHTTPLIB_SSL_ENABLED
  2184. cli_.enable_server_certificate_verification(false);
  2185. #endif
  2186. }
  2187. virtual void SetUp() {
  2188. read_file("./image.jpg", image_data_);
  2189. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2190. res.set_content("Hello World!", "text/plain");
  2191. });
  2192. svr_.Get(
  2193. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2194. res.set_chunked_content_provider(
  2195. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2196. size_t remaining = image_data_.size() - offset;
  2197. if (remaining == 0) {
  2198. sink.done();
  2199. } else {
  2200. constexpr size_t CHUNK_SIZE = 1024;
  2201. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2202. sink.write(&image_data_[offset], send_size);
  2203. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2204. }
  2205. return true;
  2206. });
  2207. });
  2208. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2209. svr_.wait_until_ready();
  2210. }
  2211. virtual void TearDown() {
  2212. svr_.stop();
  2213. if (!request_threads_.empty()) {
  2214. std::this_thread::sleep_for(std::chrono::seconds(1));
  2215. for (auto &t : request_threads_) {
  2216. t.join();
  2217. }
  2218. }
  2219. t_.join();
  2220. }
  2221. #ifdef CPPHTTPLIB_SSL_ENABLED
  2222. SSLClient cli_;
  2223. SSLServer svr_;
  2224. #else
  2225. Client cli_;
  2226. Server svr_;
  2227. #endif
  2228. thread t_;
  2229. std::vector<thread> request_threads_;
  2230. std::string image_data_;
  2231. };
  2232. TEST_F(ChunkedEncodingTest, NormalGet) {
  2233. auto res = cli_.Get("/chunked");
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. std::string out;
  2236. read_file("./image.jpg", out);
  2237. EXPECT_EQ(StatusCode::OK_200, res->status);
  2238. EXPECT_EQ(out, res->body);
  2239. }
  2240. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2241. std::string body;
  2242. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2243. body.append(data, data_length);
  2244. return true;
  2245. });
  2246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2247. std::string out;
  2248. read_file("./image.jpg", out);
  2249. EXPECT_EQ(StatusCode::OK_200, res->status);
  2250. EXPECT_EQ(out, body);
  2251. }
  2252. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2253. std::string body;
  2254. auto res = cli_.Get(
  2255. "/chunked",
  2256. [&](const Response &response) {
  2257. EXPECT_EQ(StatusCode::OK_200, response.status);
  2258. return true;
  2259. },
  2260. [&](const char *data, size_t data_length) {
  2261. body.append(data, data_length);
  2262. return true;
  2263. });
  2264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2265. std::string out;
  2266. read_file("./image.jpg", out);
  2267. EXPECT_EQ(StatusCode::OK_200, res->status);
  2268. EXPECT_EQ(out, body);
  2269. }
  2270. TEST(RangeTest, FromHTTPBin_Online) {
  2271. auto host = "httpbingo.org";
  2272. auto path = std::string{"/range/32"};
  2273. #ifdef CPPHTTPLIB_SSL_ENABLED
  2274. auto port = 443;
  2275. SSLClient cli(host, port);
  2276. #else
  2277. auto port = 80;
  2278. Client cli(host, port);
  2279. #endif
  2280. cli.set_connection_timeout(5);
  2281. {
  2282. auto res = cli.Get(path);
  2283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2284. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2285. EXPECT_EQ(StatusCode::OK_200, res->status);
  2286. }
  2287. {
  2288. Headers headers = {make_range_header({{1, -1}})};
  2289. auto res = cli.Get(path, headers);
  2290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2291. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2293. }
  2294. {
  2295. Headers headers = {make_range_header({{1, 10}})};
  2296. auto res = cli.Get(path, headers);
  2297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2298. EXPECT_EQ("bcdefghijk", res->body);
  2299. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2300. }
  2301. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2302. // entire resource, while the original httpbin returned 200. Both are
  2303. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2304. {
  2305. Headers headers = {make_range_header({{0, 31}})};
  2306. auto res = cli.Get(path, headers);
  2307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2308. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2309. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2310. res->status == StatusCode::PartialContent_206);
  2311. }
  2312. {
  2313. Headers headers = {make_range_header({{0, -1}})};
  2314. auto res = cli.Get(path, headers);
  2315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2316. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2317. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2318. res->status == StatusCode::PartialContent_206);
  2319. }
  2320. // go-httpbin returns 206 with clamped range for over-range requests,
  2321. // while the original httpbin returned 416. Both behaviors are observed
  2322. // in real servers, so we only verify the request succeeds.
  2323. {
  2324. Headers headers = {make_range_header({{0, 32}})};
  2325. auto res = cli.Get(path, headers);
  2326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2327. }
  2328. }
  2329. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2330. auto host = "unresolvableaddress.local";
  2331. auto path = std::string{"/"};
  2332. #ifdef CPPHTTPLIB_SSL_ENABLED
  2333. auto port = 443;
  2334. SSLClient cli(host, port);
  2335. #else
  2336. auto port = 80;
  2337. Client cli(host, port);
  2338. #endif
  2339. cli.set_connection_timeout(1);
  2340. {
  2341. auto res = cli.Get(path);
  2342. ASSERT_FALSE(res);
  2343. }
  2344. std::this_thread::sleep_for(std::chrono::seconds(8));
  2345. }
  2346. #if defined(__linux__) && defined(__GLIBC__) && \
  2347. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2348. // Forward declaration: in split builds split.py strips `inline` and moves the
  2349. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2350. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2351. // against the symbol in both header-only and split builds.
  2352. namespace httplib {
  2353. namespace detail {
  2354. int getaddrinfo_with_timeout(const char *node, const char *service,
  2355. const struct addrinfo *hints,
  2356. struct addrinfo **res, time_t timeout_sec);
  2357. } // namespace detail
  2358. } // namespace httplib
  2359. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2360. //
  2361. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2362. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2363. // gai_suspend() call hits the connection timeout the function calls
  2364. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2365. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2366. // still alive and still references the now-destroyed stack frame.
  2367. //
  2368. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2369. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2370. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2371. // and runs them in a container.
  2372. namespace {
  2373. bool should_run_issue_2431_tests() {
  2374. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2375. return v && *v && std::string(v) != "0";
  2376. }
  2377. std::string unique_unresolvable_host(int n) {
  2378. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2379. // glibc still asks the configured nameserver — which is exactly the path
  2380. // we want to exercise. A unique label per call avoids the resolver cache.
  2381. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2382. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2383. std::to_string(n) + ".invalid";
  2384. }
  2385. } // namespace
  2386. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2387. if (!should_run_issue_2431_tests()) {
  2388. GTEST_SKIP()
  2389. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2390. }
  2391. for (int i = 0; i < 8; ++i) {
  2392. struct addrinfo hints;
  2393. memset(&hints, 0, sizeof(hints));
  2394. hints.ai_family = AF_UNSPEC;
  2395. hints.ai_socktype = SOCK_STREAM;
  2396. auto host = unique_unresolvable_host(i);
  2397. struct addrinfo *result = nullptr;
  2398. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2399. &result, /*timeout_sec=*/1);
  2400. if (rc == 0 && result) { freeaddrinfo(result); }
  2401. }
  2402. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2403. // stack region they still believe holds their gaicb.
  2404. std::this_thread::sleep_for(std::chrono::seconds(3));
  2405. }
  2406. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2407. if (!should_run_issue_2431_tests()) {
  2408. GTEST_SKIP()
  2409. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2410. }
  2411. std::atomic<bool> stop{false};
  2412. std::vector<std::thread> threads;
  2413. for (int t = 0; t < 8; ++t) {
  2414. threads.emplace_back([t, &stop] {
  2415. int i = 0;
  2416. while (!stop.load(std::memory_order_relaxed)) {
  2417. struct addrinfo hints;
  2418. memset(&hints, 0, sizeof(hints));
  2419. hints.ai_family = AF_UNSPEC;
  2420. hints.ai_socktype = SOCK_STREAM;
  2421. auto host = unique_unresolvable_host(t * 100000 + i++);
  2422. struct addrinfo *result = nullptr;
  2423. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2424. &result, /*timeout_sec=*/1);
  2425. if (rc == 0 && result) { freeaddrinfo(result); }
  2426. }
  2427. });
  2428. }
  2429. std::this_thread::sleep_for(std::chrono::seconds(8));
  2430. stop.store(true, std::memory_order_relaxed);
  2431. for (auto &th : threads) {
  2432. th.join();
  2433. }
  2434. std::this_thread::sleep_for(std::chrono::seconds(3));
  2435. }
  2436. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2437. if (!should_run_issue_2431_tests()) {
  2438. GTEST_SKIP()
  2439. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2440. }
  2441. std::atomic<bool> stop{false};
  2442. std::vector<std::thread> threads;
  2443. for (int t = 0; t < 8; ++t) {
  2444. threads.emplace_back([t, &stop] {
  2445. int i = 0;
  2446. while (!stop.load(std::memory_order_relaxed)) {
  2447. auto host = unique_unresolvable_host(t * 100000 + i++);
  2448. Client cli(host, 80);
  2449. cli.set_connection_timeout(1, 0);
  2450. cli.set_read_timeout(1, 0);
  2451. cli.set_write_timeout(1, 0);
  2452. (void)cli.Get("/");
  2453. }
  2454. });
  2455. }
  2456. std::this_thread::sleep_for(std::chrono::seconds(8));
  2457. stop.store(true, std::memory_order_relaxed);
  2458. for (auto &th : threads) {
  2459. th.join();
  2460. }
  2461. std::this_thread::sleep_for(std::chrono::seconds(3));
  2462. }
  2463. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2464. TEST(ConnectionErrorTest, InvalidHost) {
  2465. auto host = "-abcde.com";
  2466. #ifdef CPPHTTPLIB_SSL_ENABLED
  2467. auto port = 443;
  2468. SSLClient cli(host, port);
  2469. #else
  2470. auto port = 80;
  2471. Client cli(host, port);
  2472. #endif
  2473. cli.set_connection_timeout(std::chrono::seconds(2));
  2474. auto res = cli.Get("/");
  2475. ASSERT_TRUE(!res);
  2476. EXPECT_EQ(Error::Connection, res.error());
  2477. }
  2478. TEST(ConnectionErrorTest, InvalidHost2) {
  2479. auto host = "httpcan.org/";
  2480. #ifdef CPPHTTPLIB_SSL_ENABLED
  2481. SSLClient cli(host);
  2482. #else
  2483. Client cli(host);
  2484. #endif
  2485. cli.set_connection_timeout(std::chrono::seconds(2));
  2486. auto res = cli.Get("/");
  2487. ASSERT_TRUE(!res);
  2488. EXPECT_EQ(Error::Connection, res.error());
  2489. }
  2490. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2491. auto host = "httpcan.org/";
  2492. #ifdef CPPHTTPLIB_SSL_ENABLED
  2493. SSLClient cli(host);
  2494. #else
  2495. Client cli(host);
  2496. #endif
  2497. cli.set_connection_timeout(std::chrono::seconds(2));
  2498. auto res = cli.Get("/");
  2499. ASSERT_TRUE(!res);
  2500. stringstream s;
  2501. s << "error code: " << res.error();
  2502. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2503. }
  2504. TEST(ConnectionErrorTest, InvalidPort) {
  2505. auto host = "localhost";
  2506. auto port = 44380;
  2507. #ifdef CPPHTTPLIB_SSL_ENABLED
  2508. SSLClient cli(host, port);
  2509. #else
  2510. Client cli(host, port);
  2511. #endif
  2512. cli.set_connection_timeout(std::chrono::seconds(2));
  2513. auto res = cli.Get("/");
  2514. ASSERT_TRUE(!res);
  2515. EXPECT_TRUE(Error::Connection == res.error() ||
  2516. Error::ConnectionTimeout == res.error());
  2517. }
  2518. TEST(ConnectionErrorTest, Timeout_Online) {
  2519. auto host = "google.com";
  2520. #ifdef CPPHTTPLIB_SSL_ENABLED
  2521. auto port = 44380;
  2522. SSLClient cli(host, port);
  2523. #else
  2524. auto port = 8080;
  2525. Client cli(host, port);
  2526. #endif
  2527. cli.set_connection_timeout(std::chrono::seconds(2));
  2528. // only probe one address type so that the error reason
  2529. // correlates to the timed-out IPv4, not the unsupported
  2530. // IPv6 connection attempt
  2531. cli.set_address_family(AF_INET);
  2532. auto res = cli.Get("/");
  2533. ASSERT_TRUE(!res);
  2534. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2535. }
  2536. TEST(CancelTest, NoCancel_Online) {
  2537. auto host = "httpbingo.org";
  2538. auto path = std::string{"/range/32"};
  2539. #ifdef CPPHTTPLIB_SSL_ENABLED
  2540. auto port = 443;
  2541. SSLClient cli(host, port);
  2542. #else
  2543. auto port = 80;
  2544. Client cli(host, port);
  2545. #endif
  2546. cli.set_connection_timeout(std::chrono::seconds(5));
  2547. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2549. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2550. EXPECT_EQ(StatusCode::OK_200, res->status);
  2551. }
  2552. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2553. // Use /bytes with a large payload so that the DownloadProgress callback
  2554. // (which only fires for Content-Length responses) is invoked before the
  2555. // entire body is received, giving cancellation a chance to fire.
  2556. auto host = "httpbingo.org";
  2557. auto path = std::string{"/bytes/524288"};
  2558. #ifdef CPPHTTPLIB_SSL_ENABLED
  2559. auto port = 443;
  2560. SSLClient cli(host, port);
  2561. #else
  2562. auto port = 80;
  2563. Client cli(host, port);
  2564. #endif
  2565. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2566. cli.set_connection_timeout(std::chrono::seconds(5));
  2567. ASSERT_TRUE(!res);
  2568. EXPECT_EQ(Error::Canceled, res.error());
  2569. }
  2570. TEST(CancelTest, WithCancelLargePayload_Online) {
  2571. auto host = "httpbingo.org";
  2572. auto path = std::string{"/bytes/524288"};
  2573. #ifdef CPPHTTPLIB_SSL_ENABLED
  2574. auto port = 443;
  2575. SSLClient cli(host, port);
  2576. #else
  2577. auto port = 80;
  2578. Client cli(host, port);
  2579. #endif
  2580. cli.set_connection_timeout(std::chrono::seconds(5));
  2581. uint32_t count = 0;
  2582. auto res =
  2583. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2584. ASSERT_TRUE(!res);
  2585. EXPECT_EQ(Error::Canceled, res.error());
  2586. }
  2587. TEST(CancelTest, NoCancelPost) {
  2588. Server svr;
  2589. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2590. res.set_content("Hello World!", "text/plain");
  2591. });
  2592. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2593. auto se = detail::scope_exit([&] {
  2594. svr.stop();
  2595. thread.join();
  2596. ASSERT_FALSE(svr.is_running());
  2597. });
  2598. svr.wait_until_ready();
  2599. Client cli(HOST, PORT);
  2600. cli.set_connection_timeout(std::chrono::seconds(5));
  2601. auto res =
  2602. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2603. "application/json", [](uint64_t, uint64_t) { return true; });
  2604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2605. EXPECT_EQ("Hello World!", res->body);
  2606. EXPECT_EQ(StatusCode::OK_200, res->status);
  2607. }
  2608. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2609. Server svr;
  2610. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2611. res.set_content("Hello World!", "text/plain");
  2612. });
  2613. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2614. auto se = detail::scope_exit([&] {
  2615. svr.stop();
  2616. thread.join();
  2617. ASSERT_FALSE(svr.is_running());
  2618. });
  2619. svr.wait_until_ready();
  2620. Client cli(HOST, PORT);
  2621. cli.set_connection_timeout(std::chrono::seconds(5));
  2622. auto res =
  2623. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2624. "application/json", [](uint64_t, uint64_t) { return false; });
  2625. ASSERT_TRUE(!res);
  2626. EXPECT_EQ(Error::Canceled, res.error());
  2627. }
  2628. TEST(CancelTest, WithCancelLargePayloadPost) {
  2629. Server svr;
  2630. svr.set_payload_max_length(200 * 1024 * 1024);
  2631. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2632. res.set_content(LARGE_DATA, "text/plain");
  2633. });
  2634. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2635. auto se = detail::scope_exit([&] {
  2636. svr.stop();
  2637. thread.join();
  2638. ASSERT_FALSE(svr.is_running());
  2639. });
  2640. svr.wait_until_ready();
  2641. Client cli(HOST, PORT);
  2642. cli.set_payload_max_length(200 * 1024 * 1024);
  2643. cli.set_connection_timeout(std::chrono::seconds(5));
  2644. auto res =
  2645. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2646. "application/json", [](uint64_t, uint64_t) { return false; });
  2647. ASSERT_TRUE(!res);
  2648. EXPECT_EQ(Error::Canceled, res.error());
  2649. }
  2650. TEST(CancelTest, NoCancelPut) {
  2651. Server svr;
  2652. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2653. res.set_content("Hello World!", "text/plain");
  2654. });
  2655. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2656. auto se = detail::scope_exit([&] {
  2657. svr.stop();
  2658. thread.join();
  2659. ASSERT_FALSE(svr.is_running());
  2660. });
  2661. svr.wait_until_ready();
  2662. Client cli(HOST, PORT);
  2663. cli.set_connection_timeout(std::chrono::seconds(5));
  2664. auto res =
  2665. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2666. "application/json", [](uint64_t, uint64_t) { return true; });
  2667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2668. EXPECT_EQ("Hello World!", res->body);
  2669. EXPECT_EQ(StatusCode::OK_200, res->status);
  2670. }
  2671. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2672. Server svr;
  2673. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2674. res.set_content("Hello World!", "text/plain");
  2675. });
  2676. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2677. auto se = detail::scope_exit([&] {
  2678. svr.stop();
  2679. thread.join();
  2680. ASSERT_FALSE(svr.is_running());
  2681. });
  2682. svr.wait_until_ready();
  2683. Client cli(HOST, PORT);
  2684. cli.set_connection_timeout(std::chrono::seconds(5));
  2685. auto res =
  2686. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2687. "application/json", [](uint64_t, uint64_t) { return false; });
  2688. ASSERT_TRUE(!res);
  2689. EXPECT_EQ(Error::Canceled, res.error());
  2690. }
  2691. TEST(CancelTest, WithCancelLargePayloadPut) {
  2692. Server svr;
  2693. svr.set_payload_max_length(200 * 1024 * 1024);
  2694. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2695. res.set_content(LARGE_DATA, "text/plain");
  2696. });
  2697. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2698. auto se = detail::scope_exit([&] {
  2699. svr.stop();
  2700. thread.join();
  2701. ASSERT_FALSE(svr.is_running());
  2702. });
  2703. svr.wait_until_ready();
  2704. Client cli(HOST, PORT);
  2705. cli.set_payload_max_length(200 * 1024 * 1024);
  2706. cli.set_connection_timeout(std::chrono::seconds(5));
  2707. auto res =
  2708. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2709. "application/json", [](uint64_t, uint64_t) { return false; });
  2710. ASSERT_TRUE(!res);
  2711. EXPECT_EQ(Error::Canceled, res.error());
  2712. }
  2713. TEST(CancelTest, NoCancelPatch) {
  2714. Server svr;
  2715. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2716. res.set_content("Hello World!", "text/plain");
  2717. });
  2718. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2719. auto se = detail::scope_exit([&] {
  2720. svr.stop();
  2721. thread.join();
  2722. ASSERT_FALSE(svr.is_running());
  2723. });
  2724. svr.wait_until_ready();
  2725. Client cli(HOST, PORT);
  2726. cli.set_connection_timeout(std::chrono::seconds(5));
  2727. auto res =
  2728. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2729. "application/json", [](uint64_t, uint64_t) { return true; });
  2730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2731. EXPECT_EQ("Hello World!", res->body);
  2732. EXPECT_EQ(StatusCode::OK_200, res->status);
  2733. }
  2734. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2735. Server svr;
  2736. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2737. res.set_content("Hello World!", "text/plain");
  2738. });
  2739. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2740. auto se = detail::scope_exit([&] {
  2741. svr.stop();
  2742. thread.join();
  2743. ASSERT_FALSE(svr.is_running());
  2744. });
  2745. svr.wait_until_ready();
  2746. Client cli(HOST, PORT);
  2747. cli.set_connection_timeout(std::chrono::seconds(5));
  2748. auto res =
  2749. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2750. "application/json", [](uint64_t, uint64_t) { return false; });
  2751. ASSERT_TRUE(!res);
  2752. EXPECT_EQ(Error::Canceled, res.error());
  2753. }
  2754. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2755. Server svr;
  2756. svr.set_payload_max_length(200 * 1024 * 1024);
  2757. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2758. res.set_content(LARGE_DATA, "text/plain");
  2759. });
  2760. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2761. auto se = detail::scope_exit([&] {
  2762. svr.stop();
  2763. thread.join();
  2764. ASSERT_FALSE(svr.is_running());
  2765. });
  2766. svr.wait_until_ready();
  2767. Client cli(HOST, PORT);
  2768. cli.set_payload_max_length(200 * 1024 * 1024);
  2769. cli.set_connection_timeout(std::chrono::seconds(5));
  2770. auto res =
  2771. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2772. "application/json", [](uint64_t, uint64_t) { return false; });
  2773. ASSERT_TRUE(!res);
  2774. EXPECT_EQ(Error::Canceled, res.error());
  2775. }
  2776. TEST(CancelTest, NoCancelDelete) {
  2777. Server svr;
  2778. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2779. res.set_content("Hello World!", "text/plain");
  2780. });
  2781. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2782. auto se = detail::scope_exit([&] {
  2783. svr.stop();
  2784. thread.join();
  2785. ASSERT_FALSE(svr.is_running());
  2786. });
  2787. svr.wait_until_ready();
  2788. Client cli(HOST, PORT);
  2789. cli.set_connection_timeout(std::chrono::seconds(5));
  2790. auto res =
  2791. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2792. "application/json", [](uint64_t, uint64_t) { return true; });
  2793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2794. EXPECT_EQ("Hello World!", res->body);
  2795. EXPECT_EQ(StatusCode::OK_200, res->status);
  2796. }
  2797. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2798. Server svr;
  2799. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2800. res.set_content("Hello World!", "text/plain");
  2801. });
  2802. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2803. auto se = detail::scope_exit([&] {
  2804. svr.stop();
  2805. thread.join();
  2806. ASSERT_FALSE(svr.is_running());
  2807. });
  2808. svr.wait_until_ready();
  2809. Client cli(HOST, PORT);
  2810. cli.set_connection_timeout(std::chrono::seconds(5));
  2811. auto res =
  2812. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2813. "application/json", [](uint64_t, uint64_t) { return false; });
  2814. ASSERT_TRUE(!res);
  2815. EXPECT_EQ(Error::Canceled, res.error());
  2816. }
  2817. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2818. Server svr;
  2819. svr.set_payload_max_length(200 * 1024 * 1024);
  2820. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2821. res.set_content(LARGE_DATA, "text/plain");
  2822. });
  2823. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2824. auto se = detail::scope_exit([&] {
  2825. svr.stop();
  2826. thread.join();
  2827. ASSERT_FALSE(svr.is_running());
  2828. });
  2829. svr.wait_until_ready();
  2830. Client cli(HOST, PORT);
  2831. cli.set_payload_max_length(200 * 1024 * 1024);
  2832. cli.set_connection_timeout(std::chrono::seconds(5));
  2833. auto res =
  2834. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2835. "application/json", [](uint64_t, uint64_t) { return false; });
  2836. ASSERT_TRUE(!res);
  2837. EXPECT_EQ(Error::Canceled, res.error());
  2838. }
  2839. static std::string remove_whitespace(const std::string &input) {
  2840. std::string output;
  2841. output.reserve(input.size());
  2842. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2843. [](unsigned char c) { return !std::isspace(c); });
  2844. return output;
  2845. }
  2846. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2847. auto host = "httpbingo.org";
  2848. auto path = std::string{"/basic-auth/hello/world"};
  2849. #ifdef CPPHTTPLIB_SSL_ENABLED
  2850. auto port = 443;
  2851. SSLClient cli(host, port);
  2852. #else
  2853. auto port = 80;
  2854. Client cli(host, port);
  2855. #endif
  2856. {
  2857. auto res = cli.Get(path);
  2858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2859. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2860. }
  2861. {
  2862. auto res = cli.Get(
  2863. path, Headers{make_basic_authentication_header("hello", "world")});
  2864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2865. auto body = remove_whitespace(res->body);
  2866. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2867. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2868. EXPECT_EQ(StatusCode::OK_200, res->status);
  2869. }
  2870. {
  2871. cli.set_basic_auth("hello", "world");
  2872. auto res = cli.Get(path);
  2873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2874. auto body = remove_whitespace(res->body);
  2875. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2876. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2877. EXPECT_EQ(StatusCode::OK_200, res->status);
  2878. }
  2879. {
  2880. cli.set_basic_auth("hello", "bad");
  2881. auto res = cli.Get(path);
  2882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2883. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2884. }
  2885. {
  2886. cli.set_basic_auth("bad", "world");
  2887. auto res = cli.Get(path);
  2888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2889. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2890. }
  2891. }
  2892. #ifdef CPPHTTPLIB_SSL_ENABLED
  2893. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2894. auto host = "httpbingo.org";
  2895. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2896. auto paths = std::vector<std::string>{
  2897. "/digest-auth/auth/hello/world/MD5",
  2898. "/digest-auth/auth/hello/world/SHA-256",
  2899. };
  2900. auto port = 443;
  2901. SSLClient cli(host, port);
  2902. {
  2903. auto res = cli.Get(unauth_path);
  2904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2905. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2906. }
  2907. {
  2908. cli.set_digest_auth("hello", "world");
  2909. for (const auto &path : paths) {
  2910. auto res = cli.Get(path.c_str());
  2911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2912. auto body = remove_whitespace(res->body);
  2913. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2914. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2915. EXPECT_EQ(StatusCode::OK_200, res->status);
  2916. }
  2917. cli.set_digest_auth("hello", "bad");
  2918. for (const auto &path : paths) {
  2919. auto res = cli.Get(path.c_str());
  2920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2921. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2922. }
  2923. }
  2924. }
  2925. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2926. // comma-separated list of challenges, and each challenge may itself carry a
  2927. // comma-separated auth-param list, so a server can legally offer Basic
  2928. // before Digest, either as two field lines or packed into one. Runs one 401
  2929. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2930. // value() joins them in receipt order) and checks that the retry carries a
  2931. // well-formed Digest Authorization header naming expected_realm.
  2932. static void
  2933. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2934. const std::string &expected_realm) {
  2935. std::atomic<int> hits{0};
  2936. Server svr;
  2937. svr.Get("/x", [&](const Request &req, Response &res) {
  2938. if (++hits == 1) {
  2939. res.status = StatusCode::Unauthorized_401;
  2940. for (const auto &challenge : challenges) {
  2941. res.set_header("WWW-Authenticate", challenge);
  2942. }
  2943. } else {
  2944. auto authorization = req.get_header_value("Authorization");
  2945. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2946. EXPECT_NE(std::string::npos,
  2947. authorization.find("realm=\"" + expected_realm + "\""));
  2948. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2949. res.set_content("ok", "text/plain");
  2950. }
  2951. });
  2952. auto port = svr.bind_to_any_port(HOST);
  2953. std::thread t([&]() { svr.listen_after_bind(); });
  2954. auto se = detail::scope_exit([&] {
  2955. svr.stop();
  2956. t.join();
  2957. });
  2958. svr.wait_until_ready();
  2959. Client cli(HOST, port);
  2960. cli.set_digest_auth("hello", "world");
  2961. auto res = cli.Get("/x");
  2962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2963. EXPECT_EQ(2, hits.load());
  2964. }
  2965. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2966. static const char *kDigestChallenge =
  2967. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2968. "algorithm=MD5";
  2969. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2970. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2971. "testrealm");
  2972. }
  2973. // Same challenge list with the schemes in the opposite order, to make sure
  2974. // the fix above didn't just special-case "Basic first".
  2975. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2976. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2977. "testrealm");
  2978. }
  2979. // A comma inside a quoted auth-param value must not be mistaken for the
  2980. // separator between two challenges (or two auth-params).
  2981. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2982. run_digest_challenge_list_test(
  2983. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2984. "algorithm=MD5"},
  2985. "test,realm");
  2986. }
  2987. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2988. // the params and leaves out the fragment.
  2989. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2990. Server svr;
  2991. std::string uri, target;
  2992. svr.Get("/a b", [&](const Request &req, Response &res) {
  2993. auto auth = req.get_header_value("Authorization");
  2994. if (auth.empty()) {
  2995. res.status = StatusCode::Unauthorized_401;
  2996. res.set_header("WWW-Authenticate",
  2997. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2998. return;
  2999. }
  3000. auto b = auth.find("uri=\"") + 5;
  3001. uri = auth.substr(b, auth.find('"', b) - b);
  3002. target = req.target;
  3003. });
  3004. auto port = svr.bind_to_any_port(HOST);
  3005. std::thread t([&]() { svr.listen_after_bind(); });
  3006. auto se = detail::scope_exit([&] {
  3007. svr.stop();
  3008. t.join();
  3009. });
  3010. svr.wait_until_ready();
  3011. Client cli(HOST, port);
  3012. cli.set_digest_auth("hello", "world");
  3013. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3015. EXPECT_EQ("/a%20b?x=1", target);
  3016. EXPECT_EQ(target, uri);
  3017. }
  3018. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3019. // make_digest_authentication_header() dereferences both unconditionally, so
  3020. // a server sending a challenge missing either one must not be treated as
  3021. // usable -- doing so used to crash the client with std::out_of_range.
  3022. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3023. Server svr;
  3024. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3025. res.status = StatusCode::Unauthorized_401;
  3026. res.set_header("WWW-Authenticate", challenge);
  3027. });
  3028. auto port = svr.bind_to_any_port(HOST);
  3029. std::thread t([&]() { svr.listen_after_bind(); });
  3030. auto se = detail::scope_exit([&] {
  3031. svr.stop();
  3032. t.join();
  3033. });
  3034. svr.wait_until_ready();
  3035. Client cli(HOST, port);
  3036. cli.set_digest_auth("hello", "world");
  3037. auto res = cli.Get("/x");
  3038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3039. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3040. }
  3041. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3042. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3043. }
  3044. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3045. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3046. }
  3047. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3048. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3049. }
  3050. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3051. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3052. // when storing the values, so the header builder has to re-escape them (and
  3053. // keep algorithm a bare token); otherwise the value breaks out of its
  3054. // quoted-string and injects extra auth-params into the client's Authorization.
  3055. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3056. std::atomic<int> hits{0};
  3057. std::string authorization;
  3058. Server svr;
  3059. svr.Get("/x", [&](const Request &req, Response &res) {
  3060. if (++hits == 1) {
  3061. res.status = StatusCode::Unauthorized_401;
  3062. // On the wire the quotes embedded in the values are backslash-escaped.
  3063. res.set_header("WWW-Authenticate",
  3064. "Digest realm=\"testrealm\", "
  3065. "nonce=\"n\\\"; injected=\\\"x\", "
  3066. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3067. } else {
  3068. authorization = req.get_header_value("Authorization");
  3069. res.set_content("ok", "text/plain");
  3070. }
  3071. });
  3072. auto port = svr.bind_to_any_port(HOST);
  3073. std::thread t([&]() { svr.listen_after_bind(); });
  3074. auto se = detail::scope_exit([&] {
  3075. svr.stop();
  3076. t.join();
  3077. });
  3078. svr.wait_until_ready();
  3079. Client cli(HOST, port);
  3080. cli.set_digest_auth("hello", "world");
  3081. auto res = cli.Get("/x");
  3082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3083. EXPECT_EQ(2, hits.load());
  3084. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3085. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3086. // inside its quoted-string rather than starting an "injected" auth-param.
  3087. EXPECT_NE(std::string::npos,
  3088. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3089. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3090. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3091. }
  3092. #endif
  3093. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3094. auto host = "google.com";
  3095. auto another_host = "example.com";
  3096. auto wrong_ip = "0.0.0.0";
  3097. #ifdef CPPHTTPLIB_SSL_ENABLED
  3098. SSLClient cli(host);
  3099. #else
  3100. Client cli(host);
  3101. #endif
  3102. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3103. auto res = cli.Get("/");
  3104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3105. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3106. }
  3107. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3108. auto host = "google.com";
  3109. auto wrong_ip = "0.0.0.0";
  3110. #ifdef CPPHTTPLIB_SSL_ENABLED
  3111. SSLClient cli(host);
  3112. #else
  3113. Client cli(host);
  3114. #endif
  3115. cli.set_hostname_addr_map({{host, wrong_ip}});
  3116. auto res = cli.Get("/");
  3117. ASSERT_TRUE(!res);
  3118. EXPECT_EQ(Error::Connection, res.error());
  3119. }
  3120. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3121. // A mapped value that is not an IP literal must be resolved. "localhost"
  3122. // resolves from the hosts file, so this test needs no external DNS.
  3123. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3124. auto host = "target.invalid";
  3125. Server svr;
  3126. std::string received_host;
  3127. svr.Get("/hi", [&](const Request &req, Response &res) {
  3128. received_host = req.get_header_value("Host");
  3129. res.set_content("Hello World!", "text/plain");
  3130. });
  3131. auto port = svr.bind_to_any_port(HOST);
  3132. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3133. auto se = detail::scope_exit([&] {
  3134. svr.stop();
  3135. thread.join();
  3136. ASSERT_FALSE(svr.is_running());
  3137. });
  3138. svr.wait_until_ready();
  3139. Client cli(host, port);
  3140. cli.set_hostname_addr_map({{host, HOST}});
  3141. auto res = cli.Get("/hi");
  3142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3143. EXPECT_EQ(StatusCode::OK_200, res->status);
  3144. // The mapping only redirects the connection; the identity stays host_.
  3145. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3146. }
  3147. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3148. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3149. auto host = "target.invalid";
  3150. Server svr;
  3151. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3152. res.set_content("Hello World!", "text/plain");
  3153. });
  3154. auto port = svr.bind_to_any_port("127.0.0.1");
  3155. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3156. auto se = detail::scope_exit([&] {
  3157. svr.stop();
  3158. thread.join();
  3159. ASSERT_FALSE(svr.is_running());
  3160. });
  3161. svr.wait_until_ready();
  3162. Client cli(host, port);
  3163. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3164. auto res = cli.Get("/hi");
  3165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3166. EXPECT_EQ(StatusCode::OK_200, res->status);
  3167. }
  3168. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3169. // An empty mapped value must leave host_ as the connection target. Without
  3170. // that guard the empty value would become the host argument, getaddrinfo
  3171. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3172. // loopback - silently connecting somewhere the caller never asked for.
  3173. // The server listens on loopback, so such a fallback would succeed and is
  3174. // therefore observable as a failure of this test.
  3175. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3176. Server svr;
  3177. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3178. res.set_content("Hello World!", "text/plain");
  3179. });
  3180. auto port = svr.bind_to_any_port(HOST);
  3181. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3182. auto se = detail::scope_exit([&] {
  3183. svr.stop();
  3184. thread.join();
  3185. ASSERT_FALSE(svr.is_running());
  3186. });
  3187. svr.wait_until_ready();
  3188. Client cli(blackhole, port);
  3189. cli.set_hostname_addr_map({{blackhole, ""}});
  3190. cli.set_connection_timeout(1);
  3191. auto res = cli.Get("/hi");
  3192. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3193. }
  3194. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3195. auto host = "httpbingo.org";
  3196. auto path = std::string{"/absolute-redirect/3"};
  3197. #ifdef CPPHTTPLIB_SSL_ENABLED
  3198. SSLClient cli(host);
  3199. #else
  3200. Client cli(host);
  3201. #endif
  3202. cli.set_follow_location(true);
  3203. auto res = cli.Get(path);
  3204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3205. EXPECT_EQ(StatusCode::OK_200, res->status);
  3206. }
  3207. TEST(RedirectTest, Redirect_Online) {
  3208. auto host = "httpbingo.org";
  3209. auto path = std::string{"/redirect/3"};
  3210. #ifdef CPPHTTPLIB_SSL_ENABLED
  3211. SSLClient cli(host);
  3212. #else
  3213. Client cli(host);
  3214. #endif
  3215. cli.set_follow_location(true);
  3216. auto res = cli.Get(path);
  3217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3218. EXPECT_EQ(StatusCode::OK_200, res->status);
  3219. }
  3220. TEST(RelativeRedirectTest, Redirect_Online) {
  3221. auto host = "httpbingo.org";
  3222. auto path = std::string{"/relative-redirect/3"};
  3223. #ifdef CPPHTTPLIB_SSL_ENABLED
  3224. SSLClient cli(host);
  3225. #else
  3226. Client cli(host);
  3227. #endif
  3228. cli.set_follow_location(true);
  3229. auto res = cli.Get(path);
  3230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3231. EXPECT_EQ(StatusCode::OK_200, res->status);
  3232. }
  3233. TEST(TooManyRedirectTest, Redirect_Online) {
  3234. auto host = "httpbingo.org";
  3235. auto path = std::string{"/redirect/21"};
  3236. #ifdef CPPHTTPLIB_SSL_ENABLED
  3237. SSLClient cli(host);
  3238. #else
  3239. Client cli(host);
  3240. #endif
  3241. cli.set_follow_location(true);
  3242. auto res = cli.Get(path);
  3243. ASSERT_TRUE(!res);
  3244. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3245. }
  3246. #ifdef CPPHTTPLIB_SSL_ENABLED
  3247. TEST(YahooRedirectTest, Redirect_Online) {
  3248. Client cli("yahoo.com");
  3249. auto res = cli.Get("/");
  3250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3251. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3252. cli.set_follow_location(true);
  3253. res = cli.Get("/");
  3254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3255. EXPECT_EQ(StatusCode::OK_200, res->status);
  3256. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3257. }
  3258. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3259. #define REDIR_HOST "httpbingo.org"
  3260. #define REDIR_PATH "/redirect-to"
  3261. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3262. SSLClient cli(REDIR_HOST);
  3263. cli.set_follow_location(true);
  3264. auto res =
  3265. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3267. EXPECT_EQ(StatusCode::OK_200, res->status);
  3268. }
  3269. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3270. SSLClient cli(REDIR_HOST);
  3271. cli.set_follow_location(true);
  3272. Params params;
  3273. params.emplace("url", "http://example.com");
  3274. params.emplace("status_code", "302");
  3275. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. EXPECT_EQ(StatusCode::OK_200, res->status);
  3278. }
  3279. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3280. SSLClient cli(REDIR_HOST);
  3281. cli.set_follow_location(true);
  3282. Params params;
  3283. params.emplace("url", "http://example.com");
  3284. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3286. EXPECT_EQ(StatusCode::OK_200, res->status);
  3287. }
  3288. TEST(UrlWithSpace, Redirect_Online) {
  3289. SSLClient cli("edge.forgecdn.net");
  3290. cli.set_follow_location(true);
  3291. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3293. EXPECT_EQ(StatusCode::OK_200, res->status);
  3294. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3295. }
  3296. #endif
  3297. #if !defined(_WIN32) && !defined(_WIN64)
  3298. TEST(ReceiveSignals, Signal) {
  3299. auto setupSignalHandlers = []() {
  3300. struct sigaction act;
  3301. sigemptyset(&act.sa_mask);
  3302. act.sa_flags = SA_SIGINFO;
  3303. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3304. switch (sig) {
  3305. case SIGINT:
  3306. default: break;
  3307. }
  3308. };
  3309. ::sigaction(SIGINT, &act, nullptr);
  3310. };
  3311. Server svr;
  3312. int port = 0;
  3313. auto thread = std::thread([&]() {
  3314. setupSignalHandlers();
  3315. port = svr.bind_to_any_port(HOST);
  3316. svr.listen_after_bind();
  3317. });
  3318. auto se = detail::scope_exit([&] {
  3319. svr.stop();
  3320. thread.join();
  3321. ASSERT_FALSE(svr.is_running());
  3322. });
  3323. svr.wait_until_ready();
  3324. ASSERT_TRUE(svr.is_running());
  3325. pthread_kill(thread.native_handle(), SIGINT);
  3326. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3327. ASSERT_TRUE(svr.is_running());
  3328. }
  3329. #endif
  3330. TEST(RedirectToDifferentPort, Redirect) {
  3331. Server svr1;
  3332. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3333. res.set_content("Hello World!", "text/plain");
  3334. });
  3335. int svr1_port = 0;
  3336. auto thread1 = std::thread([&]() {
  3337. svr1_port = svr1.bind_to_any_port(HOST);
  3338. svr1.listen_after_bind();
  3339. });
  3340. Server svr2;
  3341. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3342. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3343. });
  3344. int svr2_port = 0;
  3345. auto thread2 = std::thread([&]() {
  3346. svr2_port = svr2.bind_to_any_port(HOST);
  3347. svr2.listen_after_bind();
  3348. });
  3349. auto se = detail::scope_exit([&] {
  3350. svr2.stop();
  3351. thread2.join();
  3352. svr1.stop();
  3353. thread1.join();
  3354. ASSERT_FALSE(svr2.is_running());
  3355. ASSERT_FALSE(svr1.is_running());
  3356. });
  3357. svr1.wait_until_ready();
  3358. svr2.wait_until_ready();
  3359. Client cli("localhost", svr2_port);
  3360. cli.set_follow_location(true);
  3361. auto res = cli.Get("/2");
  3362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3363. EXPECT_EQ(StatusCode::OK_200, res->status);
  3364. EXPECT_EQ("Hello World!", res->body);
  3365. }
  3366. // GET /redir on one server redirects to /target on another port, so the
  3367. // client follows it with a new client.
  3368. static Result
  3369. GetThroughRedirectToDifferentPort(Server::Handler target,
  3370. const std::function<void(Client &)> &setup,
  3371. const Headers &headers = Headers()) {
  3372. Server target_svr;
  3373. target_svr.Get("/target", target);
  3374. int target_port = 0;
  3375. auto target_thread = std::thread([&]() {
  3376. target_port = target_svr.bind_to_any_port(HOST);
  3377. target_svr.listen_after_bind();
  3378. });
  3379. Server origin_svr;
  3380. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3381. res.set_redirect(
  3382. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3383. });
  3384. int origin_port = 0;
  3385. auto origin_thread = std::thread([&]() {
  3386. origin_port = origin_svr.bind_to_any_port(HOST);
  3387. origin_svr.listen_after_bind();
  3388. });
  3389. auto se = detail::scope_exit([&] {
  3390. origin_svr.stop();
  3391. origin_thread.join();
  3392. target_svr.stop();
  3393. target_thread.join();
  3394. });
  3395. target_svr.wait_until_ready();
  3396. origin_svr.wait_until_ready();
  3397. Client cli("localhost", origin_port);
  3398. cli.set_follow_location(true);
  3399. setup(cli);
  3400. return cli.Get("/redir", headers);
  3401. }
  3402. static void
  3403. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3404. std::string captured_authorization;
  3405. auto result = GetThroughRedirectToDifferentPort(
  3406. [&](const Request &req, Response &res) {
  3407. captured_authorization = req.get_header_value("Authorization");
  3408. res.set_content("OK", "text/plain");
  3409. },
  3410. set_auth);
  3411. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3412. EXPECT_EQ(StatusCode::OK_200, result->status);
  3413. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3414. EXPECT_TRUE(captured_authorization.empty());
  3415. }
  3416. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3417. TestDoNotForwardCredentialsOnRedirect(
  3418. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3419. }
  3420. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3421. TestDoNotForwardCredentialsOnRedirect(
  3422. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3423. }
  3424. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3425. std::string captured_cookie;
  3426. auto result = GetThroughRedirectToDifferentPort(
  3427. [&](const Request &req, Response &res) {
  3428. captured_cookie = req.get_header_value("Cookie");
  3429. res.set_content("OK", "text/plain");
  3430. },
  3431. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3432. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3433. EXPECT_EQ(StatusCode::OK_200, result->status);
  3434. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3435. EXPECT_TRUE(captured_cookie.empty());
  3436. }
  3437. TEST(RedirectToSamePort, ForwardCookie) {
  3438. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3439. // header so that ordinary session flows keep working.
  3440. Server svr;
  3441. std::string captured_cookie;
  3442. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3443. res.set_redirect("/target", 302);
  3444. });
  3445. svr.Get("/target", [&](const Request &req, Response &res) {
  3446. captured_cookie = req.get_header_value("Cookie");
  3447. res.set_content("OK", "text/plain");
  3448. });
  3449. auto port = svr.bind_to_any_port(HOST);
  3450. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3451. auto se = detail::scope_exit([&] {
  3452. svr.stop();
  3453. thread.join();
  3454. ASSERT_FALSE(svr.is_running());
  3455. });
  3456. svr.wait_until_ready();
  3457. Client cli(HOST, port);
  3458. cli.set_follow_location(true);
  3459. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3460. auto res = cli.Get("/redir", headers);
  3461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3462. EXPECT_EQ(StatusCode::OK_200, res->status);
  3463. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3464. }
  3465. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3466. std::string authorization;
  3467. std::string trace_id;
  3468. auto result = GetThroughRedirectToDifferentPort(
  3469. [&](const Request &req, Response &res) {
  3470. authorization = req.get_header_value("Authorization");
  3471. trace_id = req.get_header_value("X-Trace-Id");
  3472. res.set_content("OK", "text/plain");
  3473. },
  3474. [](Client &cli) {
  3475. cli.set_default_headers(
  3476. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3477. });
  3478. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3479. EXPECT_EQ(StatusCode::OK_200, result->status);
  3480. // Like a header given with the request, a default one goes along unless it
  3481. // carries credentials (RFC 9110 15.4).
  3482. EXPECT_TRUE(authorization.empty());
  3483. EXPECT_EQ("42", trace_id);
  3484. }
  3485. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3486. auto result = GetThroughRedirectToDifferentPort(
  3487. [](const Request &, Response &res) {
  3488. res.set_content(std::string(2048, 'x'), "text/plain");
  3489. },
  3490. [](Client &cli) { cli.set_payload_max_length(1024); });
  3491. EXPECT_FALSE(result);
  3492. }
  3493. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3494. auto result = GetThroughRedirectToDifferentPort(
  3495. [](const Request &req, Response &res) {
  3496. // Answer after a second, or once the client gives up.
  3497. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3498. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3499. }
  3500. res.set_content("late", "text/plain");
  3501. },
  3502. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3503. ASSERT_FALSE(result);
  3504. EXPECT_EQ(Error::Read, result.error());
  3505. }
  3506. #ifdef CPPHTTPLIB_SSL_ENABLED
  3507. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3508. auto result = GetThroughRedirectToDifferentPort(
  3509. [](const Request &, Response &res) {
  3510. res.status = StatusCode::Unauthorized_401;
  3511. res.set_header("WWW-Authenticate",
  3512. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3513. },
  3514. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3515. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3516. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3517. }
  3518. #endif
  3519. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3520. Server svr;
  3521. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3522. // Port number that overflows int — should not crash
  3523. res.set_redirect("http://localhost:99999999999999999999/target");
  3524. });
  3525. auto port = svr.bind_to_any_port(HOST);
  3526. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3527. auto se = detail::scope_exit([&] {
  3528. svr.stop();
  3529. thread.join();
  3530. ASSERT_FALSE(svr.is_running());
  3531. });
  3532. svr.wait_until_ready();
  3533. Client cli(HOST, port);
  3534. cli.set_follow_location(true);
  3535. auto res = cli.Get("/redir");
  3536. // Should fail gracefully, not crash (no valid response due to bad port)
  3537. EXPECT_FALSE(res);
  3538. }
  3539. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3540. Server svr;
  3541. auto port = svr.bind_to_any_port(HOST);
  3542. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3543. // The server's own port followed by junk must not be followed
  3544. res.set_redirect("http://" + std::string(HOST) + ":" +
  3545. std::to_string(port) + "junk/target");
  3546. });
  3547. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3548. res.set_content("target", "text/plain");
  3549. });
  3550. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3551. auto se = detail::scope_exit([&] {
  3552. svr.stop();
  3553. thread.join();
  3554. ASSERT_FALSE(svr.is_running());
  3555. });
  3556. svr.wait_until_ready();
  3557. Client cli(HOST, port);
  3558. cli.set_follow_location(true);
  3559. auto res = cli.Get("/redir");
  3560. EXPECT_FALSE(res);
  3561. }
  3562. TEST(RedirectFromPageWithContent, Redirect) {
  3563. Server svr;
  3564. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3565. res.set_content("___", "text/plain");
  3566. res.set_redirect("/2");
  3567. });
  3568. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3569. res.set_content("Hello World!", "text/plain");
  3570. });
  3571. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3572. auto se = detail::scope_exit([&] {
  3573. svr.stop();
  3574. th.join();
  3575. ASSERT_FALSE(svr.is_running());
  3576. });
  3577. svr.wait_until_ready();
  3578. {
  3579. Client cli("localhost", PORT);
  3580. cli.set_follow_location(true);
  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::OK_200, res->status);
  3588. EXPECT_EQ("Hello World!", body);
  3589. }
  3590. {
  3591. Client cli("localhost", PORT);
  3592. std::string body;
  3593. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3594. body.append(data, data_length);
  3595. return true;
  3596. });
  3597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3598. EXPECT_EQ(StatusCode::Found_302, res->status);
  3599. EXPECT_EQ("___", body);
  3600. }
  3601. }
  3602. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3603. Server svr;
  3604. auto port_str = std::to_string(PORT);
  3605. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3606. auto expected_host = "[::1]:" + port_str;
  3607. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3608. res.set_content("___", "text/plain");
  3609. // res.set_redirect("/2");
  3610. res.set_redirect(redirect_url);
  3611. });
  3612. svr.Get("/2", [&](const Request &req, Response &res) {
  3613. auto host_header = req.headers.find("Host");
  3614. ASSERT_TRUE(host_header != req.headers.end());
  3615. EXPECT_EQ(expected_host, host_header->second);
  3616. res.set_content("Hello World!", "text/plain");
  3617. });
  3618. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3619. auto se = detail::scope_exit([&] {
  3620. svr.stop();
  3621. th.join();
  3622. ASSERT_FALSE(svr.is_running());
  3623. });
  3624. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3625. // actually starts anything, so the condition !svr.is_running() will
  3626. // always remain true, and the loop never stops.
  3627. // This basically counts how many milliseconds have passed since the
  3628. // call to svr.listen(), and if after 5 seconds nothing started yet
  3629. // aborts the test.
  3630. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3631. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3632. ASSERT_LT(milliseconds, 5000U);
  3633. }
  3634. {
  3635. Client cli("::1", PORT);
  3636. cli.set_follow_location(true);
  3637. std::string body;
  3638. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3639. body.append(data, data_length);
  3640. return true;
  3641. });
  3642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3643. EXPECT_EQ(StatusCode::OK_200, res->status);
  3644. EXPECT_EQ("Hello World!", body);
  3645. }
  3646. {
  3647. Client cli("::1", PORT);
  3648. std::string body;
  3649. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3650. body.append(data, data_length);
  3651. return true;
  3652. });
  3653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3654. EXPECT_EQ(StatusCode::Found_302, res->status);
  3655. EXPECT_EQ("___", body);
  3656. }
  3657. }
  3658. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3659. Server svr;
  3660. svr.Get("/foo", [](const Request &req, Response &res) {
  3661. auto a = req.params.find("a");
  3662. if (a != req.params.end()) {
  3663. res.set_content((*a).second, "text/plain");
  3664. res.status = StatusCode::OK_200;
  3665. } else {
  3666. res.status = StatusCode::BadRequest_400;
  3667. }
  3668. });
  3669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3670. auto se = detail::scope_exit([&] {
  3671. svr.stop();
  3672. thread.join();
  3673. ASSERT_FALSE(svr.is_running());
  3674. });
  3675. svr.wait_until_ready();
  3676. {
  3677. Client cli(HOST, PORT);
  3678. cli.set_path_encode(false);
  3679. auto res = cli.Get("/foo?a=explicitly+encoded");
  3680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3681. EXPECT_EQ(StatusCode::OK_200, res->status);
  3682. // This expects it back with a space, as the `+` won't have been
  3683. // url-encoded, and server-side the params get decoded turning `+`
  3684. // into spaces.
  3685. EXPECT_EQ("explicitly encoded", res->body);
  3686. }
  3687. }
  3688. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3689. // When path encoding is disabled the client must transmit the supplied
  3690. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3691. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3692. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3693. // than a space (0x20). Assert on the raw wire target to catch this.
  3694. Server svr;
  3695. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3696. svr.Get("/foo", [&](const Request &req, Response &res) {
  3697. EXPECT_EQ(expected_target, req.target);
  3698. res.status = StatusCode::OK_200;
  3699. });
  3700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3701. auto se = detail::scope_exit([&] {
  3702. svr.stop();
  3703. thread.join();
  3704. ASSERT_FALSE(svr.is_running());
  3705. });
  3706. svr.wait_until_ready();
  3707. {
  3708. Client cli(HOST, PORT);
  3709. cli.set_path_encode(false);
  3710. auto res = cli.Get(expected_target.c_str());
  3711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3712. EXPECT_EQ(StatusCode::OK_200, res->status);
  3713. }
  3714. }
  3715. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3716. // `open_stream()` used to skip the path encoding that the buffered send
  3717. // path applies, so the same `path` produced different bytes in the request
  3718. // line depending on which API was used. Assert the two agree.
  3719. Server svr;
  3720. std::string target;
  3721. svr.Get(".*", [&](const Request &req, Response &res) {
  3722. target = req.target;
  3723. res.status = StatusCode::OK_200;
  3724. });
  3725. auto port = svr.bind_to_any_port(HOST);
  3726. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3727. auto se = detail::scope_exit([&] {
  3728. svr.stop();
  3729. thread.join();
  3730. ASSERT_FALSE(svr.is_running());
  3731. });
  3732. svr.wait_until_ready();
  3733. struct {
  3734. const char *path;
  3735. const char *expected;
  3736. } cases[] = {
  3737. {"/a b?x=1", "/a%20b?x=1"},
  3738. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3739. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3740. };
  3741. for (const auto &c : cases) {
  3742. Client cli(HOST, port);
  3743. target.clear();
  3744. auto res = cli.Get(c.path);
  3745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3746. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3747. auto buffered_target = target;
  3748. target.clear();
  3749. auto handle = cli.open_stream("GET", c.path);
  3750. EXPECT_TRUE(handle.is_valid())
  3751. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3752. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3753. }
  3754. }
  3755. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3756. // The `set_path_encode(false)` contract — transmit the supplied target
  3757. // verbatim — must hold for the streaming API too.
  3758. Server svr;
  3759. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3760. std::string target;
  3761. svr.Get("/foo", [&](const Request &req, Response &res) {
  3762. target = req.target;
  3763. res.status = StatusCode::OK_200;
  3764. });
  3765. auto port = svr.bind_to_any_port(HOST);
  3766. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3767. auto se = detail::scope_exit([&] {
  3768. svr.stop();
  3769. thread.join();
  3770. ASSERT_FALSE(svr.is_running());
  3771. });
  3772. svr.wait_until_ready();
  3773. {
  3774. Client cli(HOST, port);
  3775. cli.set_path_encode(false);
  3776. auto handle = cli.open_stream("GET", expected_target);
  3777. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3778. EXPECT_EQ(expected_target, target);
  3779. }
  3780. }
  3781. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3782. // With path encoding enabled a CR/LF in the target is percent-encoded
  3783. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3784. // write_request_line still backstops `set_path_encode(false)`, which is
  3785. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3786. Server svr;
  3787. // Captured before routing: the decoded path contains a newline, which a
  3788. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3789. std::string target;
  3790. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3791. target = req.target;
  3792. res.status = StatusCode::OK_200;
  3793. return Server::HandlerResponse::Handled;
  3794. });
  3795. auto port = svr.bind_to_any_port(HOST);
  3796. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3797. auto se = detail::scope_exit([&] {
  3798. svr.stop();
  3799. thread.join();
  3800. ASSERT_FALSE(svr.is_running());
  3801. });
  3802. svr.wait_until_ready();
  3803. {
  3804. Client cli(HOST, port);
  3805. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3806. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3807. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3808. }
  3809. }
  3810. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3811. // Every control character is percent-encoded, not just CR/LF, so the target
  3812. // passes the request-target check in write_request_line.
  3813. Server svr;
  3814. std::string target;
  3815. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3816. target = req.target;
  3817. res.status = StatusCode::OK_200;
  3818. return Server::HandlerResponse::Handled;
  3819. });
  3820. auto port = svr.bind_to_any_port(HOST);
  3821. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3822. auto se = detail::scope_exit([&] {
  3823. svr.stop();
  3824. thread.join();
  3825. ASSERT_FALSE(svr.is_running());
  3826. });
  3827. svr.wait_until_ready();
  3828. {
  3829. Client cli(HOST, port);
  3830. auto res = cli.Get("/a\tb\x1b\x7f");
  3831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3832. EXPECT_EQ("/a%09b%1B%7F", target);
  3833. }
  3834. }
  3835. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3836. // Nothing may reach the wire: a raw CR/LF target would split the request
  3837. // line and inject headers.
  3838. Server svr;
  3839. // Pre-routing so that "not called" means nothing reached the server at all,
  3840. // rather than merely failing to match a handler pattern.
  3841. auto handler_called = false;
  3842. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3843. handler_called = true;
  3844. res.status = StatusCode::OK_200;
  3845. return Server::HandlerResponse::Handled;
  3846. });
  3847. auto port = svr.bind_to_any_port(HOST);
  3848. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3849. auto se = detail::scope_exit([&] {
  3850. svr.stop();
  3851. thread.join();
  3852. ASSERT_FALSE(svr.is_running());
  3853. });
  3854. svr.wait_until_ready();
  3855. {
  3856. Client cli(HOST, port);
  3857. cli.set_path_encode(false);
  3858. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3859. EXPECT_FALSE(handle.is_valid());
  3860. EXPECT_EQ(Error::Write, handle.error);
  3861. EXPECT_FALSE(handler_called);
  3862. }
  3863. }
  3864. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3865. // Which of the two branches runs is decided by whether the query component
  3866. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3867. // an empty query and must still fall back to building one from
  3868. // `req.params`, while a non-empty query must win over `req.params`.
  3869. Server svr;
  3870. std::string target;
  3871. svr.Get("/foo", [&](const Request &req, Response &res) {
  3872. target = req.target;
  3873. res.status = StatusCode::OK_200;
  3874. });
  3875. auto port = svr.bind_to_any_port(HOST);
  3876. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3877. auto se = detail::scope_exit([&] {
  3878. svr.stop();
  3879. thread.join();
  3880. ASSERT_FALSE(svr.is_running());
  3881. });
  3882. svr.wait_until_ready();
  3883. {
  3884. // Trailing `?` -> empty query component -> `req.params` is used.
  3885. Client cli(HOST, port);
  3886. Request req;
  3887. req.method = "GET";
  3888. req.path = "/foo?";
  3889. req.params.emplace("a", "1");
  3890. target.clear();
  3891. auto res = cli.send(req);
  3892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3893. EXPECT_EQ("/foo?a=1", target);
  3894. }
  3895. {
  3896. // Non-empty query in `req.path` -> `req.params` is not appended.
  3897. Client cli(HOST, port);
  3898. Request req;
  3899. req.method = "GET";
  3900. req.path = "/foo?b=2";
  3901. req.params.emplace("a", "1");
  3902. target.clear();
  3903. auto res = cli.send(req);
  3904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3905. EXPECT_EQ("/foo?b=2", target);
  3906. }
  3907. }
  3908. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3909. Server svr;
  3910. svr.Get("/", [](const Request &req, Response &) {
  3911. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3912. });
  3913. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3914. auto se = detail::scope_exit([&] {
  3915. svr.stop();
  3916. thread.join();
  3917. ASSERT_FALSE(svr.is_running());
  3918. });
  3919. svr.wait_until_ready();
  3920. {
  3921. Client cli(HOST, PORT);
  3922. cli.set_path_encode(false);
  3923. auto res = cli.Get("/?something=%0A");
  3924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3925. EXPECT_EQ(StatusCode::OK_200, res->status);
  3926. }
  3927. }
  3928. TEST(BindServerTest, BindDualStack) {
  3929. Server svr;
  3930. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3931. res.set_content("Hello World!", "text/plain");
  3932. });
  3933. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3934. auto se = detail::scope_exit([&] {
  3935. svr.stop();
  3936. thread.join();
  3937. ASSERT_FALSE(svr.is_running());
  3938. });
  3939. svr.wait_until_ready();
  3940. {
  3941. Client cli("127.0.0.1", PORT);
  3942. auto res = cli.Get("/1");
  3943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3944. EXPECT_EQ(StatusCode::OK_200, res->status);
  3945. EXPECT_EQ("Hello World!", res->body);
  3946. }
  3947. {
  3948. Client cli("::1", PORT);
  3949. auto res = cli.Get("/1");
  3950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3951. EXPECT_EQ(StatusCode::OK_200, res->status);
  3952. EXPECT_EQ("Hello World!", res->body);
  3953. }
  3954. }
  3955. TEST(BindServerTest, BindAndListenSeparately) {
  3956. Server svr;
  3957. int port = svr.bind_to_any_port("0.0.0.0");
  3958. ASSERT_TRUE(svr.is_valid());
  3959. ASSERT_TRUE(port > 0);
  3960. svr.stop();
  3961. }
  3962. // Reports whether anything is still listening on a loopback port. A plain
  3963. // connect() is used instead of a Client request because a socket left bound by
  3964. // mistake accepts the connection into its backlog and never answers, which
  3965. // would hang the test instead of failing it.
  3966. static bool is_loopback_port_accepting(int port) {
  3967. sockaddr_in addr{};
  3968. addr.sin_family = AF_INET;
  3969. addr.sin_port = htons(static_cast<uint16_t>(port));
  3970. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3971. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3972. EXPECT_NE(sock, INVALID_SOCKET);
  3973. if (sock == INVALID_SOCKET) { return false; }
  3974. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3975. static_cast<socklen_t>(sizeof(addr)));
  3976. detail::close_socket(sock);
  3977. return ret == 0;
  3978. }
  3979. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3980. Server svr;
  3981. auto port = svr.bind_to_any_port("127.0.0.1");
  3982. ASSERT_TRUE(port > 0);
  3983. svr.stop();
  3984. // bind_to_any_port() already called listen(2), so until stop() closed the
  3985. // descriptor the port kept accepting connections into the backlog. ASSERT
  3986. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3987. // below blocks forever in the accept loop.
  3988. ASSERT_FALSE(is_loopback_port_accepting(port));
  3989. // Nothing is left to accept on, so listen_after_bind() must report failure
  3990. // instead of returning success without ever serving.
  3991. EXPECT_FALSE(svr.listen_after_bind());
  3992. // The failed listen marks the server decommissioned, so a waiter returns
  3993. // instead of spinning forever.
  3994. svr.wait_until_ready();
  3995. }
  3996. #ifdef CPPHTTPLIB_SSL_ENABLED
  3997. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3998. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3999. CLIENT_CA_CERT_DIR);
  4000. int port = svr.bind_to_any_port("0.0.0.0");
  4001. ASSERT_TRUE(svr.is_valid());
  4002. ASSERT_TRUE(port > 0);
  4003. svr.stop();
  4004. }
  4005. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4006. // or a rejected CustomRoute() registration would not stop the server binding.
  4007. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4009. CLIENT_CA_CERT_DIR);
  4010. ASSERT_TRUE(svr.is_valid());
  4011. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4012. EXPECT_FALSE(svr.is_valid());
  4013. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4014. }
  4015. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4016. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4017. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4018. int port = svr.bind_to_any_port("0.0.0.0");
  4019. ASSERT_TRUE(svr.is_valid());
  4020. ASSERT_TRUE(port > 0);
  4021. svr.stop();
  4022. }
  4023. TEST(BindServerTest, UpdateCertsPem) {
  4024. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4025. int port = svr.bind_to_any_port("0.0.0.0");
  4026. ASSERT_TRUE(svr.is_valid());
  4027. ASSERT_TRUE(port > 0);
  4028. // Read PEM files
  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(CLIENT_CA_CERT_FILE, ca_pem);
  4033. // Update server certificates using PEM API
  4034. ASSERT_TRUE(
  4035. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4036. ASSERT_TRUE(svr.is_valid());
  4037. svr.stop();
  4038. }
  4039. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4040. // Start server with client CA (enables client auth)
  4041. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4042. ASSERT_TRUE(svr.is_valid());
  4043. bool handler_called = false;
  4044. svr.Get("/test", [&](const Request &req, Response &res) {
  4045. handler_called = true;
  4046. // Verify client certificate is present
  4047. auto cert = req.peer_cert();
  4048. EXPECT_TRUE(static_cast<bool>(cert));
  4049. res.set_content("ok", "text/plain");
  4050. });
  4051. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4052. auto se = detail::scope_exit([&] {
  4053. svr.stop();
  4054. t.join();
  4055. ASSERT_FALSE(svr.is_running());
  4056. });
  4057. svr.wait_until_ready();
  4058. // Read PEM files
  4059. std::string cert_pem, key_pem, ca_pem;
  4060. read_file(SERVER_CERT_FILE, cert_pem);
  4061. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4062. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4063. // Update server certificates and client CA using PEM API while server running
  4064. ASSERT_TRUE(
  4065. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4066. // Connect with client certificate
  4067. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4068. cli.enable_server_certificate_verification(false);
  4069. cli.set_connection_timeout(30);
  4070. auto res = cli.Get("/test");
  4071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4072. ASSERT_EQ(StatusCode::OK_200, res->status);
  4073. ASSERT_TRUE(handler_called);
  4074. EXPECT_EQ("ok", res->body);
  4075. }
  4076. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4078. ASSERT_TRUE(svr.is_valid());
  4079. svr.Get("/test", [](const Request &, Response &res) {
  4080. res.set_content("ok", "text/plain");
  4081. });
  4082. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4083. auto se = detail::scope_exit([&] {
  4084. svr.stop();
  4085. t.join();
  4086. ASSERT_FALSE(svr.is_running());
  4087. });
  4088. svr.wait_until_ready();
  4089. auto get = [] {
  4090. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4091. cli.enable_server_certificate_verification(false);
  4092. return cli.Get("/test");
  4093. };
  4094. ASSERT_TRUE(get());
  4095. // A CA that did not sign the client's certificate takes the old one's place.
  4096. std::string cert_pem, key_pem, ca_pem;
  4097. read_file(SERVER_CERT_FILE, cert_pem);
  4098. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4099. read_file(SERVER_CERT2_FILE, ca_pem);
  4100. ASSERT_TRUE(
  4101. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4102. EXPECT_FALSE(get());
  4103. }
  4104. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4105. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4106. ASSERT_TRUE(svr.is_valid());
  4107. svr.Get("/test", [](const Request &, Response &res) {
  4108. res.set_content("ok", "text/plain");
  4109. });
  4110. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4111. auto se = detail::scope_exit([&] {
  4112. svr.stop();
  4113. t.join();
  4114. ASSERT_FALSE(svr.is_running());
  4115. });
  4116. svr.wait_until_ready();
  4117. // A connection that sends no ClientHello keeps its handshake in progress,
  4118. // once the server has had a moment to start it.
  4119. auto error = Error::Success;
  4120. auto sock = detail::create_client_socket(
  4121. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4122. /*connection_timeout_sec=*/5, 0,
  4123. /*read_timeout_sec=*/5, 0,
  4124. /*write_timeout_sec=*/5, 0, std::string(), error);
  4125. ASSERT_NE(INVALID_SOCKET, sock);
  4126. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4127. std::string cert_pem, key_pem;
  4128. read_file(SERVER_CERT_FILE, cert_pem);
  4129. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4130. auto update = std::async(std::launch::async, [&]() {
  4131. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4132. });
  4133. EXPECT_EQ(std::future_status::timeout,
  4134. update.wait_for(std::chrono::milliseconds(200)));
  4135. detail::close_socket(sock);
  4136. EXPECT_TRUE(update.get());
  4137. SSLClient cli(HOST, PORT);
  4138. cli.enable_server_certificate_verification(false);
  4139. auto res = cli.Get("/test");
  4140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4141. EXPECT_EQ(StatusCode::OK_200, res->status);
  4142. }
  4143. #endif
  4144. TEST(ErrorHandlerTest, ContentLength) {
  4145. Server svr;
  4146. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4147. res.status = StatusCode::OK_200;
  4148. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4149. "text/html"); // <= Content-Length still 13
  4150. });
  4151. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4152. res.set_content("Hello World!\n", "text/plain");
  4153. res.status = 524;
  4154. });
  4155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4156. auto se = detail::scope_exit([&] {
  4157. svr.stop();
  4158. thread.join();
  4159. ASSERT_FALSE(svr.is_running());
  4160. });
  4161. svr.wait_until_ready();
  4162. {
  4163. Client cli(HOST, PORT);
  4164. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4166. EXPECT_EQ(StatusCode::OK_200, res->status);
  4167. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4168. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4169. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4170. }
  4171. }
  4172. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4173. TEST(ExceptionTest, WithoutExceptionHandler) {
  4174. Server svr;
  4175. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4176. throw std::runtime_error("exception...");
  4177. });
  4178. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4179. throw std::runtime_error("exception\r\n...");
  4180. });
  4181. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4182. auto se = detail::scope_exit([&] {
  4183. svr.stop();
  4184. listen_thread.join();
  4185. ASSERT_FALSE(svr.is_running());
  4186. });
  4187. svr.wait_until_ready();
  4188. Client cli("localhost", PORT);
  4189. {
  4190. auto res = cli.Get("/exception");
  4191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4192. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4193. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4194. }
  4195. {
  4196. auto res = cli.Get("/unknown");
  4197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4198. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4199. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4200. }
  4201. }
  4202. TEST(ExceptionTest, WithExceptionHandler) {
  4203. Server svr;
  4204. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4205. std::exception_ptr ep) {
  4206. EXPECT_FALSE(ep == nullptr);
  4207. try {
  4208. std::rethrow_exception(ep);
  4209. } catch (std::exception &e) {
  4210. EXPECT_EQ("abc", std::string(e.what()));
  4211. } catch (...) {}
  4212. res.status = StatusCode::InternalServerError_500;
  4213. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4214. "text/html"); // <= Content-Length still 13 at this point
  4215. });
  4216. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4217. res.set_content("Hello World!\n", "text/plain");
  4218. throw std::runtime_error("abc");
  4219. });
  4220. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4221. auto se = detail::scope_exit([&] {
  4222. svr.stop();
  4223. thread.join();
  4224. ASSERT_FALSE(svr.is_running());
  4225. });
  4226. svr.wait_until_ready();
  4227. for (size_t i = 0; i < 10; i++) {
  4228. Client cli(HOST, PORT);
  4229. for (size_t j = 0; j < 100; j++) {
  4230. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4232. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4233. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4234. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4235. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4236. }
  4237. cli.set_keep_alive(true);
  4238. for (size_t j = 0; j < 100; j++) {
  4239. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4241. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4242. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4243. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4244. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4245. }
  4246. }
  4247. }
  4248. TEST(ExceptionTest, AndErrorHandler) {
  4249. Server svr;
  4250. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4251. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4252. });
  4253. svr.set_exception_handler(
  4254. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4255. EXPECT_FALSE(ep == nullptr);
  4256. try {
  4257. std::rethrow_exception(ep);
  4258. } catch (std::exception &e) {
  4259. res.set_content(e.what(), "text/html");
  4260. } catch (...) {}
  4261. res.status = StatusCode::InternalServerError_500;
  4262. });
  4263. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4264. throw std::runtime_error("EXCEPTION");
  4265. });
  4266. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4267. res.set_content("ERROR", "text/html");
  4268. res.status = StatusCode::InternalServerError_500;
  4269. });
  4270. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4271. auto se = detail::scope_exit([&] {
  4272. svr.stop();
  4273. thread.join();
  4274. ASSERT_FALSE(svr.is_running());
  4275. });
  4276. svr.wait_until_ready();
  4277. Client cli(HOST, PORT);
  4278. {
  4279. auto res = cli.Get("/exception");
  4280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4281. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4282. EXPECT_EQ("EXCEPTION", res->body);
  4283. }
  4284. {
  4285. auto res = cli.Get("/error");
  4286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4287. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4288. EXPECT_EQ("ERROR", res->body);
  4289. }
  4290. {
  4291. auto res = cli.Get("/invalid");
  4292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4294. EXPECT_EQ("NOT_FOUND", res->body);
  4295. }
  4296. }
  4297. #endif
  4298. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4299. // process_request() wraps only routing() in a try/catch, so an exception from
  4300. // any other user callback used to unwind into the task queue - which does not
  4301. // catch - and terminate the process. Each test below runs the server on a
  4302. // single worker thread: a guard that catches the exception but still loses the
  4303. // thread would otherwise be hidden by a spare worker serving the follow-up
  4304. // request. Note that a regression here aborts the whole test binary rather
  4305. // than failing one test.
  4306. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4307. Server svr;
  4308. svr.new_task_queue = [] { return new ThreadPool(1); };
  4309. std::atomic<int> reported{0};
  4310. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4311. if (err == Error::UserCallbackException) { reported++; }
  4312. });
  4313. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4314. res.set_content_provider(
  4315. 1024, "text/plain",
  4316. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4317. sink.write("hello", 5);
  4318. throw std::runtime_error("from the content provider");
  4319. });
  4320. });
  4321. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4322. res.set_content("ok", "text/plain");
  4323. });
  4324. auto port = svr.bind_to_any_port(HOST);
  4325. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4326. auto se = detail::scope_exit([&] {
  4327. svr.stop();
  4328. listen_thread.join();
  4329. ASSERT_FALSE(svr.is_running());
  4330. });
  4331. svr.wait_until_ready();
  4332. {
  4333. Client cli(HOST, port);
  4334. cli.set_read_timeout(5, 0);
  4335. EXPECT_FALSE(cli.Get("/throw"));
  4336. }
  4337. EXPECT_TRUE(svr.is_running());
  4338. EXPECT_EQ(1, reported.load());
  4339. // A request on a fresh connection is still served.
  4340. {
  4341. Client cli(HOST, port);
  4342. auto res = cli.Get("/ok");
  4343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4344. EXPECT_EQ(StatusCode::OK_200, res->status);
  4345. EXPECT_EQ("ok", res->body);
  4346. }
  4347. }
  4348. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4349. Server svr;
  4350. svr.new_task_queue = [] { return new ThreadPool(1); };
  4351. std::atomic<bool> should_throw{true};
  4352. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4353. res.set_content("hi", "text/plain");
  4354. });
  4355. svr.set_post_routing_handler(
  4356. [&](const Request & /*req*/, Response & /*res*/) {
  4357. if (should_throw) {
  4358. throw std::runtime_error("from the post-routing handler");
  4359. }
  4360. });
  4361. auto port = svr.bind_to_any_port(HOST);
  4362. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4363. auto se = detail::scope_exit([&] {
  4364. svr.stop();
  4365. listen_thread.join();
  4366. ASSERT_FALSE(svr.is_running());
  4367. });
  4368. svr.wait_until_ready();
  4369. {
  4370. Client cli(HOST, port);
  4371. cli.set_read_timeout(5, 0);
  4372. EXPECT_FALSE(cli.Get("/hi"));
  4373. }
  4374. EXPECT_TRUE(svr.is_running());
  4375. should_throw = false;
  4376. {
  4377. Client cli(HOST, port);
  4378. auto res = cli.Get("/hi");
  4379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4380. EXPECT_EQ(StatusCode::OK_200, res->status);
  4381. EXPECT_EQ("hi", res->body);
  4382. }
  4383. }
  4384. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4385. // The guard reports the caught exception through the error logger, which is
  4386. // a user callback too. A logger that throws has to be contained as well, or
  4387. // the process would terminate from inside the catch.
  4388. Server svr;
  4389. svr.new_task_queue = [] { return new ThreadPool(1); };
  4390. std::atomic<int> reported{0};
  4391. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4392. if (err == Error::UserCallbackException) {
  4393. reported++;
  4394. throw std::runtime_error("from the error logger");
  4395. }
  4396. });
  4397. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4398. res.set_content_provider(
  4399. 1024, "text/plain",
  4400. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4401. sink.write("hello", 5);
  4402. throw std::runtime_error("from the content provider");
  4403. });
  4404. });
  4405. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4406. res.set_content("ok", "text/plain");
  4407. });
  4408. auto port = svr.bind_to_any_port(HOST);
  4409. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4410. auto se = detail::scope_exit([&] {
  4411. svr.stop();
  4412. listen_thread.join();
  4413. ASSERT_FALSE(svr.is_running());
  4414. });
  4415. svr.wait_until_ready();
  4416. {
  4417. Client cli(HOST, port);
  4418. cli.set_read_timeout(5, 0);
  4419. EXPECT_FALSE(cli.Get("/throw"));
  4420. }
  4421. EXPECT_TRUE(svr.is_running());
  4422. EXPECT_EQ(1, reported.load());
  4423. {
  4424. Client cli(HOST, port);
  4425. auto res = cli.Get("/ok");
  4426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4427. EXPECT_EQ(StatusCode::OK_200, res->status);
  4428. EXPECT_EQ("ok", res->body);
  4429. }
  4430. }
  4431. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4432. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4433. // so the exception unwinds through the ws::WebSocket object on its way to
  4434. // the guard. None of the HTTP cases above cross that.
  4435. Server svr;
  4436. svr.new_task_queue = [] { return new ThreadPool(1); };
  4437. std::atomic<int> reported{0};
  4438. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4439. if (err == Error::UserCallbackException) { reported++; }
  4440. });
  4441. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4442. throw std::runtime_error("from the WebSocket handler");
  4443. });
  4444. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4445. res.set_content("ok", "text/plain");
  4446. });
  4447. auto port = svr.bind_to_any_port(HOST);
  4448. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4449. auto se = detail::scope_exit([&] {
  4450. svr.stop();
  4451. listen_thread.join();
  4452. ASSERT_FALSE(svr.is_running());
  4453. });
  4454. svr.wait_until_ready();
  4455. {
  4456. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4457. "/ws");
  4458. auto res = client.connect();
  4459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4460. // The server dropped the connection instead of dying.
  4461. std::string msg;
  4462. EXPECT_FALSE(client.read(msg));
  4463. client.close();
  4464. }
  4465. EXPECT_TRUE(svr.is_running());
  4466. EXPECT_EQ(1, reported.load());
  4467. {
  4468. Client cli(HOST, port);
  4469. auto res = cli.Get("/ok");
  4470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4471. EXPECT_EQ(StatusCode::OK_200, res->status);
  4472. EXPECT_EQ("ok", res->body);
  4473. }
  4474. }
  4475. #ifdef CPPHTTPLIB_SSL_ENABLED
  4476. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4477. // SSLServer::process_and_close_socket() is a separate overload with its own
  4478. // guard, so it is exercised on its own.
  4479. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4480. ASSERT_TRUE(svr.is_valid());
  4481. svr.new_task_queue = [] { return new ThreadPool(1); };
  4482. std::atomic<int> reported{0};
  4483. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4484. if (err == Error::UserCallbackException) { reported++; }
  4485. });
  4486. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4487. res.set_content_provider(
  4488. 1024, "text/plain",
  4489. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4490. sink.write("hello", 5);
  4491. throw std::runtime_error("from the content provider");
  4492. });
  4493. });
  4494. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4495. res.set_content("ok", "text/plain");
  4496. });
  4497. auto port = svr.bind_to_any_port(HOST);
  4498. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4499. auto se = detail::scope_exit([&] {
  4500. svr.stop();
  4501. listen_thread.join();
  4502. ASSERT_FALSE(svr.is_running());
  4503. });
  4504. svr.wait_until_ready();
  4505. {
  4506. SSLClient cli(HOST, port);
  4507. cli.enable_server_certificate_verification(false);
  4508. cli.set_read_timeout(5, 0);
  4509. EXPECT_FALSE(cli.Get("/throw"));
  4510. }
  4511. EXPECT_TRUE(svr.is_running());
  4512. EXPECT_EQ(1, reported.load());
  4513. {
  4514. SSLClient cli(HOST, port);
  4515. cli.enable_server_certificate_verification(false);
  4516. auto res = cli.Get("/ok");
  4517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4518. EXPECT_EQ(StatusCode::OK_200, res->status);
  4519. EXPECT_EQ("ok", res->body);
  4520. }
  4521. }
  4522. #endif
  4523. #endif
  4524. TEST(NoContentTest, ContentLength) {
  4525. Server svr;
  4526. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4527. res.status = StatusCode::NoContent_204;
  4528. });
  4529. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4530. auto se = detail::scope_exit([&] {
  4531. svr.stop();
  4532. thread.join();
  4533. ASSERT_FALSE(svr.is_running());
  4534. });
  4535. svr.wait_until_ready();
  4536. {
  4537. Client cli(HOST, PORT);
  4538. auto res = cli.Get("/hi");
  4539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4540. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4541. // RFC 9110 8.6: none in a 204 response
  4542. EXPECT_FALSE(res->has_header("Content-Length"));
  4543. }
  4544. }
  4545. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4546. Server svr;
  4547. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4548. res.set_header("Content-Length", "5");
  4549. res.set_content("hello world", "text/plain");
  4550. });
  4551. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4552. // A body that reads as the last chunk, were it taken as chunked
  4553. res.set_header("Transfer-Encoding", "chunked");
  4554. res.set_content("0\r\n\r\n", "text/plain");
  4555. });
  4556. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4557. res.set_header("Content-Length", "2");
  4558. res.set_content_provider(5, "text/plain",
  4559. [](size_t offset, size_t length, DataSink &sink) {
  4560. sink.write(&"hello"[offset], length);
  4561. return true;
  4562. });
  4563. });
  4564. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4565. res.set_header("Content-Length", "1234");
  4566. });
  4567. thread t = thread([&] { svr.listen(HOST, PORT); });
  4568. auto se = detail::scope_exit([&] {
  4569. svr.stop();
  4570. t.join();
  4571. ASSERT_FALSE(svr.is_running());
  4572. });
  4573. svr.wait_until_ready();
  4574. Client cli(HOST, PORT);
  4575. cli.set_read_timeout(1, 0);
  4576. auto expect_body = [&](const Result &res, const std::string &body) {
  4577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4578. EXPECT_EQ(body, res->body);
  4579. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4580. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4581. };
  4582. Headers identity{{"Accept-Encoding", ""}};
  4583. expect_body(cli.Get("/body", identity), "hello world");
  4584. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4585. expect_body(cli.Get("/body",
  4586. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4587. "he");
  4588. expect_body(cli.Get("/provider", identity), "hello");
  4589. expect_body(cli.Get("/empty", identity), "");
  4590. // A HEAD response may give the length of the body a GET would get.
  4591. auto res = cli.Head("/empty");
  4592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4593. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4594. }
  4595. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4596. Server svr;
  4597. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4598. res.set_content("short", "text/plain");
  4599. });
  4600. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4601. res.body += " with a footer";
  4602. res.set_header("Transfer-Encoding", "chunked");
  4603. });
  4604. thread t = thread([&] { svr.listen(HOST, PORT); });
  4605. auto se = detail::scope_exit([&] {
  4606. svr.stop();
  4607. t.join();
  4608. ASSERT_FALSE(svr.is_running());
  4609. });
  4610. svr.wait_until_ready();
  4611. Client cli(HOST, PORT);
  4612. cli.set_read_timeout(1, 0);
  4613. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4615. EXPECT_EQ("short with a footer", res->body);
  4616. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4617. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4618. }
  4619. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4620. #ifdef CPPHTTPLIB_SSL_ENABLED
  4621. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4622. ASSERT_TRUE(svr.is_valid());
  4623. #else
  4624. Server svr;
  4625. #endif
  4626. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4627. if (req.path == "/routing_handler") {
  4628. res.set_header("PRE_ROUTING", "on");
  4629. res.set_content("Routing Handler", "text/plain");
  4630. return httplib::Server::HandlerResponse::Handled;
  4631. }
  4632. return httplib::Server::HandlerResponse::Unhandled;
  4633. });
  4634. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4635. res.set_content("Error", "text/html");
  4636. });
  4637. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4638. if (req.path == "/routing_handler") {
  4639. res.set_header("POST_ROUTING", "on");
  4640. }
  4641. });
  4642. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4643. res.set_content("Hello World!\n", "text/plain");
  4644. });
  4645. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4646. auto se = detail::scope_exit([&] {
  4647. svr.stop();
  4648. thread.join();
  4649. ASSERT_FALSE(svr.is_running());
  4650. });
  4651. svr.wait_until_ready();
  4652. {
  4653. #ifdef CPPHTTPLIB_SSL_ENABLED
  4654. SSLClient cli(HOST, PORT);
  4655. cli.enable_server_certificate_verification(false);
  4656. #else
  4657. Client cli(HOST, PORT);
  4658. #endif
  4659. auto res = cli.Get("/routing_handler");
  4660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4661. EXPECT_EQ(StatusCode::OK_200, res->status);
  4662. EXPECT_EQ("Routing Handler", res->body);
  4663. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4664. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4665. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4666. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4667. }
  4668. {
  4669. #ifdef CPPHTTPLIB_SSL_ENABLED
  4670. SSLClient cli(HOST, PORT);
  4671. cli.enable_server_certificate_verification(false);
  4672. #else
  4673. Client cli(HOST, PORT);
  4674. #endif
  4675. auto res = cli.Get("/hi");
  4676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4677. EXPECT_EQ(StatusCode::OK_200, res->status);
  4678. EXPECT_EQ("Hello World!\n", res->body);
  4679. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4680. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4681. }
  4682. {
  4683. #ifdef CPPHTTPLIB_SSL_ENABLED
  4684. SSLClient cli(HOST, PORT);
  4685. cli.enable_server_certificate_verification(false);
  4686. #else
  4687. Client cli(HOST, PORT);
  4688. #endif
  4689. auto res = cli.Get("/aaa");
  4690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4691. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4692. EXPECT_EQ("Error", res->body);
  4693. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4694. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4695. }
  4696. }
  4697. TEST(RequestHandlerTest, PreRequestHandler) {
  4698. auto route_path = "/user/:user";
  4699. Server svr;
  4700. svr.Get("/hi", [](const Request &, Response &res) {
  4701. res.set_content("hi", "text/plain");
  4702. });
  4703. svr.Get(route_path, [](const Request &req, Response &res) {
  4704. res.set_content(req.path_params.at("user"), "text/plain");
  4705. });
  4706. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4707. if (req.matched_route == route_path) {
  4708. auto user = req.path_params.at("user");
  4709. if (user != "john") {
  4710. res.status = StatusCode::Forbidden_403;
  4711. res.set_content("error", "text/html");
  4712. return Server::HandlerResponse::Handled;
  4713. }
  4714. }
  4715. return Server::HandlerResponse::Unhandled;
  4716. });
  4717. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4718. auto se = detail::scope_exit([&] {
  4719. svr.stop();
  4720. thread.join();
  4721. ASSERT_FALSE(svr.is_running());
  4722. });
  4723. svr.wait_until_ready();
  4724. Client cli(HOST, PORT);
  4725. {
  4726. auto res = cli.Get("/hi");
  4727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4728. EXPECT_EQ(StatusCode::OK_200, res->status);
  4729. EXPECT_EQ("hi", res->body);
  4730. }
  4731. {
  4732. auto res = cli.Get("/user/john");
  4733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4734. EXPECT_EQ(StatusCode::OK_200, res->status);
  4735. EXPECT_EQ("john", res->body);
  4736. }
  4737. {
  4738. auto res = cli.Get("/user/invalid-user");
  4739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4740. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4741. EXPECT_EQ("error", res->body);
  4742. }
  4743. }
  4744. // The pre-request handler must run before the request body is read, so a
  4745. // rejected request never forces the server to buffer a (potentially large)
  4746. // body. Here the posted body is larger than the payload limit: if the body
  4747. // were read first the server would answer 413, but because the pre-request
  4748. // handler runs first it answers 403 and the body is never read.
  4749. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4750. Server svr;
  4751. svr.set_payload_max_length(8);
  4752. auto handler_ran = false;
  4753. svr.Post("/reject", [&](const Request &req, Response &res) {
  4754. handler_ran = true;
  4755. res.set_content(req.body, "text/plain");
  4756. });
  4757. svr.Post("/accept", [](const Request &req, Response &res) {
  4758. res.set_content(req.body, "text/plain");
  4759. });
  4760. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4761. if (req.matched_route == "/reject") {
  4762. res.status = StatusCode::Forbidden_403;
  4763. res.set_content("denied", "text/plain");
  4764. return Server::HandlerResponse::Handled;
  4765. }
  4766. return Server::HandlerResponse::Unhandled;
  4767. });
  4768. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4769. auto se = detail::scope_exit([&] {
  4770. svr.stop();
  4771. thread.join();
  4772. ASSERT_FALSE(svr.is_running());
  4773. });
  4774. svr.wait_until_ready();
  4775. Client cli(HOST, PORT);
  4776. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4777. // rejects with 403 before the body is read, so 413 is never reached.
  4778. {
  4779. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4781. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4782. EXPECT_EQ("denied", res->body);
  4783. EXPECT_FALSE(handler_ran);
  4784. }
  4785. // An approved route still reads the body and enforces the payload limit.
  4786. {
  4787. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4789. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4790. }
  4791. }
  4792. TEST(UserDataTest, BasicOperations) {
  4793. httplib::UserData ud;
  4794. // Initially empty
  4795. EXPECT_FALSE(ud.has("key"));
  4796. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4797. // set and get
  4798. ud.set("key", 42);
  4799. EXPECT_TRUE(ud.has("key"));
  4800. auto *p = ud.get<int>("key");
  4801. ASSERT_NE(nullptr, p);
  4802. EXPECT_EQ(42, *p);
  4803. // Type mismatch → nullptr
  4804. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4805. // Overwrite with different type
  4806. ud.set("key", std::string("hello"));
  4807. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4808. auto *s = ud.get<std::string>("key");
  4809. ASSERT_NE(nullptr, s);
  4810. EXPECT_EQ("hello", *s);
  4811. // erase
  4812. ud.erase("key");
  4813. EXPECT_FALSE(ud.has("key"));
  4814. // clear
  4815. ud.set("a", 1);
  4816. ud.set("b", 2);
  4817. ud.clear();
  4818. EXPECT_FALSE(ud.has("a"));
  4819. EXPECT_FALSE(ud.has("b"));
  4820. }
  4821. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4822. struct AuthCtx {
  4823. std::string user_id;
  4824. };
  4825. Server svr;
  4826. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4827. res.user_data.set("auth", AuthCtx{"alice"});
  4828. return Server::HandlerResponse::Unhandled;
  4829. });
  4830. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4831. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4832. ASSERT_NE(nullptr, ctx);
  4833. res.set_content("Hello " + ctx->user_id, "text/plain");
  4834. });
  4835. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4836. auto se = detail::scope_exit([&] {
  4837. svr.stop();
  4838. thread.join();
  4839. ASSERT_FALSE(svr.is_running());
  4840. });
  4841. svr.wait_until_ready();
  4842. Client cli(HOST, PORT);
  4843. auto res = cli.Get("/me");
  4844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4845. EXPECT_EQ(StatusCode::OK_200, res->status);
  4846. EXPECT_EQ("Hello alice", res->body);
  4847. }
  4848. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4849. struct RoleCtx {
  4850. std::string role;
  4851. };
  4852. Server svr;
  4853. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4854. res.user_data.set("role", RoleCtx{"admin"});
  4855. return Server::HandlerResponse::Unhandled;
  4856. });
  4857. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4858. auto *ctx = res.user_data.get<RoleCtx>("role");
  4859. ASSERT_NE(nullptr, ctx);
  4860. res.set_content(ctx->role, "text/plain");
  4861. });
  4862. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4863. auto se = detail::scope_exit([&] {
  4864. svr.stop();
  4865. thread.join();
  4866. ASSERT_FALSE(svr.is_running());
  4867. });
  4868. svr.wait_until_ready();
  4869. Client cli(HOST, PORT);
  4870. auto res = cli.Get("/role");
  4871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4872. EXPECT_EQ(StatusCode::OK_200, res->status);
  4873. EXPECT_EQ("admin", res->body);
  4874. }
  4875. TEST(InvalidFormatTest, StatusCode) {
  4876. Server svr;
  4877. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4878. res.set_content("Hello World!\n", "text/plain");
  4879. res.status = 9999; // Status should be a three-digit code...
  4880. });
  4881. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4882. auto se = detail::scope_exit([&] {
  4883. svr.stop();
  4884. thread.join();
  4885. ASSERT_FALSE(svr.is_running());
  4886. });
  4887. svr.wait_until_ready();
  4888. {
  4889. Client cli(HOST, PORT);
  4890. auto res = cli.Get("/hi");
  4891. ASSERT_FALSE(res);
  4892. }
  4893. }
  4894. TEST(URLFragmentTest, WithFragment) {
  4895. Server svr;
  4896. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4897. EXPECT_TRUE(req.target == "/hi");
  4898. });
  4899. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4900. auto se = detail::scope_exit([&] {
  4901. svr.stop();
  4902. thread.join();
  4903. ASSERT_FALSE(svr.is_running());
  4904. });
  4905. svr.wait_until_ready();
  4906. {
  4907. Client cli(HOST, PORT);
  4908. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4909. EXPECT_TRUE(res);
  4910. EXPECT_EQ(StatusCode::OK_200, res->status);
  4911. res = cli.Get("/hi%23key1=val1=key2=val2");
  4912. EXPECT_TRUE(res);
  4913. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4914. }
  4915. }
  4916. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  4917. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  4918. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  4919. Server svr;
  4920. std::vector<std::string> targets;
  4921. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  4922. targets.push_back(req.target);
  4923. });
  4924. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4925. auto se = detail::scope_exit([&] {
  4926. svr.stop();
  4927. thread.join();
  4928. ASSERT_FALSE(svr.is_running());
  4929. });
  4930. svr.wait_until_ready();
  4931. Client cli(HOST, PORT);
  4932. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  4933. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  4934. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  4935. // A '?' after the '#' belongs to the fragment, not to the query.
  4936. Request req;
  4937. req.method = "GET";
  4938. req.path = "/hi#f?x=1";
  4939. req.params.emplace("a", "1");
  4940. Response res;
  4941. auto error = Error::Success;
  4942. EXPECT_TRUE(cli.send(req, res, error));
  4943. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  4944. "/hi?a=1"}),
  4945. targets);
  4946. }
  4947. TEST(HeaderWriter, SetHeaderWriter) {
  4948. Server svr;
  4949. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4950. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4951. return detail::write_headers(strm, hdrs);
  4952. });
  4953. svr.Get("/hi", [](const Request &req, Response &res) {
  4954. auto it = req.headers.find("CustomClientHeader");
  4955. EXPECT_TRUE(it != req.headers.end());
  4956. EXPECT_EQ(it->second, "CustomClientValue");
  4957. res.set_content("Hello World!\n", "text/plain");
  4958. });
  4959. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4960. auto se = detail::scope_exit([&] {
  4961. svr.stop();
  4962. thread.join();
  4963. ASSERT_FALSE(svr.is_running());
  4964. });
  4965. svr.wait_until_ready();
  4966. {
  4967. Client cli(HOST, PORT);
  4968. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4969. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4970. return detail::write_headers(strm, hdrs);
  4971. });
  4972. auto res = cli.Get("/hi");
  4973. EXPECT_TRUE(res);
  4974. EXPECT_EQ(StatusCode::OK_200, res->status);
  4975. auto it = res->headers.find("CustomServerHeader");
  4976. EXPECT_TRUE(it != res->headers.end());
  4977. EXPECT_EQ(it->second, "CustomServerValue");
  4978. }
  4979. }
  4980. class ServerTest : public ::testing::Test {
  4981. protected:
  4982. ServerTest()
  4983. : cli_(HOST, PORT)
  4984. #ifdef CPPHTTPLIB_SSL_ENABLED
  4985. ,
  4986. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4987. #endif
  4988. {
  4989. #ifdef CPPHTTPLIB_SSL_ENABLED
  4990. cli_.enable_server_certificate_verification(false);
  4991. #endif
  4992. // Allow LARGE_DATA (100MB) responses
  4993. cli_.set_payload_max_length(200 * 1024 * 1024);
  4994. }
  4995. virtual void SetUp() {
  4996. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4997. svr_.set_payload_max_length(200 * 1024 * 1024);
  4998. svr_.set_mount_point("/", "./www");
  4999. svr_.set_mount_point("/mount", "./www2");
  5000. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5001. svr_.Get("/hi",
  5002. [&](const Request & /*req*/, Response &res) {
  5003. res.set_content("Hello World!", "text/plain");
  5004. })
  5005. .Get("/file_content",
  5006. [&](const Request & /*req*/, Response &res) {
  5007. res.set_file_content("./www/dir/test.html");
  5008. })
  5009. .Get("/file_content_with_content_type",
  5010. [&](const Request & /*req*/, Response &res) {
  5011. res.set_file_content("./www/file", "text/plain");
  5012. })
  5013. .Get("/invalid_file_content",
  5014. [&](const Request & /*req*/, Response &res) {
  5015. res.set_file_content("./www/dir/invalid_file_path");
  5016. })
  5017. .Get("/http_response_splitting",
  5018. [&](const Request & /*req*/, Response &res) {
  5019. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5020. EXPECT_EQ(0U, res.headers.size());
  5021. EXPECT_FALSE(res.has_header("a"));
  5022. res.set_header("a", "1\nSet-Cookie: a=1");
  5023. EXPECT_EQ(0U, res.headers.size());
  5024. EXPECT_FALSE(res.has_header("a"));
  5025. res.set_header("a", "1\rSet-Cookie: a=1");
  5026. EXPECT_EQ(0U, res.headers.size());
  5027. EXPECT_FALSE(res.has_header("a"));
  5028. res.set_header("a\r\nb", "0");
  5029. EXPECT_EQ(0U, res.headers.size());
  5030. EXPECT_FALSE(res.has_header("a"));
  5031. res.set_header("a\rb", "0");
  5032. EXPECT_EQ(0U, res.headers.size());
  5033. EXPECT_FALSE(res.has_header("a"));
  5034. res.set_header("a\nb", "0");
  5035. EXPECT_EQ(0U, res.headers.size());
  5036. EXPECT_FALSE(res.has_header("a"));
  5037. res.set_redirect("1\r\nSet-Cookie: a=1");
  5038. EXPECT_EQ(0U, res.headers.size());
  5039. EXPECT_FALSE(res.has_header("Location"));
  5040. })
  5041. .Get("/slow",
  5042. [&](const Request & /*req*/, Response &res) {
  5043. std::this_thread::sleep_for(std::chrono::seconds(4));
  5044. res.set_content("slow", "text/plain");
  5045. })
  5046. #if 0
  5047. .Post("/slowpost",
  5048. [&](const Request & /*req*/, Response &res) {
  5049. std::this_thread::sleep_for(std::chrono::seconds(2));
  5050. res.set_content("slow", "text/plain");
  5051. })
  5052. #endif
  5053. .Get("/remote_addr",
  5054. [&](const Request &req, Response &res) {
  5055. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5056. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5057. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5058. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5059. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5060. #endif
  5061. res.set_content(req.remote_addr, "text/plain");
  5062. })
  5063. .Get("/local_addr",
  5064. [&](const Request &req, Response &res) {
  5065. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5066. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5067. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5068. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5069. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5070. #endif
  5071. auto local_addr = req.local_addr;
  5072. auto local_port = std::to_string(req.local_port);
  5073. res.set_content(local_addr.append(":").append(local_port),
  5074. "text/plain");
  5075. })
  5076. .Get("/endwith%",
  5077. [&](const Request & /*req*/, Response &res) {
  5078. res.set_content("Hello World!", "text/plain");
  5079. })
  5080. .Get("/a\\+\\+b",
  5081. [&](const Request &req, Response &res) {
  5082. ASSERT_TRUE(req.has_param("a +b"));
  5083. auto val = req.get_param_value("a +b");
  5084. res.set_content(val, "text/plain");
  5085. })
  5086. .Get("/", [&](const Request & /*req*/,
  5087. Response &res) { res.set_redirect("/hi"); })
  5088. .Post("/1",
  5089. [](const Request & /*req*/, Response &res) {
  5090. res.set_redirect("/2", StatusCode::SeeOther_303);
  5091. })
  5092. .Get("/2",
  5093. [](const Request & /*req*/, Response &res) {
  5094. res.set_content("redirected.", "text/plain");
  5095. res.status = StatusCode::OK_200;
  5096. })
  5097. .Post("/person",
  5098. [&](const Request &req, Response &res) {
  5099. if (req.has_param("name") && req.has_param("note")) {
  5100. persons_[req.get_param_value("name")] =
  5101. req.get_param_value("note");
  5102. } else {
  5103. res.status = StatusCode::BadRequest_400;
  5104. }
  5105. })
  5106. .Put("/person",
  5107. [&](const Request &req, Response &res) {
  5108. if (req.has_param("name") && req.has_param("note")) {
  5109. persons_[req.get_param_value("name")] =
  5110. req.get_param_value("note");
  5111. } else {
  5112. res.status = StatusCode::BadRequest_400;
  5113. }
  5114. })
  5115. .Get("/person/(.*)",
  5116. [&](const Request &req, Response &res) {
  5117. string name = req.matches[1];
  5118. if (persons_.find(name) != persons_.end()) {
  5119. auto note = persons_[name];
  5120. res.set_content(note, "text/plain");
  5121. } else {
  5122. res.status = StatusCode::NotFound_404;
  5123. }
  5124. })
  5125. .Delete("/person",
  5126. [&](const Request &req, Response &res) {
  5127. if (req.has_param("name")) {
  5128. string name = req.get_param_value("name");
  5129. if (persons_.find(name) != persons_.end()) {
  5130. persons_.erase(name);
  5131. res.set_content("DELETED", "text/plain");
  5132. } else {
  5133. res.status = StatusCode::NotFound_404;
  5134. }
  5135. } else {
  5136. res.status = StatusCode::BadRequest_400;
  5137. }
  5138. })
  5139. .Post("/x-www-form-urlencoded-json",
  5140. [&](const Request &req, Response &res) {
  5141. auto json = req.get_param_value("json");
  5142. ASSERT_EQ(JSON_DATA, json);
  5143. res.set_content(json, "appliation/json");
  5144. res.status = StatusCode::OK_200;
  5145. })
  5146. .Get("/streamed-chunked",
  5147. [&](const Request & /*req*/, Response &res) {
  5148. res.set_chunked_content_provider(
  5149. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5150. sink.os << "123";
  5151. sink.os << "456";
  5152. sink.os << "789";
  5153. sink.done();
  5154. return true;
  5155. });
  5156. })
  5157. .Get("/streamed-chunked-with-prohibited-trailer",
  5158. [&](const Request & /*req*/, Response &res) {
  5159. auto i = new int(0);
  5160. // Declare both a prohibited trailer (Content-Length) and an
  5161. // allowed one
  5162. res.set_header("Trailer", "Content-Length, X-Allowed");
  5163. res.set_chunked_content_provider(
  5164. "text/plain",
  5165. [i](size_t /*offset*/, DataSink &sink) {
  5166. switch (*i) {
  5167. case 0: sink.os << "123"; break;
  5168. case 1: sink.os << "456"; break;
  5169. case 2: sink.os << "789"; break;
  5170. case 3: {
  5171. sink.done_with_trailer(
  5172. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5173. } break;
  5174. }
  5175. (*i)++;
  5176. return true;
  5177. },
  5178. [i](bool success) {
  5179. EXPECT_TRUE(success);
  5180. delete i;
  5181. });
  5182. })
  5183. .Get("/streamed-chunked2",
  5184. [&](const Request & /*req*/, Response &res) {
  5185. auto i = new int(0);
  5186. res.set_chunked_content_provider(
  5187. "text/plain",
  5188. [i](size_t /*offset*/, DataSink &sink) {
  5189. switch (*i) {
  5190. case 0: sink.os << "123"; break;
  5191. case 1: sink.os << "456"; break;
  5192. case 2: sink.os << "789"; break;
  5193. case 3: sink.done(); break;
  5194. }
  5195. (*i)++;
  5196. return true;
  5197. },
  5198. [i](bool success) {
  5199. EXPECT_TRUE(success);
  5200. delete i;
  5201. });
  5202. })
  5203. .Get("/streamed-chunked-with-trailer",
  5204. [&](const Request & /*req*/, Response &res) {
  5205. auto i = new int(0);
  5206. res.set_header("Trailer", "Dummy1, Dummy2");
  5207. res.set_chunked_content_provider(
  5208. "text/plain",
  5209. [i](size_t /*offset*/, DataSink &sink) {
  5210. switch (*i) {
  5211. case 0: sink.os << "123"; break;
  5212. case 1: sink.os << "456"; break;
  5213. case 2: sink.os << "789"; break;
  5214. case 3: {
  5215. sink.done_with_trailer(
  5216. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5217. } break;
  5218. }
  5219. (*i)++;
  5220. return true;
  5221. },
  5222. [i](bool success) {
  5223. EXPECT_TRUE(success);
  5224. delete i;
  5225. });
  5226. })
  5227. .Get("/streamed",
  5228. [&](const Request & /*req*/, Response &res) {
  5229. res.set_content_provider(
  5230. 6, "text/plain",
  5231. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5232. sink.os << (offset < 3 ? "a" : "b");
  5233. return true;
  5234. });
  5235. })
  5236. .Get("/streamed-without-length",
  5237. [&](const Request & /*req*/, Response &res) {
  5238. auto data = new std::string("abcdefg");
  5239. res.set_content_provider(
  5240. "text/plain",
  5241. [data](size_t offset, DataSink &sink) {
  5242. if (offset < data->size()) {
  5243. sink.os << data->substr(offset);
  5244. }
  5245. sink.done();
  5246. return true;
  5247. },
  5248. [data](bool success) {
  5249. EXPECT_TRUE(success);
  5250. delete data;
  5251. });
  5252. })
  5253. .Get("/streamed-with-range",
  5254. [&](const Request &req, Response &res) {
  5255. auto data = new std::string("abcdefg");
  5256. // An explicit status keeps the server from picking the 206 it
  5257. // would otherwise choose for a ranged request, so the response
  5258. // is not a partial representation.
  5259. auto status = req.get_param_value("status");
  5260. if (status == "200") {
  5261. res.status = StatusCode::OK_200;
  5262. } else if (status == "403") {
  5263. res.status = StatusCode::Forbidden_403;
  5264. }
  5265. res.set_content_provider(
  5266. data->size(), "text/plain",
  5267. [data](size_t offset, size_t length, DataSink &sink) {
  5268. size_t DATA_CHUNK_SIZE = 4;
  5269. const auto &d = *data;
  5270. auto out_len =
  5271. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5272. auto ret =
  5273. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5274. EXPECT_TRUE(ret);
  5275. return true;
  5276. },
  5277. [data, &req](bool success) {
  5278. EXPECT_EQ(success, !req.has_param("error"));
  5279. delete data;
  5280. });
  5281. })
  5282. .Get("/streamed-cancel",
  5283. [&](const Request & /*req*/, Response &res) {
  5284. res.set_content_provider(
  5285. size_t(-1), "text/plain",
  5286. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5287. sink.os << "data_chunk";
  5288. return true;
  5289. });
  5290. })
  5291. .Get("/regex-with-delimiter",
  5292. [&](const Request &req, Response & /*res*/) {
  5293. ASSERT_TRUE(req.has_param("key"));
  5294. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5295. })
  5296. .Get("/with-range",
  5297. [&](const Request & /*req*/, Response &res) {
  5298. res.set_content("abcdefg", "text/plain");
  5299. })
  5300. .Get("/test-start-time",
  5301. [&](const Request &req, Response & /*res*/) {
  5302. EXPECT_NE(req.start_time_,
  5303. std::chrono::steady_clock::time_point::min());
  5304. })
  5305. .Get("/with-range-customized-response",
  5306. [&](const Request & /*req*/, Response &res) {
  5307. res.status = StatusCode::BadRequest_400;
  5308. res.set_content(JSON_DATA, "application/json");
  5309. })
  5310. .Post("/chunked",
  5311. [&](const Request &req, Response & /*res*/) {
  5312. EXPECT_EQ(req.body, "dechunked post body");
  5313. })
  5314. .Post("/large-chunked",
  5315. [&](const Request &req, Response & /*res*/) {
  5316. std::string expected(6 * 30 * 1024u, 'a');
  5317. EXPECT_EQ(req.body, expected);
  5318. })
  5319. .Post("/multipart",
  5320. [&](const Request &req, Response & /*res*/) {
  5321. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5322. req.form.get_field_count("text2") +
  5323. req.form.get_field_count("file3") +
  5324. req.form.get_field_count("file4"));
  5325. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5326. req.form.get_file_count("file2"));
  5327. ASSERT_TRUE(!req.form.has_file("???"));
  5328. ASSERT_TRUE(!req.form.has_field("???"));
  5329. ASSERT_TRUE(req.body.empty());
  5330. {
  5331. const auto &text = req.form.get_field("text1");
  5332. EXPECT_EQ("text default", text);
  5333. }
  5334. {
  5335. const auto &text = req.form.get_field("text2");
  5336. EXPECT_EQ("aωb", text);
  5337. }
  5338. {
  5339. const auto &file = req.form.get_file("file1");
  5340. EXPECT_EQ("hello.txt", file.filename);
  5341. EXPECT_EQ("text/plain", file.content_type);
  5342. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5343. }
  5344. {
  5345. const auto &file = req.form.get_file("file2");
  5346. EXPECT_EQ("world.json", file.filename);
  5347. EXPECT_EQ("application/json", file.content_type);
  5348. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5349. }
  5350. {
  5351. const auto &text = req.form.get_field("file3");
  5352. EXPECT_EQ(0u, text.size());
  5353. }
  5354. {
  5355. const auto &text = req.form.get_field("file4");
  5356. EXPECT_EQ(0u, text.size());
  5357. }
  5358. })
  5359. .Post("/multipart/multi_file_values",
  5360. [&](const Request &req, Response & /*res*/) {
  5361. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5362. req.form.get_field_count("multi_text1"));
  5363. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5364. ASSERT_TRUE(!req.form.has_file("???"));
  5365. ASSERT_TRUE(!req.form.has_field("???"));
  5366. ASSERT_TRUE(req.body.empty());
  5367. {
  5368. const auto &text = req.form.get_field("text");
  5369. EXPECT_EQ("default text", text);
  5370. }
  5371. {
  5372. const auto &text1_values = req.form.get_fields("multi_text1");
  5373. EXPECT_EQ(2u, text1_values.size());
  5374. EXPECT_EQ("aaaaa", text1_values[0]);
  5375. EXPECT_EQ("bbbbb", text1_values[1]);
  5376. }
  5377. {
  5378. const auto &file1_values = req.form.get_files("multi_file1");
  5379. EXPECT_EQ(2u, file1_values.size());
  5380. auto file1 = file1_values[0];
  5381. EXPECT_EQ(file1.filename, "hello.txt");
  5382. EXPECT_EQ(file1.content_type, "text/plain");
  5383. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5384. auto file2 = file1_values[1];
  5385. EXPECT_EQ(file2.filename, "world.json");
  5386. EXPECT_EQ(file2.content_type, "application/json");
  5387. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5388. }
  5389. })
  5390. .Post("/empty",
  5391. [&](const Request &req, Response &res) {
  5392. EXPECT_EQ(req.body, "");
  5393. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5394. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5395. res.set_content("empty", "text/plain");
  5396. })
  5397. .Post("/empty-no-content-type",
  5398. [&](const Request &req, Response &res) {
  5399. EXPECT_EQ(req.body, "");
  5400. EXPECT_FALSE(req.has_header("Content-Type"));
  5401. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5402. res.set_content("empty-no-content-type", "text/plain");
  5403. })
  5404. .Post("/path-only",
  5405. [&](const Request &req, Response &res) {
  5406. EXPECT_EQ(req.body, "");
  5407. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5408. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5409. res.set_content("path-only", "text/plain");
  5410. })
  5411. .Post("/path-headers-only",
  5412. [&](const Request &req, Response &res) {
  5413. EXPECT_EQ(req.body, "");
  5414. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5415. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5416. EXPECT_EQ("world", req.get_header_value("hello"));
  5417. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5418. res.set_content("path-headers-only", "text/plain");
  5419. })
  5420. .Post("/post-large",
  5421. [&](const Request &req, Response &res) {
  5422. EXPECT_EQ(req.body, LARGE_DATA);
  5423. res.set_content(req.body, "text/plain");
  5424. })
  5425. .Post("/post-loopback",
  5426. [&](const Request &, Response &res,
  5427. ContentReader const &content_reader) {
  5428. std::string body;
  5429. content_reader([&](const char *data, size_t data_length) {
  5430. body.append(data, data_length);
  5431. return true;
  5432. });
  5433. res.set_content(body, "text/plain");
  5434. })
  5435. .Put("/put-loopback",
  5436. [&](const Request &, Response &res,
  5437. ContentReader const &content_reader) {
  5438. std::string body;
  5439. content_reader([&](const char *data, size_t data_length) {
  5440. body.append(data, data_length);
  5441. return true;
  5442. });
  5443. res.set_content(body, "text/plain");
  5444. })
  5445. .Patch("/patch-loopback",
  5446. [&](const Request &, Response &res,
  5447. ContentReader const &content_reader) {
  5448. std::string body;
  5449. content_reader([&](const char *data, size_t data_length) {
  5450. body.append(data, data_length);
  5451. return true;
  5452. });
  5453. res.set_content(body, "text/plain");
  5454. })
  5455. .Put("/empty-no-content-type",
  5456. [&](const Request &req, Response &res) {
  5457. EXPECT_EQ(req.body, "");
  5458. EXPECT_FALSE(req.has_header("Content-Type"));
  5459. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5460. res.set_content("empty-no-content-type", "text/plain");
  5461. })
  5462. .Put("/put",
  5463. [&](const Request &req, Response &res) {
  5464. EXPECT_EQ(req.body, "PUT");
  5465. res.set_content(req.body, "text/plain");
  5466. })
  5467. .Put("/put-large",
  5468. [&](const Request &req, Response &res) {
  5469. EXPECT_EQ(req.body, LARGE_DATA);
  5470. res.set_content(req.body, "text/plain");
  5471. })
  5472. .Patch("/patch",
  5473. [&](const Request &req, Response &res) {
  5474. EXPECT_EQ(req.body, "PATCH");
  5475. res.set_content(req.body, "text/plain");
  5476. })
  5477. .Delete("/delete",
  5478. [&](const Request & /*req*/, Response &res) {
  5479. res.set_content("DELETE", "text/plain");
  5480. })
  5481. .Delete("/delete-body",
  5482. [&](const Request &req, Response &res) {
  5483. EXPECT_EQ(req.body, "content");
  5484. res.set_content(req.body, "text/plain");
  5485. })
  5486. .Options(R"(\*)",
  5487. [&](const Request & /*req*/, Response &res) {
  5488. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5489. })
  5490. .CustomRoute("PROPFIND", "/dav/:id",
  5491. [&](const Request &req, Response &res) {
  5492. res.set_header("x-body-size",
  5493. std::to_string(req.body.size()));
  5494. res.set_header("x-matched-route", req.matched_route);
  5495. res.set_header("x-dav-id", req.path_params.at("id"));
  5496. res.status = StatusCode::MultiStatus_207;
  5497. res.set_content(req.body, "application/xml");
  5498. })
  5499. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5500. [&](const Request &req, Response &res) {
  5501. res.set_header("x-dav-match", req.matches[1]);
  5502. res.status = StatusCode::MultiStatus_207;
  5503. })
  5504. .CustomRoute("MKCOL", "/dav-mkcol",
  5505. [&](const Request &req, Response &res) {
  5506. EXPECT_TRUE(req.body.empty());
  5507. res.status = StatusCode::Created_201;
  5508. })
  5509. .CustomRoute(
  5510. "REPORT", "/dav-report",
  5511. [&](const Request & /*req*/, Response &res,
  5512. const ContentReader &content_reader) {
  5513. std::string body;
  5514. content_reader([&](const char *data, size_t data_length) {
  5515. body.append(data, data_length);
  5516. return true;
  5517. });
  5518. res.set_header("x-body-size", std::to_string(body.size()));
  5519. res.status = StatusCode::MultiStatus_207;
  5520. res.set_content(body, "application/xml");
  5521. })
  5522. .Get("/request-target",
  5523. [&](const Request &req, Response & /*res*/) {
  5524. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5525. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5526. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5527. })
  5528. .Get("/long-query-value",
  5529. [&](const Request &req, Response & /*res*/) {
  5530. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5531. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5532. })
  5533. .Get("/too-long-query-value",
  5534. [&](const Request &req, Response & /*res*/) {
  5535. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5536. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5537. })
  5538. .Get("/array-param",
  5539. [&](const Request &req, Response & /*res*/) {
  5540. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5541. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5542. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5543. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5544. })
  5545. .Get("/array-param-values",
  5546. [&](const Request &req, Response & /*res*/) {
  5547. auto values = req.get_param_values("array");
  5548. EXPECT_EQ(3u, values.size());
  5549. EXPECT_EQ("value1", values[0]);
  5550. EXPECT_EQ("value2", values[1]);
  5551. EXPECT_EQ("value3", values[2]);
  5552. auto empty = req.get_param_values("nonexistent");
  5553. EXPECT_TRUE(empty.empty());
  5554. })
  5555. .Post("/validate-no-multiple-headers",
  5556. [&](const Request &req, Response & /*res*/) {
  5557. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5558. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5559. })
  5560. .Post("/content_receiver",
  5561. [&](const Request &req, Response &res,
  5562. const ContentReader &content_reader) {
  5563. if (req.is_multipart_form_data()) {
  5564. std::vector<FormData> items;
  5565. content_reader(
  5566. [&](const FormData &file) {
  5567. items.push_back(file);
  5568. return true;
  5569. },
  5570. [&](const char *data, size_t data_length) {
  5571. items.back().content.append(data, data_length);
  5572. return true;
  5573. });
  5574. EXPECT_EQ(5u, items.size());
  5575. {
  5576. const auto &file = get_file_value(items, "text1");
  5577. EXPECT_TRUE(file.filename.empty());
  5578. EXPECT_EQ("text default", file.content);
  5579. }
  5580. {
  5581. const auto &file = get_file_value(items, "text2");
  5582. EXPECT_TRUE(file.filename.empty());
  5583. EXPECT_EQ("aωb", file.content);
  5584. }
  5585. {
  5586. const auto &file = get_file_value(items, "file1");
  5587. EXPECT_EQ("hello.txt", file.filename);
  5588. EXPECT_EQ("text/plain", file.content_type);
  5589. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5590. }
  5591. {
  5592. const auto &file = get_file_value(items, "file2");
  5593. EXPECT_EQ("world.json", file.filename);
  5594. EXPECT_EQ("application/json", file.content_type);
  5595. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5596. }
  5597. {
  5598. const auto &file = get_file_value(items, "file3");
  5599. EXPECT_TRUE(file.filename.empty());
  5600. EXPECT_EQ("application/octet-stream", file.content_type);
  5601. EXPECT_EQ(0u, file.content.size());
  5602. }
  5603. } else {
  5604. std::string body;
  5605. content_reader([&](const char *data, size_t data_length) {
  5606. EXPECT_EQ(7U, data_length);
  5607. body.append(data, data_length);
  5608. return true;
  5609. });
  5610. EXPECT_EQ(body, "content");
  5611. res.set_content(body, "text/plain");
  5612. }
  5613. })
  5614. .Put("/content_receiver",
  5615. [&](const Request & /*req*/, Response &res,
  5616. const ContentReader &content_reader) {
  5617. std::string body;
  5618. content_reader([&](const char *data, size_t data_length) {
  5619. body.append(data, data_length);
  5620. return true;
  5621. });
  5622. EXPECT_EQ(body, "content");
  5623. res.set_content(body, "text/plain");
  5624. })
  5625. .Patch("/content_receiver",
  5626. [&](const Request & /*req*/, Response &res,
  5627. const ContentReader &content_reader) {
  5628. std::string body;
  5629. content_reader([&](const char *data, size_t data_length) {
  5630. body.append(data, data_length);
  5631. return true;
  5632. });
  5633. EXPECT_EQ(body, "content");
  5634. res.set_content(body, "text/plain");
  5635. })
  5636. .Post("/query-string-and-body",
  5637. [&](const Request &req, Response & /*res*/) {
  5638. ASSERT_TRUE(req.has_param("key"));
  5639. EXPECT_EQ(req.get_param_value("key"), "value");
  5640. EXPECT_EQ(req.body, "content");
  5641. })
  5642. .Get("/last-request",
  5643. [&](const Request &req, Response & /*res*/) {
  5644. EXPECT_EQ("close", req.get_header_value("Connection"));
  5645. })
  5646. .Get(R"(/redirect/(\d+))",
  5647. [&](const Request &req, Response &res) {
  5648. auto num = std::stoi(req.matches[1]) + 1;
  5649. std::string url = "/redirect/" + std::to_string(num);
  5650. res.set_redirect(url);
  5651. })
  5652. .Post("/binary",
  5653. [&](const Request &req, Response &res) {
  5654. EXPECT_EQ(4U, req.body.size());
  5655. EXPECT_EQ("application/octet-stream",
  5656. req.get_header_value("Content-Type"));
  5657. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5658. res.set_content(req.body, "application/octet-stream");
  5659. })
  5660. .Put("/binary",
  5661. [&](const Request &req, Response &res) {
  5662. EXPECT_EQ(4U, req.body.size());
  5663. EXPECT_EQ("application/octet-stream",
  5664. req.get_header_value("Content-Type"));
  5665. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5666. res.set_content(req.body, "application/octet-stream");
  5667. })
  5668. .Patch("/binary",
  5669. [&](const Request &req, Response &res) {
  5670. EXPECT_EQ(4U, req.body.size());
  5671. EXPECT_EQ("application/octet-stream",
  5672. req.get_header_value("Content-Type"));
  5673. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5674. res.set_content(req.body, "application/octet-stream");
  5675. })
  5676. .Delete("/binary",
  5677. [&](const Request &req, Response &res) {
  5678. EXPECT_EQ(4U, req.body.size());
  5679. EXPECT_EQ("application/octet-stream",
  5680. req.get_header_value("Content-Type"));
  5681. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5682. res.set_content(req.body, "application/octet-stream");
  5683. })
  5684. .Get("/issue1772",
  5685. [&](const Request & /*req*/, Response &res) {
  5686. res.status = 401;
  5687. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5688. })
  5689. .Delete("/issue609",
  5690. [](const httplib::Request &, httplib::Response &res,
  5691. const httplib::ContentReader &) {
  5692. res.set_content("ok", "text/plain");
  5693. })
  5694. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5695. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5696. .Get("/compress",
  5697. [&](const Request & /*req*/, Response &res) {
  5698. res.set_content(
  5699. "12345678901234567890123456789012345678901234567890123456789"
  5700. "01234567890123456789012345678901234567890",
  5701. "text/plain");
  5702. })
  5703. .Get("/compress-with-charset",
  5704. [&](const Request & /*req*/, Response &res) {
  5705. res.set_content(
  5706. "12345678901234567890123456789012345678901234567890123456789"
  5707. "01234567890123456789012345678901234567890",
  5708. "application/json; charset=utf-8");
  5709. })
  5710. .Get("/nocompress",
  5711. [&](const Request & /*req*/, Response &res) {
  5712. res.set_content(
  5713. "12345678901234567890123456789012345678901234567890123456789"
  5714. "01234567890123456789012345678901234567890",
  5715. "application/octet-stream");
  5716. })
  5717. .Post("/compress-multipart",
  5718. [&](const Request &req, Response & /*res*/) {
  5719. EXPECT_EQ(2u, req.form.fields.size());
  5720. ASSERT_TRUE(!req.form.has_field("???"));
  5721. {
  5722. const auto &text = req.form.get_field("key1");
  5723. EXPECT_EQ("test", text);
  5724. }
  5725. {
  5726. const auto &text = req.form.get_field("key2");
  5727. EXPECT_EQ("--abcdefg123", text);
  5728. }
  5729. })
  5730. #endif
  5731. ;
  5732. persons_["john"] = "programmer";
  5733. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5734. svr_.wait_until_ready();
  5735. }
  5736. virtual void TearDown() {
  5737. svr_.stop();
  5738. if (!request_threads_.empty()) {
  5739. std::this_thread::sleep_for(std::chrono::seconds(1));
  5740. for (auto &t : request_threads_) {
  5741. t.join();
  5742. }
  5743. }
  5744. t_.join();
  5745. }
  5746. map<string, string> persons_;
  5747. #ifdef CPPHTTPLIB_SSL_ENABLED
  5748. SSLClient cli_;
  5749. SSLServer svr_;
  5750. #else
  5751. Client cli_;
  5752. Server svr_;
  5753. #endif
  5754. thread t_;
  5755. std::vector<thread> request_threads_;
  5756. };
  5757. TEST_F(ServerTest, GetMethod200) {
  5758. auto res = cli_.Get("/hi");
  5759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5760. EXPECT_EQ("HTTP/1.1", res->version);
  5761. EXPECT_EQ(StatusCode::OK_200, res->status);
  5762. EXPECT_EQ("OK", res->reason);
  5763. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5764. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5765. EXPECT_EQ("Hello World!", res->body);
  5766. }
  5767. TEST_F(ServerTest, GetEmptyFile) {
  5768. auto res = cli_.Get("/empty_file");
  5769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5770. EXPECT_EQ(StatusCode::OK_200, res->status);
  5771. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5772. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5773. EXPECT_EQ("", res->body);
  5774. }
  5775. TEST_F(ServerTest, GetFileContent) {
  5776. auto res = cli_.Get("/file_content");
  5777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5778. EXPECT_EQ(StatusCode::OK_200, res->status);
  5779. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5780. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5781. EXPECT_EQ("test.html", res->body);
  5782. }
  5783. TEST_F(ServerTest, GetFileContentWithRange) {
  5784. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5786. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5787. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5788. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5789. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5790. EXPECT_EQ("est", res->body);
  5791. }
  5792. TEST_F(ServerTest, GetFileContentWithContentType) {
  5793. auto res = cli_.Get("/file_content_with_content_type");
  5794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5795. EXPECT_EQ(StatusCode::OK_200, res->status);
  5796. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5797. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5798. EXPECT_EQ("file\n", res->body);
  5799. }
  5800. TEST_F(ServerTest, GetInvalidFileContent) {
  5801. auto res = cli_.Get("/invalid_file_content");
  5802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5803. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5804. }
  5805. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5806. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5808. EXPECT_EQ("HTTP/1.1", res->version);
  5809. EXPECT_EQ(StatusCode::OK_200, res->status);
  5810. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5811. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5812. EXPECT_EQ("Hello World!", res->body);
  5813. }
  5814. TEST_F(ServerTest, GetMethod302) {
  5815. auto res = cli_.Get("/");
  5816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5817. EXPECT_EQ(StatusCode::Found_302, res->status);
  5818. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5819. }
  5820. TEST_F(ServerTest, GetMethod302Redirect) {
  5821. cli_.set_follow_location(true);
  5822. auto res = cli_.Get("/");
  5823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5824. EXPECT_EQ(StatusCode::OK_200, res->status);
  5825. EXPECT_EQ("Hello World!", res->body);
  5826. EXPECT_EQ("/hi", res->location);
  5827. }
  5828. TEST_F(ServerTest, GetMethod404) {
  5829. auto res = cli_.Get("/invalid");
  5830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5831. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5832. }
  5833. TEST_F(ServerTest, HeadMethod200) {
  5834. auto res = cli_.Head("/hi");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. EXPECT_EQ(StatusCode::OK_200, res->status);
  5837. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5838. EXPECT_TRUE(res->body.empty());
  5839. }
  5840. TEST_F(ServerTest, HeadMethod200Static) {
  5841. auto res = cli_.Head("/mount/dir/index.html");
  5842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5843. EXPECT_EQ(StatusCode::OK_200, res->status);
  5844. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5845. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5846. EXPECT_TRUE(res->body.empty());
  5847. }
  5848. TEST_F(ServerTest, HeadMethod404) {
  5849. auto res = cli_.Head("/invalid");
  5850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5851. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5852. EXPECT_TRUE(res->body.empty());
  5853. }
  5854. TEST_F(ServerTest, GetMethodPersonJohn) {
  5855. auto res = cli_.Get("/person/john");
  5856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5857. EXPECT_EQ(StatusCode::OK_200, res->status);
  5858. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5859. EXPECT_EQ("programmer", res->body);
  5860. }
  5861. TEST_F(ServerTest, PostMethod1) {
  5862. auto res = cli_.Get("/person/john1");
  5863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5864. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5865. res = cli_.Post("/person", "name=john1&note=coder",
  5866. "application/x-www-form-urlencoded");
  5867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5868. ASSERT_EQ(StatusCode::OK_200, res->status);
  5869. res = cli_.Get("/person/john1");
  5870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5871. ASSERT_EQ(StatusCode::OK_200, res->status);
  5872. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5873. ASSERT_EQ("coder", res->body);
  5874. }
  5875. TEST_F(ServerTest, PostMethod2) {
  5876. auto res = cli_.Get("/person/john2");
  5877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5878. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5879. Params params;
  5880. params.emplace("name", "john2");
  5881. params.emplace("note", "coder");
  5882. res = cli_.Post("/person", params);
  5883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5884. ASSERT_EQ(StatusCode::OK_200, res->status);
  5885. res = cli_.Get("/person/john2");
  5886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5887. ASSERT_EQ(StatusCode::OK_200, res->status);
  5888. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5889. ASSERT_EQ("coder", res->body);
  5890. }
  5891. TEST_F(ServerTest, PutMethod3) {
  5892. auto res = cli_.Get("/person/john3");
  5893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5894. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5895. Params params;
  5896. params.emplace("name", "john3");
  5897. params.emplace("note", "coder");
  5898. res = cli_.Put("/person", params);
  5899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5900. ASSERT_EQ(StatusCode::OK_200, res->status);
  5901. res = cli_.Get("/person/john3");
  5902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5903. ASSERT_EQ(StatusCode::OK_200, res->status);
  5904. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5905. ASSERT_EQ("coder", res->body);
  5906. }
  5907. TEST_F(ServerTest, DeleteMethod1) {
  5908. auto res = cli_.Get("/person/john4");
  5909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5910. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5911. Params params;
  5912. params.emplace("name", "john4");
  5913. params.emplace("note", "coder");
  5914. res = cli_.Post("/person", params);
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. ASSERT_EQ(StatusCode::OK_200, res->status);
  5917. res = cli_.Get("/person/john4");
  5918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5919. ASSERT_EQ(StatusCode::OK_200, res->status);
  5920. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5921. ASSERT_EQ("coder", res->body);
  5922. Params delete_params;
  5923. delete_params.emplace("name", "john4");
  5924. res = cli_.Delete("/person", delete_params);
  5925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5926. ASSERT_EQ(StatusCode::OK_200, res->status);
  5927. ASSERT_EQ("DELETED", res->body);
  5928. res = cli_.Get("/person/john4");
  5929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5930. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5931. }
  5932. TEST_F(ServerTest, DeleteMethod2) {
  5933. auto res = cli_.Get("/person/john5");
  5934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5935. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5936. Params params;
  5937. params.emplace("name", "john5");
  5938. params.emplace("note", "developer");
  5939. res = cli_.Post("/person", params);
  5940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5941. ASSERT_EQ(StatusCode::OK_200, res->status);
  5942. res = cli_.Get("/person/john5");
  5943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5944. ASSERT_EQ(StatusCode::OK_200, res->status);
  5945. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5946. ASSERT_EQ("developer", res->body);
  5947. Params delete_params;
  5948. delete_params.emplace("name", "john5");
  5949. Headers headers;
  5950. headers.emplace("Custom-Header", "test-value");
  5951. res = cli_.Delete("/person", headers, delete_params);
  5952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5953. ASSERT_EQ(StatusCode::OK_200, res->status);
  5954. ASSERT_EQ("DELETED", res->body);
  5955. res = cli_.Get("/person/john5");
  5956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5957. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5958. }
  5959. TEST_F(ServerTest, DeleteMethod3) {
  5960. auto res = cli_.Get("/person/john6");
  5961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5962. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5963. Params params;
  5964. params.emplace("name", "john6");
  5965. params.emplace("note", "tester");
  5966. res = cli_.Post("/person", params);
  5967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5968. ASSERT_EQ(StatusCode::OK_200, res->status);
  5969. res = cli_.Get("/person/john6");
  5970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5971. ASSERT_EQ(StatusCode::OK_200, res->status);
  5972. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5973. ASSERT_EQ("tester", res->body);
  5974. Params delete_params;
  5975. delete_params.emplace("name", "john6");
  5976. Headers headers;
  5977. headers.emplace("Custom-Header", "test-value");
  5978. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5980. ASSERT_EQ(StatusCode::OK_200, res->status);
  5981. ASSERT_EQ("DELETED", res->body);
  5982. res = cli_.Get("/person/john6");
  5983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5984. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5985. }
  5986. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5987. Params params;
  5988. params.emplace("json", JSON_DATA);
  5989. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5991. ASSERT_EQ(StatusCode::OK_200, res->status);
  5992. ASSERT_EQ(JSON_DATA, res->body);
  5993. }
  5994. TEST_F(ServerTest, PostEmptyContent) {
  5995. auto res = cli_.Post("/empty", "", "text/plain");
  5996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5997. ASSERT_EQ(StatusCode::OK_200, res->status);
  5998. ASSERT_EQ("empty", res->body);
  5999. }
  6000. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6001. auto res = cli_.Post("/empty-no-content-type");
  6002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6003. ASSERT_EQ(StatusCode::OK_200, res->status);
  6004. ASSERT_EQ("empty-no-content-type", res->body);
  6005. }
  6006. TEST_F(ServerTest, PostPathOnly) {
  6007. auto res = cli_.Post("/path-only");
  6008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6009. ASSERT_EQ(StatusCode::OK_200, res->status);
  6010. ASSERT_EQ("path-only", res->body);
  6011. }
  6012. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6013. auto res = cli_.Post("/path-headers-only",
  6014. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6016. ASSERT_EQ(StatusCode::OK_200, res->status);
  6017. ASSERT_EQ("path-headers-only", res->body);
  6018. }
  6019. TEST_F(ServerTest, PostLarge) {
  6020. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6022. ASSERT_EQ(StatusCode::OK_200, res->status);
  6023. EXPECT_EQ(LARGE_DATA, res->body);
  6024. }
  6025. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6026. auto res = cli_.Put("/empty-no-content-type");
  6027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6028. ASSERT_EQ(StatusCode::OK_200, res->status);
  6029. ASSERT_EQ("empty-no-content-type", res->body);
  6030. }
  6031. TEST_F(ServerTest, GetMethodDir) {
  6032. auto res = cli_.Get("/dir/");
  6033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6034. EXPECT_EQ(StatusCode::OK_200, res->status);
  6035. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6036. auto body = R"(<html>
  6037. <head>
  6038. </head>
  6039. <body>
  6040. <a href="/dir/test.html">Test</a>
  6041. <a href="/hi">hi</a>
  6042. </body>
  6043. </html>
  6044. )";
  6045. EXPECT_EQ(body, res->body);
  6046. }
  6047. TEST_F(ServerTest, GetMethodDirTest) {
  6048. auto res = cli_.Get("/dir/test.html");
  6049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6050. EXPECT_EQ(StatusCode::OK_200, res->status);
  6051. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6052. EXPECT_EQ("test.html", res->body);
  6053. }
  6054. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6055. auto res = cli_.Get("/dir/../dir/test.html");
  6056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6057. EXPECT_EQ(StatusCode::OK_200, res->status);
  6058. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6059. EXPECT_EQ("test.html", res->body);
  6060. }
  6061. TEST_F(ServerTest, GetMethodInvalidPath) {
  6062. auto res = cli_.Get("/dir/../test.html");
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6065. }
  6066. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6067. auto res = cli_.Get("/../www/dir/test.html");
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6070. }
  6071. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6072. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6074. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6075. }
  6076. TEST_F(ServerTest, GetMethodDirMountTest) {
  6077. auto res = cli_.Get("/mount/dir/test.html");
  6078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6079. EXPECT_EQ(StatusCode::OK_200, res->status);
  6080. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6081. EXPECT_EQ("test.html", res->body);
  6082. }
  6083. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6084. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6086. EXPECT_EQ(StatusCode::OK_200, res->status);
  6087. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6088. EXPECT_EQ("test.html", res->body);
  6089. }
  6090. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6091. auto res = cli_.Get("/mount/dir/../test.html");
  6092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6093. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6094. }
  6095. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6096. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6098. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6099. }
  6100. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6101. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6103. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6104. }
  6105. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6106. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6108. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6109. }
  6110. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6111. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6113. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6114. }
  6115. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6116. auto res = cli_.Get("/mount/dir");
  6117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6118. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6119. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6120. }
  6121. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6122. auto res = cli_.Get("//dir");
  6123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6124. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6125. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6126. }
  6127. TEST_F(ServerTest, PostMethod303) {
  6128. auto res = cli_.Post("/1", "body", "text/plain");
  6129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6130. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6131. EXPECT_EQ("/2", res->get_header_value("Location"));
  6132. }
  6133. TEST_F(ServerTest, PostMethod303Redirect) {
  6134. cli_.set_follow_location(true);
  6135. auto res = cli_.Post("/1", "body", "text/plain");
  6136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6137. EXPECT_EQ(StatusCode::OK_200, res->status);
  6138. EXPECT_EQ("redirected.", res->body);
  6139. EXPECT_EQ("/2", res->location);
  6140. }
  6141. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6142. auto res = cli_.Get("/dir/test.abcde");
  6143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6144. EXPECT_EQ(StatusCode::OK_200, res->status);
  6145. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6146. EXPECT_EQ("abcde", res->body);
  6147. }
  6148. TEST_F(ServerTest, StaticFileRange) {
  6149. auto res =
  6150. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6152. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6153. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6154. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6155. EXPECT_EQ(true, res->has_header("Content-Range"));
  6156. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6157. EXPECT_EQ(std::string("cd"), res->body);
  6158. }
  6159. TEST_F(ServerTest, StaticFileRanges) {
  6160. auto res = cli_.Get("/dir/test.abcde",
  6161. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6164. EXPECT_TRUE(
  6165. res->get_header_value("Content-Type")
  6166. .find(
  6167. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6168. 0);
  6169. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6170. }
  6171. TEST_F(ServerTest, StaticFileRangeHead) {
  6172. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6175. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6176. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6177. EXPECT_EQ(true, res->has_header("Content-Range"));
  6178. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6179. }
  6180. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6181. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6183. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6184. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6185. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6186. EXPECT_EQ(true, res->has_header("Content-Range"));
  6187. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6188. res->get_header_value("Content-Range"));
  6189. EXPECT_EQ("LAST\n", res->body);
  6190. }
  6191. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6192. auto res =
  6193. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6195. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6196. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6197. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6198. EXPECT_EQ(true, res->has_header("Content-Range"));
  6199. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6200. }
  6201. TEST_F(ServerTest, StaticFileBigFile) {
  6202. auto res = cli_.Get("/dir/1MB.txt");
  6203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6204. EXPECT_EQ(StatusCode::OK_200, res->status);
  6205. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6206. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6207. }
  6208. TEST_F(ServerTest, InvalidBaseDirMount) {
  6209. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6210. }
  6211. TEST_F(ServerTest, Binary) {
  6212. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6213. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6214. "application/octet-stream");
  6215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6216. ASSERT_EQ(StatusCode::OK_200, res->status);
  6217. ASSERT_EQ(4U, res->body.size());
  6218. res = cli_.Put("/binary", binary.data(), binary.size(),
  6219. "application/octet-stream");
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. ASSERT_EQ(StatusCode::OK_200, res->status);
  6222. ASSERT_EQ(4U, res->body.size());
  6223. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6224. "application/octet-stream");
  6225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6226. ASSERT_EQ(StatusCode::OK_200, res->status);
  6227. ASSERT_EQ(4U, res->body.size());
  6228. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6229. "application/octet-stream");
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. ASSERT_EQ(StatusCode::OK_200, res->status);
  6232. ASSERT_EQ(4U, res->body.size());
  6233. }
  6234. TEST_F(ServerTest, BinaryString) {
  6235. auto binary = std::string("\x00\x01\x02\x03", 4);
  6236. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. ASSERT_EQ(StatusCode::OK_200, res->status);
  6239. ASSERT_EQ(4U, res->body.size());
  6240. res = cli_.Put("/binary", binary, "application/octet-stream");
  6241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6242. ASSERT_EQ(StatusCode::OK_200, res->status);
  6243. ASSERT_EQ(4U, res->body.size());
  6244. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6246. ASSERT_EQ(StatusCode::OK_200, res->status);
  6247. ASSERT_EQ(4U, res->body.size());
  6248. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6250. ASSERT_EQ(StatusCode::OK_200, res->status);
  6251. ASSERT_EQ(4U, res->body.size());
  6252. }
  6253. TEST_F(ServerTest, EmptyRequest) {
  6254. auto res = cli_.Get("");
  6255. ASSERT_TRUE(!res);
  6256. EXPECT_EQ(Error::Connection, res.error());
  6257. }
  6258. TEST_F(ServerTest, LongRequest) {
  6259. std::string request;
  6260. for (size_t i = 0; i < 545; i++) {
  6261. request += "/TooLongRequest";
  6262. }
  6263. request += "OK";
  6264. auto res = cli_.Get(request.c_str());
  6265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6266. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6267. }
  6268. TEST_F(ServerTest, TooLongRequest) {
  6269. std::string request;
  6270. for (size_t i = 0; i < 546; i++) {
  6271. request += "/TooLongRequest";
  6272. }
  6273. request += "_NG";
  6274. auto start = std::chrono::high_resolution_clock::now();
  6275. cli_.set_keep_alive(true);
  6276. auto res = cli_.Get(request.c_str());
  6277. auto end = std::chrono::high_resolution_clock::now();
  6278. auto elapsed =
  6279. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6280. .count();
  6281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6282. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6283. EXPECT_LE(elapsed, 1000);
  6284. EXPECT_EQ("close", res->get_header_value("Connection"));
  6285. EXPECT_FALSE(cli_.is_socket_open());
  6286. }
  6287. TEST_F(ServerTest, AlmostTooLongRequest) {
  6288. // test for #2046 - URI length check shouldn't include other content on req
  6289. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6290. // leading /, space, HTTP/1.1)
  6291. std::string request =
  6292. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6293. auto res = cli_.Get(request.c_str());
  6294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6295. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6296. }
  6297. TEST_F(ServerTest, LongHeader) {
  6298. Request req;
  6299. req.method = "GET";
  6300. req.path = "/hi";
  6301. std::string host_and_port;
  6302. host_and_port += HOST;
  6303. host_and_port += ":";
  6304. host_and_port += std::to_string(PORT);
  6305. req.headers.emplace("Host", host_and_port.c_str());
  6306. req.headers.emplace("Accept", "*/*");
  6307. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6308. req.headers.emplace(
  6309. "Header-Name",
  6310. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6311. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6312. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6313. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6314. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6315. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6316. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6317. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6318. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6319. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6320. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6321. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6322. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6323. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6324. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6325. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6326. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6327. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6328. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6329. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6330. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6331. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6332. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6333. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6334. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6335. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6336. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6337. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6338. "@@@@@@@@@@@@@@@@");
  6339. auto res = std::make_shared<Response>();
  6340. auto error = Error::Success;
  6341. auto ret = cli_.send(req, *res, error);
  6342. ASSERT_TRUE(ret);
  6343. EXPECT_EQ(StatusCode::OK_200, res->status);
  6344. }
  6345. TEST_F(ServerTest, LongQueryValue) {
  6346. auto start = std::chrono::high_resolution_clock::now();
  6347. cli_.set_keep_alive(true);
  6348. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6349. auto end = std::chrono::high_resolution_clock::now();
  6350. auto elapsed =
  6351. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6352. .count();
  6353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6354. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6355. EXPECT_LE(elapsed, 1000);
  6356. EXPECT_EQ("close", res->get_header_value("Connection"));
  6357. EXPECT_FALSE(cli_.is_socket_open());
  6358. }
  6359. TEST_F(ServerTest, TooLongQueryValue) {
  6360. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6361. ASSERT_FALSE(res);
  6362. EXPECT_EQ(Error::Read, res.error());
  6363. }
  6364. TEST_F(ServerTest, TooLongHeader) {
  6365. Request req;
  6366. req.method = "GET";
  6367. req.path = "/hi";
  6368. std::string host_and_port;
  6369. host_and_port += HOST;
  6370. host_and_port += ":";
  6371. host_and_port += std::to_string(PORT);
  6372. req.headers.emplace("Host", host_and_port.c_str());
  6373. req.headers.emplace("Accept", "*/*");
  6374. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6375. req.headers.emplace(
  6376. "Header-Name",
  6377. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6378. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6379. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6380. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6381. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6382. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6383. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6384. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6385. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6386. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6387. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6388. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6389. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6390. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6391. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6392. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6393. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6394. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6395. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6396. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6397. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6398. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6399. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6400. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6401. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6402. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6403. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6404. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6405. "@@@@@@@@@@@@@@@@@");
  6406. auto res = std::make_shared<Response>();
  6407. auto error = Error::Success;
  6408. auto ret = cli_.send(req, *res, error);
  6409. ASSERT_TRUE(ret);
  6410. EXPECT_EQ(StatusCode::OK_200, res->status);
  6411. }
  6412. TEST_F(ServerTest, HeaderCountAtLimit) {
  6413. // Test with headers just under the 100 limit
  6414. httplib::Headers headers;
  6415. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6416. // This should keep us just under the 100 header limit
  6417. for (int i = 0; i < 95; i++) {
  6418. std::string name = "X-Test-Header-" + std::to_string(i);
  6419. std::string value = "value" + std::to_string(i);
  6420. headers.emplace(name, value);
  6421. }
  6422. // This should work fine as we're under the limit
  6423. auto res = cli_.Get("/hi", headers);
  6424. EXPECT_TRUE(res);
  6425. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6426. }
  6427. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6428. // Test with many headers to exceed the 100 limit
  6429. httplib::Headers headers;
  6430. // Add 150 headers to definitely exceed the 100 limit
  6431. for (int i = 0; i < 150; i++) {
  6432. std::string name = "X-Test-Header-" + std::to_string(i);
  6433. std::string value = "value" + std::to_string(i);
  6434. headers.emplace(name, value);
  6435. }
  6436. // This should fail due to exceeding header count limit
  6437. cli_.set_keep_alive(true);
  6438. auto res = cli_.Get("/hi", headers);
  6439. // The server should respond with 400 Bad Request
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6442. EXPECT_EQ("close", res->get_header_value("Connection"));
  6443. EXPECT_FALSE(cli_.is_socket_open());
  6444. }
  6445. TEST_F(ServerTest, PercentEncoding) {
  6446. auto res = cli_.Get("/e%6edwith%");
  6447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6448. EXPECT_EQ(StatusCode::OK_200, res->status);
  6449. }
  6450. TEST_F(ServerTest, PercentEncodingUnicode) {
  6451. auto res = cli_.Get("/e%u006edwith%");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. EXPECT_EQ(StatusCode::OK_200, res->status);
  6454. }
  6455. TEST_F(ServerTest, InvalidPercentEncoding) {
  6456. auto res = cli_.Get("/%endwith%");
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6459. }
  6460. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6461. auto res = cli_.Get("/%uendwith%");
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6464. }
  6465. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6466. auto res = cli_.Get("/hello?aaa=bbb%");
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6469. }
  6470. TEST_F(ServerTest, PlusSignEncoding) {
  6471. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::OK_200, res->status);
  6474. EXPECT_EQ("a +b", res->body);
  6475. }
  6476. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6477. // This test simulates a potential DoS attack using many headers
  6478. // to verify our security fix prevents memory exhaustion
  6479. httplib::Headers attack_headers;
  6480. // Attempt to add many headers like an attacker would (200 headers to far
  6481. // exceed limit)
  6482. for (int i = 0; i < 200; i++) {
  6483. std::string name = "X-Attack-Header-" + std::to_string(i);
  6484. std::string value = "attack_payload_" + std::to_string(i);
  6485. attack_headers.emplace(name, value);
  6486. }
  6487. // Try to POST with excessive headers
  6488. cli_.set_keep_alive(true);
  6489. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6490. // Should either fail or return 400 Bad Request due to security limit
  6491. if (res) {
  6492. // If we get a response, it should be 400 Bad Request
  6493. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6494. EXPECT_EQ("close", res->get_header_value("Connection"));
  6495. }
  6496. EXPECT_FALSE(cli_.is_socket_open());
  6497. }
  6498. TEST_F(ServerTest, MultipartFormData) {
  6499. UploadFormDataItems items = {
  6500. {"text1", "text default", "", ""},
  6501. {"text2", "aωb", "", ""},
  6502. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6503. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6504. {"file3", "", "", "application/octet-stream"},
  6505. {"file4", "", "", " application/json tmp-string "}};
  6506. auto res = cli_.Post("/multipart", items);
  6507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6508. EXPECT_EQ(StatusCode::OK_200, res->status);
  6509. }
  6510. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6511. UploadFormDataItems items = {
  6512. {"text", "default text", "", ""},
  6513. {"multi_text1", "aaaaa", "", ""},
  6514. {"multi_text1", "bbbbb", "", ""},
  6515. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6516. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6517. "application/json"},
  6518. };
  6519. auto res = cli_.Post("/multipart/multi_file_values", items);
  6520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6521. EXPECT_EQ(StatusCode::OK_200, res->status);
  6522. }
  6523. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6524. auto res = cli_.Get("/hi");
  6525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6526. EXPECT_EQ(StatusCode::OK_200, res->status);
  6527. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6528. EXPECT_EQ("Hello World!", res->body);
  6529. }
  6530. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6531. Request req;
  6532. req.method = "POST";
  6533. req.path = "/chunked";
  6534. std::string host_and_port;
  6535. host_and_port += HOST;
  6536. host_and_port += ":";
  6537. host_and_port += std::to_string(PORT);
  6538. req.headers.emplace("Host", host_and_port.c_str());
  6539. req.headers.emplace("Accept", "*/*");
  6540. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6541. req.headers.emplace("Content-Type", "text/plain");
  6542. req.headers.emplace("Content-Length", "0");
  6543. req.headers.emplace(
  6544. "Transfer-Encoding",
  6545. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6546. // Client does not chunk, so make a chunked body manually.
  6547. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6548. auto res = std::make_shared<Response>();
  6549. auto error = Error::Success;
  6550. auto ret = cli_.send(req, *res, error);
  6551. ASSERT_TRUE(ret);
  6552. EXPECT_EQ(StatusCode::OK_200, res->status);
  6553. }
  6554. template <typename ClientT>
  6555. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6556. int expected_status) {
  6557. Request req;
  6558. req.method = "POST";
  6559. req.path = "/chunked";
  6560. std::string host_and_port;
  6561. host_and_port += HOST;
  6562. host_and_port += ":";
  6563. host_and_port += std::to_string(PORT);
  6564. req.headers.emplace("Host", host_and_port.c_str());
  6565. req.headers.emplace("Content-Length", "0");
  6566. req.headers.emplace("Transfer-Encoding", "chunked");
  6567. req.body = body;
  6568. auto res = std::make_shared<Response>();
  6569. auto error = Error::Success;
  6570. ASSERT_TRUE(cli.send(req, *res, error));
  6571. EXPECT_EQ(expected_status, res->status);
  6572. }
  6573. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6574. // rather than treat them as valid lengths.
  6575. template <typename ClientT>
  6576. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6577. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6578. }
  6579. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6580. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6581. }
  6582. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6583. expect_chunked_body_rejected(
  6584. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6585. }
  6586. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6587. // chunk-size line carries no CR, LF or other control character ahead of its
  6588. // terminator. Such a line must be refused rather than read as extension text.
  6589. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6590. expect_chunked_body_rejected(
  6591. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6592. }
  6593. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6594. expect_chunked_body_rejected(
  6595. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6596. }
  6597. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6598. expect_chunked_body_rejected(
  6599. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6600. }
  6601. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6602. // The literal stays split: a hex escape consumes every hex digit that
  6603. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6604. expect_chunked_body_rejected(
  6605. cli_, "4;a\x01"
  6606. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6607. }
  6608. TEST_F(ServerTest, AcceptsChunkExtension) {
  6609. expect_chunked_body_status(cli_,
  6610. "4;name=value\r\ndech\r\n"
  6611. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6612. "0;last\r\n\r\n",
  6613. StatusCode::OK_200);
  6614. }
  6615. TEST_F(ServerTest, GetStreamed2) {
  6616. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6619. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6620. EXPECT_EQ(true, res->has_header("Content-Range"));
  6621. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6622. EXPECT_EQ(std::string("ab"), res->body);
  6623. }
  6624. TEST_F(ServerTest, GetStreamed) {
  6625. auto res = cli_.Get("/streamed");
  6626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6627. EXPECT_EQ(StatusCode::OK_200, res->status);
  6628. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6629. EXPECT_EQ(std::string("aaabbb"), res->body);
  6630. }
  6631. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6632. auto res = cli_.Get("/streamed-without-length",
  6633. Headers{make_range_header({{0, -1}})});
  6634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6635. EXPECT_EQ(StatusCode::OK_200, res->status);
  6636. EXPECT_EQ(false, res->has_header("Content-Length"));
  6637. EXPECT_EQ(false, res->has_header("Content-Range"));
  6638. EXPECT_EQ(std::string("abcdefg"), res->body);
  6639. }
  6640. TEST_F(ServerTest, GetStreamedWithRange1) {
  6641. auto res =
  6642. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6644. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6645. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6646. EXPECT_EQ(true, res->has_header("Content-Range"));
  6647. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6648. EXPECT_EQ(std::string("def"), res->body);
  6649. }
  6650. TEST_F(ServerTest, GetStreamedWithRange2) {
  6651. auto res =
  6652. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6654. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6655. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6656. EXPECT_EQ(true, res->has_header("Content-Range"));
  6657. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6658. EXPECT_EQ(std::string("bcdefg"), res->body);
  6659. }
  6660. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6661. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6663. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6664. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6665. EXPECT_EQ(true, res->has_header("Content-Range"));
  6666. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6667. EXPECT_EQ(std::string("efg"), res->body);
  6668. }
  6669. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6670. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6671. // the entire representation.
  6672. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6673. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6675. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6676. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6677. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6678. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6679. }
  6680. }
  6681. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6682. auto res =
  6683. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6686. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6687. EXPECT_EQ(false, res->has_header("Content-Range"));
  6688. EXPECT_EQ(0U, res->body.size());
  6689. }
  6690. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6691. // Only a 206 is served as a partial representation. Under any other status
  6692. // `apply_ranges()` reported the full content length, so the body must match
  6693. // that header, and the content provider must never be asked for an offset
  6694. // outside the representation.
  6695. auto check = [&](int status, const char *range) {
  6696. auto path =
  6697. std::string("/streamed-with-range?status=") + std::to_string(status);
  6698. auto ctx = path + " Range: " + range;
  6699. auto res = cli_.Get(path, Headers{{"Range", range}});
  6700. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6701. EXPECT_EQ(status, res->status) << ctx;
  6702. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6704. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6705. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6706. };
  6707. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6708. check(403, "bytes=3-5");
  6709. // The offset is far past the representation.
  6710. check(403, "bytes=100000-100200");
  6711. // `first_pos` is still -1 here, and the bounds asserts in
  6712. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6713. check(403, "bytes=-3");
  6714. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6715. // multipart branch would have written one that is empty.
  6716. check(403, "bytes=1-2, 4-5");
  6717. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6718. // covers the whole representation.
  6719. check(200, "bytes=3-5");
  6720. check(200, "bytes=1-2, 4-5");
  6721. }
  6722. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6723. auto res =
  6724. cli_.Get("/streamed-with-range",
  6725. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6726. "92233720368547758079223372036854775807"}});
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6729. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6730. EXPECT_EQ(false, res->has_header("Content-Range"));
  6731. EXPECT_EQ(0U, res->body.size());
  6732. }
  6733. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6734. auto res = cli_.Get(
  6735. "/with-range",
  6736. Headers{{"Range",
  6737. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6738. {"Accept-Encoding", ""}});
  6739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6740. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6741. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6742. EXPECT_EQ(true, res->has_header("Content-Range"));
  6743. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6744. EXPECT_EQ(std::string("abcdefg"), res->body);
  6745. }
  6746. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6747. auto res = cli_.Get("/with-range", Headers{
  6748. {"Range", "bytes=0-"},
  6749. {"Accept-Encoding", ""},
  6750. });
  6751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6752. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6753. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6754. EXPECT_EQ(true, res->has_header("Content-Range"));
  6755. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6756. EXPECT_EQ(std::string("abcdefg"), res->body);
  6757. }
  6758. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6759. auto res = cli_.Get("/streamed-with-range",
  6760. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6762. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6763. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6764. EXPECT_EQ(false, res->has_header("Content-Range"));
  6765. EXPECT_EQ(267U, res->body.size());
  6766. // Check that both range contents are present
  6767. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6768. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6769. // Check that Content-Range headers are present for both ranges
  6770. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6771. std::string::npos);
  6772. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6773. std::string::npos);
  6774. }
  6775. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6776. Ranges ranges;
  6777. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6778. ranges.emplace_back(0, -1);
  6779. }
  6780. auto res = cli_.Get("/streamed-with-range?error",
  6781. Headers{{make_range_header(ranges)}});
  6782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6783. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6784. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6785. EXPECT_EQ(false, res->has_header("Content-Range"));
  6786. EXPECT_EQ(0U, res->body.size());
  6787. }
  6788. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6789. auto res = cli_.Get("/streamed-with-range",
  6790. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6792. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6793. EXPECT_EQ(5U, res->body.size());
  6794. // Check that overlapping ranges are coalesced into a single range
  6795. EXPECT_EQ("bcdef", res->body);
  6796. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6797. // Should be single range, not multipart
  6798. EXPECT_TRUE(res->has_header("Content-Range"));
  6799. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6800. }
  6801. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6802. auto res = cli_.Get("/streamed-with-range",
  6803. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6805. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6806. EXPECT_EQ(268U, res->body.size());
  6807. // Check that both range contents are present
  6808. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6809. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6810. // Check that Content-Range headers are present for both ranges
  6811. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6812. std::string::npos);
  6813. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6814. std::string::npos);
  6815. }
  6816. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6817. auto res = cli_.Get("/streamed-with-range",
  6818. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6820. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6821. EXPECT_EQ(269U, res->body.size());
  6822. // Check that both duplicate range contents are present
  6823. size_t first_abc = res->body.find("abc\r\n");
  6824. EXPECT_TRUE(first_abc != std::string::npos);
  6825. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6826. EXPECT_TRUE(second_abc != std::string::npos);
  6827. // Check that Content-Range headers are present for both ranges
  6828. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6829. EXPECT_TRUE(first_range != std::string::npos);
  6830. size_t second_range =
  6831. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6832. EXPECT_TRUE(second_range != std::string::npos);
  6833. }
  6834. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6835. auto res =
  6836. cli_.Get("/streamed-with-range?error",
  6837. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6839. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6840. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6841. EXPECT_EQ(false, res->has_header("Content-Range"));
  6842. EXPECT_EQ(0U, res->body.size());
  6843. }
  6844. TEST_F(ServerTest, GetStreamedEndless) {
  6845. uint64_t offset = 0;
  6846. auto res = cli_.Get("/streamed-cancel",
  6847. [&](const char * /*data*/, uint64_t data_length) {
  6848. if (offset < 100) {
  6849. offset += data_length;
  6850. return true;
  6851. }
  6852. return false;
  6853. });
  6854. ASSERT_TRUE(!res);
  6855. EXPECT_EQ(Error::Canceled, res.error());
  6856. }
  6857. TEST_F(ServerTest, ClientStop) {
  6858. std::atomic_size_t count{4};
  6859. std::vector<std::thread> threads;
  6860. for (auto i = count.load(); i != 0; --i) {
  6861. threads.emplace_back([&]() {
  6862. auto res = cli_.Get("/streamed-cancel",
  6863. [&](const char *, uint64_t) { return true; });
  6864. --count;
  6865. ASSERT_TRUE(!res);
  6866. EXPECT_TRUE(res.error() == Error::Canceled ||
  6867. res.error() == Error::Read || res.error() == Error::Write);
  6868. });
  6869. }
  6870. std::this_thread::sleep_for(std::chrono::seconds(2));
  6871. while (count != 0) {
  6872. cli_.stop();
  6873. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6874. }
  6875. for (auto &t : threads) {
  6876. t.join();
  6877. }
  6878. }
  6879. TEST_F(ServerTest, GetWithRange1) {
  6880. auto res = cli_.Get("/with-range", Headers{
  6881. make_range_header({{3, 5}}),
  6882. {"Accept-Encoding", ""},
  6883. });
  6884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6885. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6886. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6887. EXPECT_EQ(true, res->has_header("Content-Range"));
  6888. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6889. EXPECT_EQ(std::string("def"), res->body);
  6890. }
  6891. TEST_F(ServerTest, GetWithRange2) {
  6892. auto res = cli_.Get("/with-range", Headers{
  6893. make_range_header({{1, -1}}),
  6894. {"Accept-Encoding", ""},
  6895. });
  6896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6897. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6898. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6899. EXPECT_EQ(true, res->has_header("Content-Range"));
  6900. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6901. EXPECT_EQ(std::string("bcdefg"), res->body);
  6902. }
  6903. TEST_F(ServerTest, GetWithRange3) {
  6904. auto res = cli_.Get("/with-range", Headers{
  6905. make_range_header({{0, 0}}),
  6906. {"Accept-Encoding", ""},
  6907. });
  6908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6909. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6910. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6911. EXPECT_EQ(true, res->has_header("Content-Range"));
  6912. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6913. EXPECT_EQ(std::string("a"), res->body);
  6914. }
  6915. TEST_F(ServerTest, GetWithRange4) {
  6916. auto res = cli_.Get("/with-range", Headers{
  6917. make_range_header({{-1, 2}}),
  6918. {"Accept-Encoding", ""},
  6919. });
  6920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6921. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6922. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6923. EXPECT_EQ(true, res->has_header("Content-Range"));
  6924. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6925. EXPECT_EQ(std::string("fg"), res->body);
  6926. }
  6927. TEST_F(ServerTest, GetWithRange5) {
  6928. auto res = cli_.Get("/with-range", Headers{
  6929. make_range_header({{0, 5}}),
  6930. {"Accept-Encoding", ""},
  6931. });
  6932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6933. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6934. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6935. EXPECT_EQ(true, res->has_header("Content-Range"));
  6936. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6937. EXPECT_EQ(std::string("abcdef"), res->body);
  6938. }
  6939. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6940. auto res =
  6941. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6944. }
  6945. TEST_F(ServerTest, GetWithRangeMultipart) {
  6946. auto res =
  6947. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6949. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6950. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6951. EXPECT_EQ(false, res->has_header("Content-Range"));
  6952. EXPECT_EQ(267U, res->body.size());
  6953. }
  6954. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6955. auto res = cli_.Get("/with-range",
  6956. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6958. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6959. }
  6960. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6961. auto res = cli_.Get("/with-range-customized-response",
  6962. Headers{{make_range_header({{1, 2}})}});
  6963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6964. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6965. EXPECT_EQ(true, res->has_header("Content-Length"));
  6966. EXPECT_EQ(false, res->has_header("Content-Range"));
  6967. EXPECT_EQ(JSON_DATA, res->body);
  6968. }
  6969. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6970. auto res = cli_.Get("/with-range-customized-response",
  6971. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6973. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6974. EXPECT_EQ(true, res->has_header("Content-Length"));
  6975. EXPECT_EQ(false, res->has_header("Content-Range"));
  6976. EXPECT_EQ(JSON_DATA, res->body);
  6977. }
  6978. TEST_F(ServerTest, Issue1772) {
  6979. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6981. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6982. }
  6983. TEST_F(ServerTest, Issue609) {
  6984. auto res = cli_.Delete("/issue609");
  6985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6986. EXPECT_EQ(StatusCode::OK_200, res->status);
  6987. EXPECT_EQ(std::string("ok"), res->body);
  6988. }
  6989. TEST_F(ServerTest, GetStreamedChunked) {
  6990. auto res = cli_.Get("/streamed-chunked");
  6991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6992. EXPECT_EQ(StatusCode::OK_200, res->status);
  6993. EXPECT_EQ(std::string("123456789"), res->body);
  6994. }
  6995. TEST_F(ServerTest, GetStreamedChunked2) {
  6996. auto res = cli_.Get("/streamed-chunked2");
  6997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6998. EXPECT_EQ(StatusCode::OK_200, res->status);
  6999. EXPECT_EQ(std::string("123456789"), res->body);
  7000. }
  7001. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7002. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7004. EXPECT_EQ(StatusCode::OK_200, res->status);
  7005. EXPECT_EQ(std::string("123456789"), res->body);
  7006. EXPECT_TRUE(res->has_header("Trailer"));
  7007. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7008. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7009. // Trailers are now stored separately from headers (security fix)
  7010. EXPECT_EQ(2U, res->trailers.size());
  7011. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7012. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7013. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7014. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7015. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7016. // Verify trailers are NOT in headers (security verification)
  7017. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7018. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7019. }
  7020. TEST_F(ServerTest, LargeChunkedPost) {
  7021. Request req;
  7022. req.method = "POST";
  7023. req.path = "/large-chunked";
  7024. std::string host_and_port;
  7025. host_and_port += HOST;
  7026. host_and_port += ":";
  7027. host_and_port += std::to_string(PORT);
  7028. req.headers.emplace("Host", host_and_port.c_str());
  7029. req.headers.emplace("Accept", "*/*");
  7030. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7031. req.headers.emplace("Content-Type", "text/plain");
  7032. req.headers.emplace("Content-Length", "0");
  7033. req.headers.emplace("Transfer-Encoding", "chunked");
  7034. std::string long_string(30 * 1024u, 'a');
  7035. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7036. // Attempt to make a large enough post to exceed OS buffers, to test that
  7037. // the server handles short reads if the full chunk data isn't available.
  7038. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7039. auto res = std::make_shared<Response>();
  7040. auto error = Error::Success;
  7041. auto ret = cli_.send(req, *res, error);
  7042. ASSERT_TRUE(ret);
  7043. EXPECT_EQ(StatusCode::OK_200, res->status);
  7044. }
  7045. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7046. auto res = cli_.Get("/remote_addr");
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::OK_200, res->status);
  7049. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7050. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7051. }
  7052. TEST_F(ServerTest, GetMethodLocalAddr) {
  7053. auto res = cli_.Get("/local_addr");
  7054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7055. EXPECT_EQ(StatusCode::OK_200, res->status);
  7056. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7057. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7058. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7059. }
  7060. TEST_F(ServerTest, HTTPResponseSplitting) {
  7061. auto res = cli_.Get("/http_response_splitting");
  7062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7063. EXPECT_EQ(StatusCode::OK_200, res->status);
  7064. }
  7065. TEST_F(ServerTest, SlowRequest) {
  7066. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7067. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7068. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7069. }
  7070. #if 0
  7071. TEST_F(ServerTest, SlowPost) {
  7072. char buffer[64 * 1024];
  7073. memset(buffer, 0x42, sizeof(buffer));
  7074. auto res = cli_.Post(
  7075. "/slowpost", 64 * 1024 * 1024,
  7076. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7077. auto ret = sink.write(buffer, sizeof(buffer));
  7078. EXPECT_TRUE(ret);
  7079. return true;
  7080. },
  7081. "text/plain");
  7082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7083. EXPECT_EQ(StatusCode::OK_200, res->status);
  7084. }
  7085. TEST_F(ServerTest, SlowPostFail) {
  7086. char buffer[64 * 1024];
  7087. memset(buffer, 0x42, sizeof(buffer));
  7088. cli_.set_write_timeout(std::chrono::seconds(0));
  7089. auto res = cli_.Post(
  7090. "/slowpost", 64 * 1024 * 1024,
  7091. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7092. sink.write(buffer, sizeof(buffer));
  7093. return true;
  7094. },
  7095. "text/plain");
  7096. ASSERT_TRUE(!res);
  7097. EXPECT_EQ(Error::Write, res.error());
  7098. }
  7099. #endif
  7100. TEST_F(ServerTest, Put) {
  7101. auto res = cli_.Put("/put", "PUT", "text/plain");
  7102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7103. EXPECT_EQ(StatusCode::OK_200, res->status);
  7104. EXPECT_EQ("PUT", res->body);
  7105. }
  7106. TEST_F(ServerTest, PutWithContentProvider) {
  7107. auto res = cli_.Put(
  7108. "/put", 3,
  7109. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7110. sink.os << "PUT";
  7111. return true;
  7112. },
  7113. "text/plain");
  7114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7115. EXPECT_EQ(StatusCode::OK_200, res->status);
  7116. EXPECT_EQ("PUT", res->body);
  7117. }
  7118. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7119. auto res = cli_.Post(
  7120. "/post", 42,
  7121. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7122. return false;
  7123. },
  7124. "text/plain");
  7125. ASSERT_TRUE(!res);
  7126. EXPECT_EQ(Error::Canceled, res.error());
  7127. }
  7128. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7129. auto res = cli_.Put(
  7130. "/put",
  7131. [](size_t /*offset*/, DataSink &sink) {
  7132. sink.os << "PUT";
  7133. sink.done();
  7134. return true;
  7135. },
  7136. "text/plain");
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::OK_200, res->status);
  7139. EXPECT_EQ("PUT", res->body);
  7140. }
  7141. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7142. auto res = cli_.Post(
  7143. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7144. "text/plain");
  7145. ASSERT_TRUE(!res);
  7146. EXPECT_EQ(Error::Canceled, res.error());
  7147. }
  7148. TEST_F(ServerTest, PostLoopBack) {
  7149. std::string body;
  7150. auto res = cli_.Post(
  7151. "/post-loopback", 9,
  7152. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7153. EXPECT_EQ(9u, length);
  7154. sink.write("123", 3);
  7155. sink.write("456", 3);
  7156. sink.write("789", 3);
  7157. return true;
  7158. },
  7159. "text/plain",
  7160. [&body](const char *data, size_t data_length) {
  7161. body.append(data, data_length);
  7162. return true;
  7163. });
  7164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7165. EXPECT_EQ(StatusCode::OK_200, res->status);
  7166. EXPECT_EQ("123456789", body);
  7167. }
  7168. TEST_F(ServerTest, PutLoopBack) {
  7169. std::string body;
  7170. auto res = cli_.Put(
  7171. "/put-loopback", 9,
  7172. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7173. EXPECT_EQ(9u, length);
  7174. sink.write("123", 3);
  7175. sink.write("456", 3);
  7176. sink.write("789", 3);
  7177. return true;
  7178. },
  7179. "text/plain",
  7180. [&body](const char *data, size_t data_length) {
  7181. body.append(data, data_length);
  7182. return true;
  7183. });
  7184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7185. EXPECT_EQ(StatusCode::OK_200, res->status);
  7186. EXPECT_EQ("123456789", body);
  7187. }
  7188. TEST_F(ServerTest, PatchLoopBack) {
  7189. std::string body;
  7190. auto res = cli_.Patch(
  7191. "/patch-loopback", 9,
  7192. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7193. EXPECT_EQ(9u, length);
  7194. sink.write("123", 3);
  7195. sink.write("456", 3);
  7196. sink.write("789", 3);
  7197. return true;
  7198. },
  7199. "text/plain",
  7200. [&body](const char *data, size_t data_length) {
  7201. body.append(data, data_length);
  7202. return true;
  7203. });
  7204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7205. EXPECT_EQ(StatusCode::OK_200, res->status);
  7206. EXPECT_EQ("123456789", body);
  7207. }
  7208. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7209. std::string body;
  7210. auto res = cli_.Post(
  7211. "/post-loopback",
  7212. [](size_t /*offset*/, DataSink &sink) {
  7213. sink.write("123", 3);
  7214. sink.write("456", 3);
  7215. sink.write("789", 3);
  7216. sink.done();
  7217. return true;
  7218. },
  7219. "text/plain",
  7220. [&body](const char *data, size_t data_length) {
  7221. body.append(data, data_length);
  7222. return true;
  7223. });
  7224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7225. EXPECT_EQ(StatusCode::OK_200, res->status);
  7226. EXPECT_EQ("123456789", body);
  7227. }
  7228. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7229. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7230. cli_.set_compress(true);
  7231. auto res = cli_.Put(
  7232. "/put", 3,
  7233. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7234. sink.os << "PUT";
  7235. return true;
  7236. },
  7237. "text/plain");
  7238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7239. EXPECT_EQ(StatusCode::OK_200, res->status);
  7240. EXPECT_EQ("PUT", res->body);
  7241. }
  7242. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7243. cli_.set_compress(true);
  7244. auto res = cli_.Post(
  7245. "/post", 42,
  7246. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7247. return false;
  7248. },
  7249. "text/plain");
  7250. ASSERT_TRUE(!res);
  7251. EXPECT_EQ(Error::Canceled, res.error());
  7252. }
  7253. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7254. cli_.set_compress(true);
  7255. auto res = cli_.Put(
  7256. "/put",
  7257. [](size_t /*offset*/, DataSink &sink) {
  7258. sink.os << "PUT";
  7259. sink.done();
  7260. return true;
  7261. },
  7262. "text/plain");
  7263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7264. EXPECT_EQ(StatusCode::OK_200, res->status);
  7265. EXPECT_EQ("PUT", res->body);
  7266. }
  7267. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7268. cli_.set_compress(true);
  7269. auto res = cli_.Post(
  7270. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7271. "text/plain");
  7272. ASSERT_TRUE(!res);
  7273. EXPECT_EQ(Error::Canceled, res.error());
  7274. }
  7275. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7276. cli_.set_compress(true);
  7277. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7279. EXPECT_EQ(StatusCode::OK_200, res->status);
  7280. EXPECT_EQ(LARGE_DATA, res->body);
  7281. }
  7282. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7283. #ifdef CPPHTTPLIB_SSL_ENABLED
  7284. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7285. Client cli(s.c_str());
  7286. cli.enable_server_certificate_verification(false);
  7287. #else
  7288. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7289. Client cli(s.c_str());
  7290. #endif
  7291. cli.set_compress(true);
  7292. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7294. EXPECT_EQ(StatusCode::OK_200, res->status);
  7295. EXPECT_EQ(LARGE_DATA, res->body);
  7296. // The compressed size should be less than a 10th of the original. May vary
  7297. // depending on the zlib library.
  7298. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7299. static_cast<uint64_t>(10 * 1024 * 1024));
  7300. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7301. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7302. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7303. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7304. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7305. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7306. #endif
  7307. }
  7308. TEST_F(ServerTest, PutContentWithDeflate) {
  7309. cli_.set_compress(false);
  7310. Headers headers;
  7311. headers.emplace("Content-Encoding", "deflate");
  7312. // PUT in deflate format:
  7313. auto res = cli_.Put("/put", headers,
  7314. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7316. EXPECT_EQ(StatusCode::OK_200, res->status);
  7317. EXPECT_EQ("PUT", res->body);
  7318. }
  7319. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7320. Headers headers;
  7321. headers.emplace("Accept-Encoding", "gzip, deflate");
  7322. auto res = cli_.Get("/streamed-chunked", headers);
  7323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7324. EXPECT_EQ(StatusCode::OK_200, res->status);
  7325. EXPECT_EQ(std::string("123456789"), res->body);
  7326. }
  7327. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7328. Headers headers;
  7329. headers.emplace("Accept-Encoding", "gzip, deflate");
  7330. auto res = cli_.Get("/streamed-chunked2", headers);
  7331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7332. EXPECT_EQ(StatusCode::OK_200, res->status);
  7333. EXPECT_EQ(std::string("123456789"), res->body);
  7334. }
  7335. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7336. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7338. EXPECT_EQ(StatusCode::OK_200, res->status);
  7339. }
  7340. TEST(GzipDecompressor, ChunkedDecompression) {
  7341. std::string data;
  7342. for (size_t i = 0; i < 32 * 1024; ++i) {
  7343. data.push_back(static_cast<char>('a' + i % 26));
  7344. }
  7345. std::string compressed_data;
  7346. {
  7347. httplib::detail::gzip_compressor compressor;
  7348. bool result = compressor.compress(
  7349. data.data(), data.size(),
  7350. /*last=*/true,
  7351. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7352. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7353. compressed_data_size);
  7354. return true;
  7355. });
  7356. ASSERT_TRUE(result);
  7357. }
  7358. std::string decompressed_data;
  7359. {
  7360. httplib::detail::gzip_decompressor decompressor;
  7361. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7362. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7363. size_t chunk_size = 130;
  7364. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7365. chunk_begin += chunk_size) {
  7366. size_t current_chunk_size =
  7367. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7368. bool result = decompressor.decompress(
  7369. compressed_data.data() + chunk_begin, current_chunk_size,
  7370. [&](const char *decompressed_data_chunk,
  7371. size_t decompressed_data_chunk_size) {
  7372. decompressed_data.insert(decompressed_data.size(),
  7373. decompressed_data_chunk,
  7374. decompressed_data_chunk_size);
  7375. return true;
  7376. });
  7377. ASSERT_TRUE(result);
  7378. }
  7379. }
  7380. ASSERT_EQ(data, decompressed_data);
  7381. }
  7382. TEST(GzipDecompressor, DeflateDecompression) {
  7383. std::string original_text = "Raw deflate without gzip";
  7384. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7385. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7386. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7387. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7388. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7389. std::string decompressed_data;
  7390. {
  7391. httplib::detail::gzip_decompressor decompressor;
  7392. bool result = decompressor.decompress(
  7393. compressed_data.data(), compressed_data.size(),
  7394. [&](const char *decompressed_data_chunk,
  7395. size_t decompressed_data_chunk_size) {
  7396. decompressed_data.insert(decompressed_data.size(),
  7397. decompressed_data_chunk,
  7398. decompressed_data_chunk_size);
  7399. return true;
  7400. });
  7401. ASSERT_TRUE(result);
  7402. }
  7403. ASSERT_EQ(original_text, decompressed_data);
  7404. }
  7405. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7406. std::string original_text = "Raw deflate without gzip";
  7407. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7408. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7409. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7410. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7411. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7412. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7413. std::string decompressed_data;
  7414. {
  7415. httplib::detail::gzip_decompressor decompressor;
  7416. bool result = decompressor.decompress(
  7417. compressed_data.data(), compressed_data.size(),
  7418. [&](const char *decompressed_data_chunk,
  7419. size_t decompressed_data_chunk_size) {
  7420. decompressed_data.insert(decompressed_data.size(),
  7421. decompressed_data_chunk,
  7422. decompressed_data_chunk_size);
  7423. return true;
  7424. });
  7425. ASSERT_TRUE(result);
  7426. }
  7427. ASSERT_EQ(original_text, decompressed_data);
  7428. }
  7429. #endif
  7430. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7431. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7432. Headers headers;
  7433. headers.emplace("Accept-Encoding", "br");
  7434. auto res = cli_.Get("/streamed-chunked", headers);
  7435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7436. EXPECT_EQ(StatusCode::OK_200, res->status);
  7437. EXPECT_EQ(std::string("123456789"), res->body);
  7438. }
  7439. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7440. Headers headers;
  7441. headers.emplace("Accept-Encoding", "br");
  7442. auto res = cli_.Get("/streamed-chunked2", headers);
  7443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7444. EXPECT_EQ(StatusCode::OK_200, res->status);
  7445. EXPECT_EQ(std::string("123456789"), res->body);
  7446. }
  7447. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7448. cli_.set_compress(true);
  7449. auto res = cli_.Put(
  7450. "/put", 3,
  7451. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7452. sink.os << "PUT";
  7453. return true;
  7454. },
  7455. "text/plain");
  7456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7457. EXPECT_EQ(StatusCode::OK_200, res->status);
  7458. EXPECT_EQ("PUT", res->body);
  7459. }
  7460. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7461. cli_.set_compress(true);
  7462. auto res = cli_.Put(
  7463. "/put",
  7464. [](size_t /*offset*/, DataSink &sink) {
  7465. sink.os << "PUT";
  7466. sink.done();
  7467. return true;
  7468. },
  7469. "text/plain");
  7470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7471. EXPECT_EQ(StatusCode::OK_200, res->status);
  7472. EXPECT_EQ("PUT", res->body);
  7473. }
  7474. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7475. cli_.set_compress(true);
  7476. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7478. EXPECT_EQ(StatusCode::OK_200, res->status);
  7479. EXPECT_EQ(LARGE_DATA, res->body);
  7480. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7481. }
  7482. #endif
  7483. TEST_F(ServerTest, Patch) {
  7484. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7486. EXPECT_EQ(StatusCode::OK_200, res->status);
  7487. EXPECT_EQ("PATCH", res->body);
  7488. }
  7489. TEST_F(ServerTest, Delete) {
  7490. auto res = cli_.Delete("/delete");
  7491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7492. EXPECT_EQ(StatusCode::OK_200, res->status);
  7493. EXPECT_EQ("DELETE", res->body);
  7494. }
  7495. TEST_F(ServerTest, DeleteContentReceiver) {
  7496. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_EQ(StatusCode::OK_200, res->status);
  7499. EXPECT_EQ("content", res->body);
  7500. }
  7501. TEST_F(ServerTest, Options) {
  7502. auto res = cli_.Options("*");
  7503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7504. EXPECT_EQ(StatusCode::OK_200, res->status);
  7505. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7506. EXPECT_TRUE(res->body.empty());
  7507. }
  7508. TEST_F(ServerTest, URL) {
  7509. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7511. EXPECT_EQ(StatusCode::OK_200, res->status);
  7512. }
  7513. TEST_F(ServerTest, ArrayParam) {
  7514. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7516. EXPECT_EQ(StatusCode::OK_200, res->status);
  7517. }
  7518. TEST_F(ServerTest, ArrayParamValues) {
  7519. auto res =
  7520. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7522. EXPECT_EQ(StatusCode::OK_200, res->status);
  7523. }
  7524. TEST_F(ServerTest, NoMultipleHeaders) {
  7525. Headers headers = {{"Content-Length", "5"}};
  7526. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7527. "text/plain");
  7528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7529. EXPECT_EQ(StatusCode::OK_200, res->status);
  7530. }
  7531. TEST_F(ServerTest, PostContentReceiver) {
  7532. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. ASSERT_EQ(StatusCode::OK_200, res->status);
  7535. ASSERT_EQ("content", res->body);
  7536. }
  7537. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7538. UploadFormDataItems items = {
  7539. {"text1", "text default", "", ""},
  7540. {"text2", "aωb", "", ""},
  7541. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7542. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7543. {"file3", "", "", "application/octet-stream"},
  7544. };
  7545. auto res = cli_.Post("/content_receiver", items);
  7546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7547. EXPECT_EQ(StatusCode::OK_200, res->status);
  7548. }
  7549. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7550. UploadFormDataItems items = {
  7551. {"text1", "text default", "", ""},
  7552. {"text2", "aωb", "", ""},
  7553. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7554. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7555. {"file3", "", "", "application/octet-stream"},
  7556. };
  7557. auto boundary = std::string("+++++");
  7558. std::string body;
  7559. for (const auto &item : items) {
  7560. body += "--" + boundary + "\r\n";
  7561. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7562. if (!item.filename.empty()) {
  7563. body += "; filename=\"" + item.filename + "\"";
  7564. }
  7565. body += "\r\n";
  7566. if (!item.content_type.empty()) {
  7567. body += "Content-Type: " + item.content_type + "\r\n";
  7568. }
  7569. body += "\r\n";
  7570. body += item.content + "\r\n";
  7571. }
  7572. body += "--" + boundary + "--\r\n";
  7573. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7574. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7576. EXPECT_EQ(StatusCode::OK_200, res->status);
  7577. }
  7578. TEST(MultipartFormDataTest, FieldEscaping) {
  7579. Server svr;
  7580. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7581. const ContentReader &content_reader) {
  7582. ASSERT_TRUE(req.is_multipart_form_data());
  7583. std::vector<FormData> received;
  7584. content_reader(
  7585. [&](const FormData &file) {
  7586. received.push_back(file);
  7587. return true;
  7588. },
  7589. [&](const char *data, size_t data_length) {
  7590. received.back().content.append(data, data_length);
  7591. return true;
  7592. });
  7593. // '"', CR and LF in names and filenames are escaped following the
  7594. // WHATWG HTML standard, so each part still parses as a single part
  7595. // with no injected headers. Content types get CR/LF escaped too,
  7596. // while '"' (legal there, e.g. quoted charset) is preserved.
  7597. ASSERT_EQ(4U, received.size());
  7598. EXPECT_EQ("na%22me", received[0].name);
  7599. EXPECT_EQ("quoted name", received[0].content);
  7600. EXPECT_EQ("file", received[1].name);
  7601. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7602. received[1].filename);
  7603. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7604. EXPECT_EQ("injected", received[1].content);
  7605. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7606. EXPECT_EQ("my%22file.txt", received[2].filename);
  7607. EXPECT_EQ("cr lf name", received[2].content);
  7608. EXPECT_EQ("typed", received[3].name);
  7609. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7610. received[3].content_type);
  7611. EXPECT_EQ("typed content", received[3].content);
  7612. });
  7613. auto port = svr.bind_to_any_port("localhost");
  7614. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7615. auto se = detail::scope_exit([&] {
  7616. svr.stop();
  7617. t.join();
  7618. ASSERT_FALSE(svr.is_running());
  7619. });
  7620. svr.wait_until_ready();
  7621. Client cli("localhost", port);
  7622. UploadFormDataItems items = {
  7623. {"na\"me", "quoted name", "", ""},
  7624. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7625. "application/octet-stream"},
  7626. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7627. {"typed", "typed content", "",
  7628. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7629. };
  7630. auto res = cli.Post("/post", items);
  7631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7632. EXPECT_EQ(StatusCode::OK_200, res->status);
  7633. }
  7634. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7635. const UploadFormDataItems items = {
  7636. {"name1", "Content 1", "", ""},
  7637. {"name2", "Content 2", "file2.txt", "text/plain"},
  7638. };
  7639. Server svr;
  7640. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7641. const ContentReader &content_reader) {
  7642. ASSERT_TRUE(req.is_multipart_form_data());
  7643. std::vector<FormData> received;
  7644. content_reader(
  7645. [&](const FormData &file) {
  7646. received.push_back(file);
  7647. return true;
  7648. },
  7649. [&](const char *data, size_t data_length) {
  7650. received.back().content.append(data, data_length);
  7651. return true;
  7652. });
  7653. ASSERT_EQ(2U, received.size());
  7654. EXPECT_EQ("name1", received[0].name);
  7655. EXPECT_EQ("Content 1", received[0].content);
  7656. EXPECT_EQ("name2", received[1].name);
  7657. EXPECT_EQ("Content 2", received[1].content);
  7658. EXPECT_EQ("file2.txt", received[1].filename);
  7659. EXPECT_EQ("text/plain", received[1].content_type);
  7660. });
  7661. auto port = svr.bind_to_any_port("localhost");
  7662. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7663. auto se = detail::scope_exit([&] {
  7664. svr.stop();
  7665. t.join();
  7666. ASSERT_FALSE(svr.is_running());
  7667. });
  7668. svr.wait_until_ready();
  7669. Client cli("localhost", port);
  7670. // Whole-body serialization with a generated boundary
  7671. {
  7672. MultipartFormDataWriter writer;
  7673. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7674. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7675. writer.content_type());
  7676. auto body = writer.serialize(items);
  7677. EXPECT_EQ(body.size(), writer.content_length(items));
  7678. auto res = cli.Post("/post", body, writer.content_type());
  7679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7680. EXPECT_EQ(StatusCode::OK_200, res->status);
  7681. }
  7682. // Per-part framing with a custom boundary via a content provider
  7683. {
  7684. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7685. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7686. MultipartFormDataWriter writer("custom-boundary_123");
  7687. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7688. std::string body;
  7689. for (const auto &item : items) {
  7690. body += writer.item_begin(item);
  7691. body += item.content;
  7692. body += MultipartFormDataWriter::item_end();
  7693. }
  7694. body += writer.finish();
  7695. EXPECT_EQ(body.size(), writer.content_length(items));
  7696. auto res = cli.Post(
  7697. "/post", body.size(),
  7698. [&](size_t offset, size_t length, DataSink &sink) {
  7699. sink.write(body.data() + offset, length);
  7700. return true;
  7701. },
  7702. writer.content_type());
  7703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7704. EXPECT_EQ(StatusCode::OK_200, res->status);
  7705. }
  7706. }
  7707. TEST_F(ServerTest, PostContentReceiverGzip) {
  7708. cli_.set_compress(true);
  7709. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7711. ASSERT_EQ(StatusCode::OK_200, res->status);
  7712. ASSERT_EQ("content", res->body);
  7713. }
  7714. TEST_F(ServerTest, PutContentReceiver) {
  7715. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7717. ASSERT_EQ(StatusCode::OK_200, res->status);
  7718. ASSERT_EQ("content", res->body);
  7719. }
  7720. TEST_F(ServerTest, PatchContentReceiver) {
  7721. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7723. ASSERT_EQ(StatusCode::OK_200, res->status);
  7724. ASSERT_EQ("content", res->body);
  7725. }
  7726. template <typename ClientType>
  7727. void TestWithHeadersAndContentReceiver(
  7728. ClientType &cli,
  7729. std::function<Result(ClientType &, const std::string &, const Headers &,
  7730. const std::string &, const std::string &,
  7731. ContentReceiver, DownloadProgress)>
  7732. request_func) {
  7733. Headers headers;
  7734. headers.emplace("X-Custom-Header", "test-value");
  7735. std::string received_body;
  7736. auto res = request_func(
  7737. cli, "/content_receiver", headers, "content", "application/json",
  7738. [&](const char *data, size_t data_length) {
  7739. received_body.append(data, data_length);
  7740. return true;
  7741. },
  7742. nullptr);
  7743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7744. EXPECT_EQ(StatusCode::OK_200, res->status);
  7745. EXPECT_EQ("content", received_body);
  7746. }
  7747. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7748. #ifdef CPPHTTPLIB_SSL_ENABLED
  7749. using ClientT = SSLClient;
  7750. #else
  7751. using ClientT = Client;
  7752. #endif
  7753. TestWithHeadersAndContentReceiver<ClientT>(
  7754. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7755. const std::string &body, const std::string &content_type,
  7756. ContentReceiver receiver, DownloadProgress progress) {
  7757. return cli.Post(path, headers, body, content_type, receiver, progress);
  7758. });
  7759. }
  7760. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7761. #ifdef CPPHTTPLIB_SSL_ENABLED
  7762. using ClientT = SSLClient;
  7763. #else
  7764. using ClientT = Client;
  7765. #endif
  7766. TestWithHeadersAndContentReceiver<ClientT>(
  7767. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7768. const std::string &body, const std::string &content_type,
  7769. ContentReceiver receiver, DownloadProgress progress) {
  7770. return cli.Put(path, headers, body, content_type, receiver, progress);
  7771. });
  7772. }
  7773. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7774. #ifdef CPPHTTPLIB_SSL_ENABLED
  7775. using ClientT = SSLClient;
  7776. #else
  7777. using ClientT = Client;
  7778. #endif
  7779. TestWithHeadersAndContentReceiver<ClientT>(
  7780. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7781. const std::string &body, const std::string &content_type,
  7782. ContentReceiver receiver, DownloadProgress progress) {
  7783. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7784. });
  7785. }
  7786. template <typename ClientType>
  7787. void TestWithHeadersAndContentReceiverWithProgress(
  7788. ClientType &cli,
  7789. std::function<Result(ClientType &, const std::string &, const Headers &,
  7790. const std::string &, const std::string &,
  7791. ContentReceiver, DownloadProgress)>
  7792. request_func) {
  7793. Headers headers;
  7794. headers.emplace("X-Test-Header", "progress-test");
  7795. std::string received_body;
  7796. auto progress_called = false;
  7797. auto res = request_func(
  7798. cli, "/content_receiver", headers, "content", "text/plain",
  7799. [&](const char *data, size_t data_length) {
  7800. received_body.append(data, data_length);
  7801. return true;
  7802. },
  7803. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7804. progress_called = true;
  7805. return true;
  7806. });
  7807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7808. EXPECT_EQ(StatusCode::OK_200, res->status);
  7809. EXPECT_EQ("content", received_body);
  7810. EXPECT_TRUE(progress_called);
  7811. }
  7812. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7813. #ifdef CPPHTTPLIB_SSL_ENABLED
  7814. using ClientT = SSLClient;
  7815. #else
  7816. using ClientT = Client;
  7817. #endif
  7818. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7819. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7820. const std::string &body, const std::string &content_type,
  7821. ContentReceiver receiver, DownloadProgress progress) {
  7822. return cli.Post(path, headers, body, content_type, receiver, progress);
  7823. });
  7824. }
  7825. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7826. #ifdef CPPHTTPLIB_SSL_ENABLED
  7827. using ClientT = SSLClient;
  7828. #else
  7829. using ClientT = Client;
  7830. #endif
  7831. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7832. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7833. const std::string &body, const std::string &content_type,
  7834. ContentReceiver receiver, DownloadProgress progress) {
  7835. return cli.Put(path, headers, body, content_type, receiver, progress);
  7836. });
  7837. }
  7838. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7839. #ifdef CPPHTTPLIB_SSL_ENABLED
  7840. using ClientT = SSLClient;
  7841. #else
  7842. using ClientT = Client;
  7843. #endif
  7844. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7845. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7846. const std::string &body, const std::string &content_type,
  7847. ContentReceiver receiver, DownloadProgress progress) {
  7848. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7849. });
  7850. }
  7851. template <typename ClientType>
  7852. void TestWithHeadersAndContentReceiverError(
  7853. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7854. const Headers &, const std::string &,
  7855. const std::string &, ContentReceiver)>
  7856. request_func) {
  7857. Headers headers;
  7858. headers.emplace("X-Error-Test", "true");
  7859. std::string received_body;
  7860. auto receiver_failed = false;
  7861. auto res =
  7862. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7863. [&](const char *data, size_t data_length) {
  7864. received_body.append(data, data_length);
  7865. receiver_failed = true;
  7866. return false;
  7867. });
  7868. ASSERT_FALSE(res);
  7869. EXPECT_TRUE(receiver_failed);
  7870. }
  7871. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7872. #ifdef CPPHTTPLIB_SSL_ENABLED
  7873. using ClientT = SSLClient;
  7874. #else
  7875. using ClientT = Client;
  7876. #endif
  7877. TestWithHeadersAndContentReceiverError<ClientT>(
  7878. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7879. const std::string &body, const std::string &content_type,
  7880. ContentReceiver receiver) {
  7881. return cli.Post(path, headers, body, content_type, receiver);
  7882. });
  7883. }
  7884. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7885. #ifdef CPPHTTPLIB_SSL_ENABLED
  7886. using ClientT = SSLClient;
  7887. #else
  7888. using ClientT = Client;
  7889. #endif
  7890. TestWithHeadersAndContentReceiverError<ClientT>(
  7891. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7892. const std::string &body, const std::string &content_type,
  7893. ContentReceiver receiver) {
  7894. return cli.Put(path, headers, body, content_type, receiver);
  7895. });
  7896. }
  7897. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7898. #ifdef CPPHTTPLIB_SSL_ENABLED
  7899. using ClientT = SSLClient;
  7900. #else
  7901. using ClientT = Client;
  7902. #endif
  7903. TestWithHeadersAndContentReceiverError<ClientT>(
  7904. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7905. const std::string &body, const std::string &content_type,
  7906. ContentReceiver receiver) {
  7907. return cli.Patch(path, headers, body, content_type, receiver);
  7908. });
  7909. }
  7910. TEST_F(ServerTest, PostQueryStringAndBody) {
  7911. auto res =
  7912. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7914. ASSERT_EQ(StatusCode::OK_200, res->status);
  7915. }
  7916. TEST_F(ServerTest, HTTP2Magic) {
  7917. Request req;
  7918. req.method = "PRI";
  7919. req.path = "*";
  7920. req.body = "SM";
  7921. auto res = std::make_shared<Response>();
  7922. auto error = Error::Success;
  7923. auto ret = cli_.send(req, *res, error);
  7924. ASSERT_TRUE(ret);
  7925. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7926. }
  7927. TEST_F(ServerTest, KeepAlive) {
  7928. auto res = cli_.Get("/hi");
  7929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7930. EXPECT_EQ(StatusCode::OK_200, res->status);
  7931. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7932. EXPECT_EQ("Hello World!", res->body);
  7933. res = cli_.Get("/hi");
  7934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7935. EXPECT_EQ(StatusCode::OK_200, res->status);
  7936. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7937. EXPECT_EQ("Hello World!", res->body);
  7938. res = cli_.Get("/hi");
  7939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7940. EXPECT_EQ(StatusCode::OK_200, res->status);
  7941. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7942. EXPECT_EQ("Hello World!", res->body);
  7943. res = cli_.Get("/not-exist");
  7944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7945. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7946. res = cli_.Post("/empty", "", "text/plain");
  7947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7948. EXPECT_EQ(StatusCode::OK_200, res->status);
  7949. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7950. EXPECT_EQ("empty", res->body);
  7951. EXPECT_EQ("close", res->get_header_value("Connection"));
  7952. res = cli_.Post(
  7953. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7954. "text/plain");
  7955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7956. EXPECT_EQ(StatusCode::OK_200, res->status);
  7957. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7958. EXPECT_EQ("empty", res->body);
  7959. cli_.set_keep_alive(false);
  7960. res = cli_.Get("/last-request");
  7961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7962. EXPECT_EQ(StatusCode::OK_200, res->status);
  7963. EXPECT_EQ("close", res->get_header_value("Connection"));
  7964. }
  7965. TEST_F(ServerTest, TooManyRedirect) {
  7966. cli_.set_follow_location(true);
  7967. auto res = cli_.Get("/redirect/0");
  7968. ASSERT_TRUE(!res);
  7969. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7970. }
  7971. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7972. Request req;
  7973. req.method = "FOOBAR";
  7974. req.path = "/hi";
  7975. cli_.set_keep_alive(true);
  7976. auto res = cli_.send(req);
  7977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7978. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7979. EXPECT_EQ("close", res->get_header_value("Connection"));
  7980. EXPECT_FALSE(cli_.is_socket_open());
  7981. }
  7982. TEST_F(ServerTest, CustomRouteReadsBody) {
  7983. const std::string xml =
  7984. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7985. Request req;
  7986. req.method = "PROPFIND";
  7987. req.path = "/dav/dir";
  7988. req.set_header("Depth", "1");
  7989. req.body = xml;
  7990. auto res = cli_.send(req);
  7991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7992. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7993. EXPECT_EQ(xml, res->body);
  7994. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7995. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7996. }
  7997. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7998. Request req;
  7999. req.method = "PROPFIND";
  8000. req.path = "/dav/42";
  8001. auto res = cli_.send(req);
  8002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8003. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8004. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8005. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8006. }
  8007. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8008. Request req;
  8009. req.method = "PROPFIND";
  8010. req.path = "/dav-re/123";
  8011. auto res = cli_.send(req);
  8012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8013. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8014. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8015. }
  8016. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8017. Request req;
  8018. req.method = "MKCOL";
  8019. req.path = "/dav-mkcol";
  8020. auto res = cli_.send(req);
  8021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8022. EXPECT_EQ(StatusCode::Created_201, res->status);
  8023. }
  8024. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8025. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8026. Request req;
  8027. req.method = "REPORT";
  8028. req.path = "/dav-report";
  8029. req.body = xml;
  8030. auto res = cli_.send(req);
  8031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8032. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8033. EXPECT_EQ(xml, res->body);
  8034. }
  8035. // A content reader route must fire even when the request carries no body,
  8036. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8037. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8038. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8039. Request req;
  8040. req.method = "REPORT";
  8041. req.path = "/dav-report";
  8042. auto res = cli_.send(req);
  8043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8044. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8045. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8046. }
  8047. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8048. Request req;
  8049. req.method = "PROPFIND";
  8050. req.path = "/not-dav";
  8051. auto res = cli_.send(req);
  8052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8053. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8054. }
  8055. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8056. Request req;
  8057. req.method = "UNLOCK";
  8058. req.path = "/dav/dir";
  8059. cli_.set_keep_alive(true);
  8060. auto res = cli_.send(req);
  8061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8062. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8063. EXPECT_EQ("close", res->get_header_value("Connection"));
  8064. EXPECT_FALSE(cli_.is_socket_open());
  8065. }
  8066. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8067. // The mount point serves this path, but only for GET and HEAD.
  8068. auto get_res = cli_.Get("/dir/index.html");
  8069. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8070. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8071. Request req;
  8072. req.method = "PROPFIND";
  8073. req.path = "/dir/index.html";
  8074. auto res = cli_.send(req);
  8075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8076. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8077. }
  8078. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8079. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8080. cli_.set_keep_alive(true);
  8081. for (auto i = 0; i < 2; i++) {
  8082. Request req;
  8083. req.method = "PROPFIND";
  8084. req.path = "/dav/dir";
  8085. req.body = xml;
  8086. auto res = cli_.send(req);
  8087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8088. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8089. EXPECT_EQ(xml, res->body);
  8090. EXPECT_TRUE(cli_.is_socket_open());
  8091. }
  8092. // A built-in method must still be served on the same connection.
  8093. cli_.set_keep_alive(false);
  8094. auto res = cli_.Get("/hi");
  8095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8096. EXPECT_EQ(StatusCode::OK_200, res->status);
  8097. EXPECT_EQ("close", res->get_header_value("Connection"));
  8098. }
  8099. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8100. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8101. Request req;
  8102. req.method = "PROPFIND";
  8103. req.path = "/dav/dir";
  8104. req.set_header("Expect", "100-continue");
  8105. req.body = xml;
  8106. auto res = cli_.send(req);
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8109. EXPECT_EQ(xml, res->body);
  8110. }
  8111. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8112. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8113. TEST_F(ServerTest, Gzip) {
  8114. Headers headers;
  8115. headers.emplace("Accept-Encoding", "gzip, deflate");
  8116. auto res = cli_.Get("/compress", headers);
  8117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8118. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8119. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8120. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8121. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8122. "7890123456789012345678901234567890",
  8123. res->body);
  8124. EXPECT_EQ(StatusCode::OK_200, res->status);
  8125. }
  8126. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8127. Headers headers;
  8128. headers.emplace("Accept-Encoding", "gzip, deflate");
  8129. auto res = cli_.Get("/compress-with-charset", headers);
  8130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8131. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8132. EXPECT_EQ("application/json; charset=utf-8",
  8133. res->get_header_value("Content-Type"));
  8134. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8135. "7890123456789012345678901234567890",
  8136. res->body);
  8137. EXPECT_EQ(StatusCode::OK_200, res->status);
  8138. }
  8139. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8140. Headers headers;
  8141. headers.emplace("Accept-Encoding", "");
  8142. auto res = cli_.Get("/compress", headers);
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8145. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8146. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8147. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8148. "7890123456789012345678901234567890",
  8149. res->body);
  8150. EXPECT_EQ(StatusCode::OK_200, res->status);
  8151. }
  8152. TEST_F(ServerTest, GzipWithContentReceiver) {
  8153. Headers headers;
  8154. headers.emplace("Accept-Encoding", "gzip, deflate");
  8155. std::string body;
  8156. auto res = cli_.Get("/compress", headers,
  8157. [&](const char *data, uint64_t data_length) {
  8158. EXPECT_EQ(100U, data_length);
  8159. body.append(data, data_length);
  8160. return true;
  8161. });
  8162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8163. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8164. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8165. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8166. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8167. "7890123456789012345678901234567890",
  8168. body);
  8169. EXPECT_EQ(StatusCode::OK_200, res->status);
  8170. }
  8171. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8172. Headers headers;
  8173. headers.emplace("Accept-Encoding", "gzip, deflate");
  8174. cli_.set_decompress(false);
  8175. auto res = cli_.Get("/compress", headers);
  8176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8177. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8178. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8179. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8180. EXPECT_EQ(33U, res->body.size());
  8181. EXPECT_EQ(StatusCode::OK_200, res->status);
  8182. }
  8183. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8184. Headers headers;
  8185. headers.emplace("Accept-Encoding", "");
  8186. std::string body;
  8187. auto res = cli_.Get("/compress", headers,
  8188. [&](const char *data, uint64_t data_length) {
  8189. EXPECT_EQ(100U, data_length);
  8190. body.append(data, data_length);
  8191. return true;
  8192. });
  8193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8194. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8195. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8196. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8197. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8198. "7890123456789012345678901234567890",
  8199. body);
  8200. EXPECT_EQ(StatusCode::OK_200, res->status);
  8201. }
  8202. TEST_F(ServerTest, NoGzip) {
  8203. Headers headers;
  8204. headers.emplace("Accept-Encoding", "gzip, deflate");
  8205. auto res = cli_.Get("/nocompress", headers);
  8206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8207. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8208. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8209. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8210. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8211. "7890123456789012345678901234567890",
  8212. res->body);
  8213. EXPECT_EQ(StatusCode::OK_200, res->status);
  8214. }
  8215. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8216. Headers headers;
  8217. headers.emplace("Accept-Encoding", "gzip, deflate");
  8218. std::string body;
  8219. auto res = cli_.Get("/nocompress", headers,
  8220. [&](const char *data, uint64_t data_length) {
  8221. EXPECT_EQ(100U, data_length);
  8222. body.append(data, data_length);
  8223. return true;
  8224. });
  8225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8226. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8227. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8228. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8229. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8230. "7890123456789012345678901234567890",
  8231. body);
  8232. EXPECT_EQ(StatusCode::OK_200, res->status);
  8233. }
  8234. TEST_F(ServerTest, MultipartFormDataGzip) {
  8235. UploadFormDataItems items = {
  8236. {"key1", "test", "", ""},
  8237. {"key2", "--abcdefg123", "", ""},
  8238. };
  8239. cli_.set_compress(true);
  8240. auto res = cli_.Post("/compress-multipart", items);
  8241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8242. EXPECT_EQ(StatusCode::OK_200, res->status);
  8243. }
  8244. #endif
  8245. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8246. // Static file compression is opt-in, so these run their own server rather than
  8247. // flipping it on for the shared ServerTest fixture, which would silently
  8248. // rewrite what every other static file test is asserting.
  8249. class StaticFileCompressionTest : public ::testing::Test {
  8250. protected:
  8251. void TearDown() override {
  8252. if (t_.joinable()) {
  8253. svr_.stop();
  8254. t_.join();
  8255. }
  8256. }
  8257. int start(const std::function<void(Server &)> &configure = nullptr) {
  8258. // Serves the same tree as a directory of build-time compressed assets
  8259. // would be served: the mount point names the coding the files are already
  8260. // stored in. Registered before "/" so it is the one that matches.
  8261. svr_.set_mount_point("/pre-encoded", "./www",
  8262. {{"Content-Encoding", "gzip"}});
  8263. svr_.set_mount_point("/", "./www");
  8264. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8265. res.set_file_content("./www/dir/index.html", "text/html");
  8266. });
  8267. svr_.Get("/pre-encoded-file-content",
  8268. [](const Request & /*req*/, Response &res) {
  8269. res.set_header("Content-Encoding", "gzip");
  8270. res.set_file_content("./www/dir/index.html", "text/html");
  8271. });
  8272. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8273. res.set_content_provider(
  8274. 6, "text/plain",
  8275. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8276. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8277. return true;
  8278. });
  8279. });
  8280. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8281. res.set_content_provider(
  8282. 1000, "text/plain",
  8283. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8284. if (offset < 100) {
  8285. std::string data(100, 'A');
  8286. sink.write(data.data(), data.size());
  8287. return true;
  8288. }
  8289. std::this_thread::sleep_for(std::chrono::seconds(2));
  8290. std::string data(900, 'B');
  8291. sink.write(data.data(), data.size());
  8292. return true;
  8293. });
  8294. });
  8295. if (configure) { configure(svr_); }
  8296. auto port = svr_.bind_to_any_port(HOST);
  8297. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8298. svr_.wait_until_ready();
  8299. return port;
  8300. }
  8301. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8302. // Every file under ./www except 1MB.txt is smaller than the default
  8303. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8304. // it out of the way.
  8305. static void enable_without_floor(Server &svr) {
  8306. svr.set_static_file_compression(true);
  8307. svr.set_static_file_compression_min_length(0);
  8308. }
  8309. Server svr_;
  8310. std::thread t_;
  8311. };
  8312. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8313. auto port = start();
  8314. Client cli(HOST, port);
  8315. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8317. EXPECT_EQ(StatusCode::OK_200, res->status);
  8318. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8319. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8320. EXPECT_EQ(1048576U, res->body.size());
  8321. }
  8322. TEST_F(StaticFileCompressionTest, MountPoint) {
  8323. auto port = start(enable);
  8324. Client cli(HOST, port);
  8325. cli.set_decompress(false);
  8326. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8328. EXPECT_EQ(StatusCode::OK_200, res->status);
  8329. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8330. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8331. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8332. // The response stays self-delimiting: a length, not a chunked body.
  8333. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8334. EXPECT_EQ(std::to_string(res->body.size()),
  8335. res->get_header_value("Content-Length"));
  8336. EXPECT_LT(res->body.size(), 1048576U);
  8337. EXPECT_FALSE(res->body.empty());
  8338. }
  8339. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8340. auto port = start(enable);
  8341. Client cli(HOST, port);
  8342. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8344. EXPECT_EQ(StatusCode::OK_200, res->status);
  8345. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8346. EXPECT_EQ(1048576U, res->body.size());
  8347. }
  8348. TEST_F(StaticFileCompressionTest, FileContent) {
  8349. auto port = start(enable_without_floor);
  8350. Client cli(HOST, port);
  8351. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8353. EXPECT_EQ(StatusCode::OK_200, res->status);
  8354. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8355. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8356. EXPECT_EQ(104U, res->body.size());
  8357. }
  8358. // A handler that serves an already-encoded file names the coding itself. The
  8359. // file-backed path decided its coding from Accept-Encoding and the content
  8360. // type alone, so it compressed the stored bytes a second time and appended a
  8361. // second Content-Encoding field line.
  8362. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8363. auto port = start(enable_without_floor);
  8364. Client cli(HOST, port);
  8365. cli.set_decompress(false);
  8366. auto res = cli.Get("/pre-encoded-file-content",
  8367. Headers{{"Accept-Encoding", "gzip"}});
  8368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8369. EXPECT_EQ(StatusCode::OK_200, res->status);
  8370. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8371. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8372. // Vary belongs to a coding the server chose, and it chose none here.
  8373. EXPECT_FALSE(res->has_header("Vary"));
  8374. // The file travels exactly as it is stored on disk.
  8375. EXPECT_EQ(104U, res->body.size());
  8376. }
  8377. // The 1MB file clears the default floor, so this one runs the configuration a
  8378. // deployment would actually have.
  8379. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8380. auto port = start(enable);
  8381. Client cli(HOST, port);
  8382. cli.set_decompress(false);
  8383. auto res =
  8384. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8386. EXPECT_EQ(StatusCode::OK_200, res->status);
  8387. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8388. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8389. EXPECT_FALSE(res->has_header("Vary"));
  8390. EXPECT_EQ(1048576U, res->body.size());
  8391. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8392. }
  8393. TEST_F(StaticFileCompressionTest, Head) {
  8394. auto port = start(enable);
  8395. Client cli(HOST, port);
  8396. cli.set_decompress(false);
  8397. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8398. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8399. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8401. EXPECT_EQ(StatusCode::OK_200, res->status);
  8402. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8403. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8404. // HEAD still reports the size a GET would return.
  8405. EXPECT_EQ(get->get_header_value("Content-Length"),
  8406. res->get_header_value("Content-Length"));
  8407. EXPECT_TRUE(res->body.empty());
  8408. }
  8409. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8410. auto port = start(enable);
  8411. Client cli(HOST, port);
  8412. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8413. {"Accept-Encoding", "gzip"}});
  8414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8415. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8416. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8417. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8418. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8419. EXPECT_EQ("cd", res->body);
  8420. }
  8421. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8422. auto port = start(enable);
  8423. Client cli(HOST, port);
  8424. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8426. EXPECT_EQ(StatusCode::OK_200, res->status);
  8427. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8428. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8429. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8430. }
  8431. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8432. auto port = start(enable);
  8433. Client cli(HOST, port);
  8434. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8436. EXPECT_EQ(StatusCode::OK_200, res->status);
  8437. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8438. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8439. EXPECT_TRUE(res->body.empty());
  8440. }
  8441. TEST_F(StaticFileCompressionTest, MinLength) {
  8442. auto port = start(enable);
  8443. Client cli(HOST, port);
  8444. // 104 bytes, well under the default floor. Compressing it would add the
  8445. // gzip header and trailer to a body that already fits in one packet.
  8446. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8448. EXPECT_EQ(StatusCode::OK_200, res->status);
  8449. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8450. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8451. }
  8452. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8453. auto port = start([](Server &svr) {
  8454. svr.set_static_file_compression(true);
  8455. svr.set_static_file_compression_min_length(1);
  8456. });
  8457. Client cli(HOST, port);
  8458. cli.set_decompress(false);
  8459. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8461. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8462. // A 9-byte file comes back larger than it went in, because gzip's header and
  8463. // trailer outweigh anything deflate can save. That is the end of the range
  8464. // the floor exists to keep out.
  8465. EXPECT_GT(res->body.size(), 9U);
  8466. }
  8467. TEST_F(StaticFileCompressionTest, MaxLength) {
  8468. auto port = start([](Server &svr) {
  8469. svr.set_static_file_compression(true);
  8470. svr.set_static_file_compression_min_length(0);
  8471. svr.set_static_file_compression_max_length(1024);
  8472. });
  8473. Client cli(HOST, port);
  8474. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8475. // defines `small` as a macro on Windows.
  8476. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8477. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8478. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8479. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8480. // Under it: compressed.
  8481. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8482. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8483. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8484. }
  8485. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8486. auto port = start(enable_without_floor);
  8487. Client cli(HOST, port);
  8488. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8489. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8490. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8491. auto identity_etag = identity->get_header_value("ETag");
  8492. ASSERT_FALSE(identity_etag.empty());
  8493. auto gzipped =
  8494. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8495. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8496. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8497. auto gzip_etag = gzipped->get_header_value("ETag");
  8498. ASSERT_FALSE(gzip_etag.empty());
  8499. // Two representations, two validators.
  8500. EXPECT_NE(identity_etag, gzip_etag);
  8501. // Each one revalidates against the request that would produce it...
  8502. auto fresh =
  8503. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8504. {"If-None-Match", gzip_etag}});
  8505. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8506. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8507. auto fresh_identity =
  8508. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8509. {"If-None-Match", identity_etag}});
  8510. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8511. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8512. // ...and not against the other representation.
  8513. auto crossed =
  8514. cli.Get("/dir/index.html",
  8515. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8516. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8517. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8518. }
  8519. // The opt-in covers responses the server reads off disk itself. A caller's own
  8520. // known-length provider keeps its Content-Length and, more importantly, keeps
  8521. // delivering incrementally: routing it through a compressor would hold every
  8522. // write back until zlib's window filled.
  8523. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8524. auto port = start(enable);
  8525. Client cli(HOST, port);
  8526. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8528. EXPECT_EQ(StatusCode::OK_200, res->status);
  8529. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8530. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8531. EXPECT_EQ("aaabbb", res->body);
  8532. }
  8533. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8534. auto port = start(enable);
  8535. Client cli(HOST, port);
  8536. cli.set_read_timeout(1, 0);
  8537. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8538. Headers{{"Accept-Encoding", "gzip"}});
  8539. ASSERT_TRUE(handle.is_valid());
  8540. // The provider writes 100 bytes and then stalls for longer than the read
  8541. // timeout. Those first bytes have to arrive anyway: run the response through
  8542. // a compressor and zlib holds them until its window fills, so the read would
  8543. // come back empty instead.
  8544. char buf[256];
  8545. auto n = handle.read(buf, sizeof(buf));
  8546. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8547. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8548. }
  8549. #endif
  8550. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8551. TEST_F(ServerTest, Brotli) {
  8552. Headers headers;
  8553. headers.emplace("Accept-Encoding", "br");
  8554. auto res = cli_.Get("/compress", headers);
  8555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8556. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8557. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8558. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8559. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8560. "7890123456789012345678901234567890",
  8561. res->body);
  8562. EXPECT_EQ(StatusCode::OK_200, res->status);
  8563. }
  8564. #endif
  8565. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8566. TEST_F(ServerTest, Zstd) {
  8567. Headers headers;
  8568. headers.emplace("Accept-Encoding", "zstd");
  8569. auto res = cli_.Get("/compress", headers);
  8570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8571. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8572. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8573. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8574. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8575. "7890123456789012345678901234567890",
  8576. res->body);
  8577. EXPECT_EQ(StatusCode::OK_200, res->status);
  8578. }
  8579. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8580. Headers headers;
  8581. headers.emplace("Accept-Encoding", "");
  8582. auto res = cli_.Get("/compress", headers);
  8583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8584. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8585. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8586. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8587. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8588. "7890123456789012345678901234567890",
  8589. res->body);
  8590. EXPECT_EQ(StatusCode::OK_200, res->status);
  8591. }
  8592. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8593. Headers headers;
  8594. headers.emplace("Accept-Encoding", "zstd");
  8595. std::string body;
  8596. auto res = cli_.Get("/compress", headers,
  8597. [&](const char *data, uint64_t data_length) {
  8598. EXPECT_EQ(100U, data_length);
  8599. body.append(data, data_length);
  8600. return true;
  8601. });
  8602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8603. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8604. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8605. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8606. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8607. "7890123456789012345678901234567890",
  8608. body);
  8609. EXPECT_EQ(StatusCode::OK_200, res->status);
  8610. }
  8611. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8612. Headers headers;
  8613. headers.emplace("Accept-Encoding", "zstd");
  8614. cli_.set_decompress(false);
  8615. auto res = cli_.Get("/compress", headers);
  8616. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8617. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8618. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8619. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8621. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8622. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8623. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8624. EXPECT_EQ(StatusCode::OK_200, res->status);
  8625. ASSERT_EQ(26U, res->body.size());
  8626. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8627. 0);
  8628. }
  8629. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8630. Headers headers;
  8631. headers.emplace("Accept-Encoding", "");
  8632. std::string body;
  8633. auto res = cli_.Get("/compress", headers,
  8634. [&](const char *data, uint64_t data_length) {
  8635. EXPECT_EQ(100U, data_length);
  8636. body.append(data, data_length);
  8637. return true;
  8638. });
  8639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8640. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8641. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8642. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8643. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8644. "7890123456789012345678901234567890",
  8645. body);
  8646. EXPECT_EQ(StatusCode::OK_200, res->status);
  8647. }
  8648. TEST_F(ServerTest, NoZstd) {
  8649. Headers headers;
  8650. headers.emplace("Accept-Encoding", "zstd");
  8651. auto res = cli_.Get("/nocompress", headers);
  8652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8653. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8654. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8655. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8656. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8657. "7890123456789012345678901234567890",
  8658. res->body);
  8659. EXPECT_EQ(StatusCode::OK_200, res->status);
  8660. }
  8661. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8662. Headers headers;
  8663. headers.emplace("Accept-Encoding", "zstd");
  8664. std::string body;
  8665. auto res = cli_.Get("/nocompress", headers,
  8666. [&](const char *data, uint64_t data_length) {
  8667. EXPECT_EQ(100U, data_length);
  8668. body.append(data, data_length);
  8669. return true;
  8670. });
  8671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8672. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8673. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8674. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8675. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8676. "7890123456789012345678901234567890",
  8677. body);
  8678. EXPECT_EQ(StatusCode::OK_200, res->status);
  8679. }
  8680. // TODO: How to enable zstd ??
  8681. TEST_F(ServerTest, MultipartFormDataZstd) {
  8682. UploadFormDataItems items = {
  8683. {"key1", "test", "", ""},
  8684. {"key2", "--abcdefg123", "", ""},
  8685. };
  8686. Headers headers;
  8687. headers.emplace("Accept-Encoding", "zstd");
  8688. cli_.set_compress(true);
  8689. auto res = cli_.Post("/compress-multipart", headers, items);
  8690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8691. EXPECT_EQ(StatusCode::OK_200, res->status);
  8692. }
  8693. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8694. Headers headers;
  8695. headers.emplace("Accept-Encoding", "zstd");
  8696. cli_.set_compress(true);
  8697. auto res = cli_.Put(
  8698. "/put", headers, 3,
  8699. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8700. sink.os << "PUT";
  8701. return true;
  8702. },
  8703. "text/plain");
  8704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8705. EXPECT_EQ(StatusCode::OK_200, res->status);
  8706. EXPECT_EQ("PUT", res->body);
  8707. }
  8708. // Pre-compression logging tests
  8709. TEST_F(ServerTest, PreCompressionLogging) {
  8710. // Test data for compression (matches the actual /compress endpoint content)
  8711. const std::string test_content =
  8712. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8713. "3456789012345678901234567890";
  8714. // Variables to capture logging data
  8715. std::string pre_compression_body;
  8716. std::string pre_compression_content_type;
  8717. std::string pre_compression_content_encoding;
  8718. std::string post_compression_body;
  8719. std::string post_compression_content_type;
  8720. std::string post_compression_content_encoding;
  8721. // Set up pre-compression logger
  8722. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8723. const Response &res) {
  8724. pre_compression_body = res.body;
  8725. pre_compression_content_type = res.get_header_value("Content-Type");
  8726. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8727. });
  8728. // Set up post-compression logger
  8729. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8730. post_compression_body = res.body;
  8731. post_compression_content_type = res.get_header_value("Content-Type");
  8732. post_compression_content_encoding =
  8733. res.get_header_value("Content-Encoding");
  8734. });
  8735. // Test with gzip compression
  8736. Headers headers;
  8737. headers.emplace("Accept-Encoding", "gzip");
  8738. auto res = cli_.Get("/compress", headers);
  8739. // Verify response was compressed
  8740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8741. EXPECT_EQ(StatusCode::OK_200, res->status);
  8742. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8743. // Verify pre-compression logger captured uncompressed content
  8744. EXPECT_EQ(test_content, pre_compression_body);
  8745. EXPECT_EQ("text/plain", pre_compression_content_type);
  8746. EXPECT_TRUE(pre_compression_content_encoding
  8747. .empty()); // No encoding header before compression
  8748. // Verify post-compression logger captured compressed content
  8749. EXPECT_NE(test_content,
  8750. post_compression_body); // Should be different after compression
  8751. EXPECT_EQ("text/plain", post_compression_content_type);
  8752. EXPECT_EQ("gzip", post_compression_content_encoding);
  8753. // Verify compressed content is smaller
  8754. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8755. }
  8756. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8757. const std::string test_content =
  8758. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8759. "3456789012345678901234567890";
  8760. std::string pre_compression_body;
  8761. std::string post_compression_body;
  8762. svr_.set_pre_compression_logger(
  8763. [&](const Request & /*req*/, const Response &res) {
  8764. pre_compression_body = res.body;
  8765. });
  8766. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8767. post_compression_body = res.body;
  8768. });
  8769. Headers headers;
  8770. headers.emplace("Accept-Encoding", "br");
  8771. auto res = cli_.Get("/compress", headers);
  8772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8773. EXPECT_EQ(StatusCode::OK_200, res->status);
  8774. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8775. // Verify pre-compression content is uncompressed
  8776. EXPECT_EQ(test_content, pre_compression_body);
  8777. // Verify post-compression content is compressed
  8778. EXPECT_NE(test_content, post_compression_body);
  8779. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8780. }
  8781. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8782. const std::string test_content =
  8783. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8784. "3456789012345678901234567890";
  8785. std::string pre_compression_body;
  8786. std::string post_compression_body;
  8787. svr_.set_pre_compression_logger(
  8788. [&](const Request & /*req*/, const Response &res) {
  8789. pre_compression_body = res.body;
  8790. });
  8791. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8792. post_compression_body = res.body;
  8793. });
  8794. // Request without compression (use /nocompress endpoint)
  8795. Headers headers;
  8796. auto res = cli_.Get("/nocompress", headers);
  8797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8798. EXPECT_EQ(StatusCode::OK_200, res->status);
  8799. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8800. // Pre-compression logger should not be called when no compression is applied
  8801. EXPECT_TRUE(
  8802. pre_compression_body.empty()); // Pre-compression logger not called
  8803. EXPECT_EQ(
  8804. test_content,
  8805. post_compression_body); // Post-compression logger captures final content
  8806. }
  8807. TEST_F(ServerTest, LoggerSeesContentLength) {
  8808. size_t logged_content_length = 0;
  8809. std::string logged_content_length_header;
  8810. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8811. logged_content_length = res.content_length_;
  8812. logged_content_length_header = res.get_header_value("Content-Length");
  8813. });
  8814. auto res = cli_.Get("/nocompress");
  8815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8816. EXPECT_EQ(StatusCode::OK_200, res->status);
  8817. EXPECT_EQ(res->body.size(), logged_content_length);
  8818. EXPECT_EQ(std::to_string(logged_content_length),
  8819. logged_content_length_header);
  8820. }
  8821. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8822. const std::string test_content =
  8823. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8824. "3456789012345678901234567890";
  8825. std::string pre_compression_body;
  8826. bool pre_logger_called = false;
  8827. // Set only pre-compression logger
  8828. svr_.set_pre_compression_logger(
  8829. [&](const Request & /*req*/, const Response &res) {
  8830. pre_compression_body = res.body;
  8831. pre_logger_called = true;
  8832. });
  8833. Headers headers;
  8834. headers.emplace("Accept-Encoding", "gzip");
  8835. auto res = cli_.Get("/compress", headers);
  8836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8837. EXPECT_EQ(StatusCode::OK_200, res->status);
  8838. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8839. // Verify pre-compression logger was called
  8840. EXPECT_TRUE(pre_logger_called);
  8841. EXPECT_EQ(test_content, pre_compression_body);
  8842. }
  8843. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8844. {
  8845. // Test with Expect: 100-continue header - success case
  8846. // Server returns 100 Continue, client sends body, server returns 200 OK
  8847. Request req;
  8848. req.method = "POST";
  8849. req.path = "/post-large";
  8850. req.set_header("Expect", "100-continue");
  8851. req.body = LARGE_DATA;
  8852. Response res;
  8853. auto error = Error::Success;
  8854. cli_.set_keep_alive(true);
  8855. auto ret = cli_.send(req, res, error);
  8856. EXPECT_TRUE(ret);
  8857. EXPECT_EQ(StatusCode::OK_200, res.status);
  8858. EXPECT_EQ(LARGE_DATA, res.body);
  8859. }
  8860. {
  8861. // Test with Expect: 100-continue header - error case
  8862. // Client should not send the body when server returns an error
  8863. Request req;
  8864. req.method = "POST";
  8865. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8866. req.set_header("Expect", "100-continue");
  8867. req.body = LARGE_DATA;
  8868. Response res;
  8869. auto error = Error::Success;
  8870. auto start = std::chrono::high_resolution_clock::now();
  8871. cli_.set_keep_alive(true);
  8872. auto ret = cli_.send(req, res, error);
  8873. auto end = std::chrono::high_resolution_clock::now();
  8874. auto elapsed =
  8875. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8876. .count();
  8877. // With Expect: 100-continue, request completes successfully but with error
  8878. EXPECT_TRUE(ret);
  8879. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8880. EXPECT_EQ("close", res.get_header_value("Connection"));
  8881. EXPECT_FALSE(cli_.is_socket_open());
  8882. EXPECT_LE(elapsed, 2000);
  8883. }
  8884. {
  8885. // Send an extra GET request to ensure error recovery without hanging
  8886. Request req;
  8887. req.method = "GET";
  8888. req.path = "/hi";
  8889. auto start = std::chrono::high_resolution_clock::now();
  8890. auto res = cli_.send(req);
  8891. auto end = std::chrono::high_resolution_clock::now();
  8892. auto elapsed =
  8893. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8894. .count();
  8895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8896. EXPECT_EQ(StatusCode::OK_200, res->status);
  8897. EXPECT_EQ("Hello World!", res->body);
  8898. EXPECT_LE(elapsed, 500);
  8899. }
  8900. }
  8901. TEST(ZstdDecompressor, ChunkedDecompression) {
  8902. std::string data;
  8903. for (size_t i = 0; i < 32 * 1024; ++i) {
  8904. data.push_back(static_cast<char>('a' + i % 26));
  8905. }
  8906. std::string compressed_data;
  8907. {
  8908. httplib::detail::zstd_compressor compressor;
  8909. bool result = compressor.compress(
  8910. data.data(), data.size(),
  8911. /*last=*/true,
  8912. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8913. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8914. compressed_data_size);
  8915. return true;
  8916. });
  8917. ASSERT_TRUE(result);
  8918. }
  8919. std::string decompressed_data;
  8920. {
  8921. httplib::detail::zstd_decompressor decompressor;
  8922. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8923. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8924. size_t chunk_size = 130;
  8925. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8926. chunk_begin += chunk_size) {
  8927. size_t current_chunk_size =
  8928. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8929. bool result = decompressor.decompress(
  8930. compressed_data.data() + chunk_begin, current_chunk_size,
  8931. [&](const char *decompressed_data_chunk,
  8932. size_t decompressed_data_chunk_size) {
  8933. decompressed_data.insert(decompressed_data.size(),
  8934. decompressed_data_chunk,
  8935. decompressed_data_chunk_size);
  8936. return true;
  8937. });
  8938. ASSERT_TRUE(result);
  8939. }
  8940. }
  8941. ASSERT_EQ(data, decompressed_data);
  8942. }
  8943. TEST(ZstdDecompressor, Decompress) {
  8944. std::string original_text = "Compressed with ZSTD";
  8945. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8946. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8947. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8948. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8949. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8950. std::string decompressed_data;
  8951. {
  8952. httplib::detail::zstd_decompressor decompressor;
  8953. bool result = decompressor.decompress(
  8954. compressed_data.data(), compressed_data.size(),
  8955. [&](const char *decompressed_data_chunk,
  8956. size_t decompressed_data_chunk_size) {
  8957. decompressed_data.insert(decompressed_data.size(),
  8958. decompressed_data_chunk,
  8959. decompressed_data_chunk_size);
  8960. return true;
  8961. });
  8962. ASSERT_TRUE(result);
  8963. }
  8964. ASSERT_EQ(original_text, decompressed_data);
  8965. }
  8966. #endif
  8967. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8968. // separate chunks so that the server sees each part in its own read(). Used to
  8969. // place a read boundary at a specific offset of a request body.
  8970. static bool send_request_in_parts(time_t read_timeout_sec,
  8971. const std::vector<std::string> &parts,
  8972. std::string *resp = nullptr,
  8973. int port = PORT) {
  8974. auto error = Error::Success;
  8975. auto client_sock = detail::create_client_socket(
  8976. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8977. /*connection_timeout_sec=*/5, 0,
  8978. /*read_timeout_sec=*/5, 0,
  8979. /*write_timeout_sec=*/5, 0, std::string(), error);
  8980. if (client_sock == INVALID_SOCKET) { return false; }
  8981. auto ret = detail::process_client_socket(
  8982. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8983. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8984. for (size_t i = 0; i < parts.size(); i++) {
  8985. const auto &part = parts[i];
  8986. if (part.size() !=
  8987. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8988. return false;
  8989. }
  8990. if (i + 1 < parts.size()) {
  8991. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8992. }
  8993. }
  8994. char buf[512];
  8995. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8996. while (line_reader.getline()) {
  8997. if (resp) { *resp += line_reader.ptr(); }
  8998. }
  8999. return true;
  9000. });
  9001. detail::close_socket(client_sock);
  9002. return ret;
  9003. }
  9004. // Sends a raw request to a server listening at HOST:PORT.
  9005. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9006. std::string *resp = nullptr, int port = PORT) {
  9007. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9008. }
  9009. #ifdef CPPHTTPLIB_SSL_ENABLED
  9010. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9012. ASSERT_TRUE(svr.is_valid());
  9013. svr.set_read_timeout(1, 0);
  9014. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9015. auto se = detail::scope_exit([&] {
  9016. svr.stop();
  9017. t.join();
  9018. ASSERT_FALSE(svr.is_running());
  9019. });
  9020. svr.wait_until_ready();
  9021. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9022. // keeps each wait well within the read timeout. The server gives up a
  9023. // second in, so the bytes sent after that fail.
  9024. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9025. parts.resize(26, std::string(1, '\0'));
  9026. EXPECT_FALSE(send_request_in_parts(5, parts));
  9027. }
  9028. #endif
  9029. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9030. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9031. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9032. const std::vector<std::string> &parts,
  9033. std::string *resp = nullptr,
  9034. int port = PORT) {
  9035. auto error = Error::Success;
  9036. auto sock = detail::create_client_socket(
  9037. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9038. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9039. /*write_timeout_sec=*/5, 0, std::string(), error);
  9040. if (sock == INVALID_SOCKET) { return false; }
  9041. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9042. auto ctx = SSL_CTX_new(TLS_client_method());
  9043. auto ssl = SSL_new(ctx);
  9044. auto ssl_se = detail::scope_exit([&] {
  9045. SSL_free(ssl);
  9046. SSL_CTX_free(ctx);
  9047. });
  9048. SSL_set_fd(ssl, static_cast<int>(sock));
  9049. if (SSL_connect(ssl) != 1) { return false; }
  9050. for (size_t i = 0; i < parts.size(); i++) {
  9051. const auto &part = parts[i];
  9052. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9053. static_cast<int>(part.size())) {
  9054. return false;
  9055. }
  9056. if (i + 1 < parts.size()) {
  9057. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9058. }
  9059. }
  9060. char buf[512];
  9061. int n;
  9062. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9063. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9064. }
  9065. return true;
  9066. }
  9067. #endif
  9068. // The request line, then a header value a byte at a time.
  9069. static std::vector<std::string> slow_request_head_parts() {
  9070. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9071. parts.resize(26, "a");
  9072. parts.emplace_back("\r\n\r\n");
  9073. return parts;
  9074. }
  9075. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9076. // within the one-second read timeout. The server gives up a second in, before
  9077. // the head is complete.
  9078. static void
  9079. expect_slow_request_head_dropped(Server &svr,
  9080. const std::function<std::string()> &send) {
  9081. std::atomic<bool> handled(false);
  9082. svr.Get("/", [&](const Request &, Response &res) {
  9083. handled = true;
  9084. res.set_content("ok", "text/plain");
  9085. });
  9086. svr.set_read_timeout(1, 0);
  9087. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9088. auto se = detail::scope_exit([&] {
  9089. svr.stop();
  9090. t.join();
  9091. ASSERT_FALSE(svr.is_running());
  9092. });
  9093. svr.wait_until_ready();
  9094. auto resp = send();
  9095. EXPECT_FALSE(handled);
  9096. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9097. }
  9098. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9099. Server svr;
  9100. expect_slow_request_head_dropped(svr, [] {
  9101. std::string resp;
  9102. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9103. return resp;
  9104. });
  9105. }
  9106. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9107. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9108. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9109. ASSERT_TRUE(svr.is_valid());
  9110. expect_slow_request_head_dropped(svr, [] {
  9111. std::string resp;
  9112. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9113. return resp;
  9114. });
  9115. }
  9116. #endif
  9117. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9118. Server svr;
  9119. std::string header_value;
  9120. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9121. header_value = req.get_header_value("foo");
  9122. res.set_content("ok", "text/plain");
  9123. });
  9124. thread t = thread([&] { svr.listen(HOST, PORT); });
  9125. auto se = detail::scope_exit([&] {
  9126. svr.stop();
  9127. t.join();
  9128. ASSERT_FALSE(svr.is_running());
  9129. });
  9130. svr.wait_until_ready();
  9131. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9132. // like characters are not treated the same - use vertical tab and escape.
  9133. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9134. "foo: \t \v bar \x1B\t \r\n"
  9135. "Connection: close\r\n"
  9136. "\r\n";
  9137. std::string res;
  9138. ASSERT_TRUE(send_request(5, req, &res));
  9139. EXPECT_EQ(header_value, "");
  9140. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9141. }
  9142. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9143. Server svr;
  9144. std::string received;
  9145. svr.Get("/order", [&](const Request &req, Response &res) {
  9146. received = entries_to_string(req.headers);
  9147. res.set_content("ok", "text/plain");
  9148. });
  9149. auto port = svr.bind_to_any_port(HOST);
  9150. thread t = thread([&] { svr.listen_after_bind(); });
  9151. auto se = detail::scope_exit([&] {
  9152. svr.stop();
  9153. t.join();
  9154. ASSERT_FALSE(svr.is_running());
  9155. });
  9156. svr.wait_until_ready();
  9157. const std::string req = "GET /order HTTP/1.1\r\n"
  9158. "Host: localhost\r\n"
  9159. "X-First: 1\r\n"
  9160. "X-Dup: a\r\n"
  9161. "X-Second: 2\r\n"
  9162. "X-Dup: b\r\n"
  9163. "Connection: close\r\n"
  9164. "\r\n";
  9165. std::string res;
  9166. ASSERT_TRUE(send_request(5, req, &res, port));
  9167. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9168. EXPECT_EQ(
  9169. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9170. received);
  9171. }
  9172. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9173. Server svr;
  9174. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9175. res.set_header("Set-Cookie", "first=1");
  9176. res.set_header("X-Between", "y");
  9177. res.set_header("Set-Cookie", "second=2");
  9178. res.set_content("ok", "text/plain");
  9179. });
  9180. auto port = svr.bind_to_any_port(HOST);
  9181. thread t = thread([&] { svr.listen_after_bind(); });
  9182. auto se = detail::scope_exit([&] {
  9183. svr.stop();
  9184. t.join();
  9185. ASSERT_FALSE(svr.is_running());
  9186. });
  9187. svr.wait_until_ready();
  9188. Client cli(HOST, port);
  9189. auto res = cli.Get("/cookies");
  9190. ASSERT_TRUE(res);
  9191. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9192. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9193. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9194. }
  9195. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9196. Server svr;
  9197. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9198. auto i = new int(0);
  9199. res.set_header("Trailer", "X-Safe, X-Reflected");
  9200. res.set_chunked_content_provider(
  9201. "text/plain",
  9202. [i](size_t /*offset*/, DataSink &sink) {
  9203. if (*i == 0) {
  9204. sink.os << "body";
  9205. } else {
  9206. Headers trailer;
  9207. // A valid trailer that must survive.
  9208. trailer.emplace("X-Safe", "safe");
  9209. // Attacker-controlled value carrying CR/LF (response splitting).
  9210. trailer.emplace("X-Reflected",
  9211. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9212. // Attacker-controlled name carrying CR/LF.
  9213. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9214. sink.done_with_trailer(trailer);
  9215. }
  9216. (*i)++;
  9217. return true;
  9218. },
  9219. [i](bool /*success*/) { delete i; });
  9220. });
  9221. thread t = thread([&] { svr.listen(HOST, PORT); });
  9222. auto se = detail::scope_exit([&] {
  9223. svr.stop();
  9224. t.join();
  9225. ASSERT_FALSE(svr.is_running());
  9226. });
  9227. svr.wait_until_ready();
  9228. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9229. "Host: " + HOST +
  9230. "\r\n"
  9231. "Connection: close\r\n"
  9232. "\r\n";
  9233. std::string res;
  9234. ASSERT_TRUE(send_request(5, req, &res));
  9235. // The injected fields must not appear anywhere in the raw response.
  9236. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9237. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9238. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9239. // Invalid trailers are dropped entirely, matching set_header().
  9240. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9241. // The valid trailer still passes through.
  9242. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9243. }
  9244. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9245. Server svr;
  9246. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9247. // res.headers is a public field an application can populate directly,
  9248. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9249. // A valid header that must survive.
  9250. res.headers.emplace("X-Safe", "safe");
  9251. // Attacker-controlled value carrying CR/LF (response splitting).
  9252. res.headers.emplace("X-Reflected",
  9253. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9254. // Attacker-controlled name carrying CR/LF.
  9255. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9256. res.set_content("body", "text/plain");
  9257. });
  9258. thread t = thread([&] { svr.listen(HOST, PORT); });
  9259. auto se = detail::scope_exit([&] {
  9260. svr.stop();
  9261. t.join();
  9262. ASSERT_FALSE(svr.is_running());
  9263. });
  9264. svr.wait_until_ready();
  9265. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9266. "Host: " + HOST +
  9267. "\r\n"
  9268. "Connection: close\r\n"
  9269. "\r\n";
  9270. std::string res;
  9271. ASSERT_TRUE(send_request(5, req, &res));
  9272. // The injected fields must not appear anywhere in the raw response.
  9273. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9274. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9275. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9276. // Invalid headers are dropped entirely, matching set_header().
  9277. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9278. // The valid header still passes through.
  9279. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9280. }
  9281. // Forward declaration: in split builds split.py strips `inline` and moves the
  9282. // definition into httplib.cc, so detail::write_request_line is not visible from
  9283. // the public httplib.h. Re-declaring it here lets the tests link against the
  9284. // symbol in both header-only and split builds.
  9285. namespace httplib {
  9286. namespace detail {
  9287. ssize_t write_request_line(Stream &strm, const std::string &method,
  9288. const std::string &path);
  9289. } // namespace detail
  9290. } // namespace httplib
  9291. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9292. // A well-formed target is written verbatim.
  9293. {
  9294. detail::BufferStream strm;
  9295. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9296. EXPECT_GT(n, 0);
  9297. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9298. }
  9299. // A target carrying CR/LF, SP or other control octets must be rejected
  9300. // before anything reaches the wire, otherwise it splits the request line and
  9301. // injects a header or a whole request.
  9302. const std::string evil_targets[] = {
  9303. "/a\r\nInjected: pwned",
  9304. "/a\rInjected",
  9305. "/a\nInjected",
  9306. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9307. "/a b",
  9308. "/a\tb",
  9309. "/a\x7f",
  9310. };
  9311. for (const auto &evil : evil_targets) {
  9312. detail::BufferStream strm;
  9313. auto n = detail::write_request_line(strm, "GET", evil);
  9314. EXPECT_LT(n, 0);
  9315. EXPECT_TRUE(strm.get_buffer().empty());
  9316. }
  9317. }
  9318. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9319. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9320. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9321. // target reaches write_request. The client must fail cleanly with
  9322. // Error::Write instead of putting a request-line-less, header-injecting
  9323. // request on the wire.
  9324. Server svr;
  9325. svr.Get("/a", [](const Request &, Response &res) {
  9326. res.set_content("ok", "text/plain");
  9327. });
  9328. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9329. auto se = detail::scope_exit([&] {
  9330. svr.stop();
  9331. thread.join();
  9332. ASSERT_FALSE(svr.is_running());
  9333. });
  9334. svr.wait_until_ready();
  9335. {
  9336. Client cli(HOST, PORT);
  9337. cli.set_path_encode(false);
  9338. // The request is rejected before anything is written, so the connection
  9339. // stays silent and the subsequent response read would otherwise block for
  9340. // the full default read timeout. Shorten it -- the assertion is on the
  9341. // error, not the timeout.
  9342. cli.set_read_timeout(1, 0);
  9343. auto res = cli.Get("/a\r\nInjected: pwned");
  9344. EXPECT_FALSE(res);
  9345. EXPECT_EQ(Error::Write, res.error());
  9346. }
  9347. }
  9348. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9349. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9350. // including extension methods.
  9351. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9352. for (const auto &method : good_methods) {
  9353. detail::BufferStream strm;
  9354. auto n = detail::write_request_line(strm, method, "/");
  9355. EXPECT_GT(n, 0);
  9356. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9357. }
  9358. // A method carrying CR/LF would split the request line and smuggle a whole
  9359. // request ahead of the real one. A space or an empty method corrupts the
  9360. // request line. All must be rejected before anything reaches the wire.
  9361. const std::string evil_methods[] = {
  9362. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9363. "GET\r\nInjected: pwned",
  9364. "GET\r",
  9365. "GET\n",
  9366. "GE T",
  9367. "",
  9368. };
  9369. for (const auto &evil : evil_methods) {
  9370. detail::BufferStream strm;
  9371. auto n = detail::write_request_line(strm, evil, "/");
  9372. EXPECT_LT(n, 0);
  9373. EXPECT_TRUE(strm.get_buffer().empty());
  9374. }
  9375. }
  9376. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9377. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9378. // through Client::send must fail with Error::Write and no request, neither
  9379. // the smuggled one nor the real one, may reach the server.
  9380. Server svr;
  9381. std::atomic<int> request_count(0);
  9382. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9383. request_count++;
  9384. res.status = StatusCode::OK_200;
  9385. return Server::HandlerResponse::Handled;
  9386. });
  9387. auto port = svr.bind_to_any_port(HOST);
  9388. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9389. auto se = detail::scope_exit([&] {
  9390. svr.stop();
  9391. thread.join();
  9392. ASSERT_FALSE(svr.is_running());
  9393. });
  9394. svr.wait_until_ready();
  9395. {
  9396. Client cli(HOST, port);
  9397. const std::string evil_methods[] = {
  9398. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9399. "GE T",
  9400. "",
  9401. };
  9402. for (const auto &evil : evil_methods) {
  9403. Request req;
  9404. req.method = evil;
  9405. req.path = "/";
  9406. auto res = cli.send(req);
  9407. EXPECT_FALSE(res);
  9408. EXPECT_EQ(Error::Write, res.error());
  9409. }
  9410. auto handle =
  9411. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9412. EXPECT_FALSE(handle.is_valid());
  9413. EXPECT_EQ(Error::Write, handle.error);
  9414. // A valid request on the same client still goes through.
  9415. auto res = cli.Get("/");
  9416. ASSERT_TRUE(res);
  9417. EXPECT_EQ(StatusCode::OK_200, res->status);
  9418. }
  9419. EXPECT_EQ(1, request_count.load());
  9420. }
  9421. // Sends a raw request and verifies that there isn't a crash or exception.
  9422. static void test_raw_request(const std::string &req,
  9423. std::string *out = nullptr) {
  9424. Server svr;
  9425. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9426. res.set_content("ok", "text/plain");
  9427. });
  9428. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9429. res.set_content("ok", "text/plain");
  9430. });
  9431. svr.Get("/header_field_value_check",
  9432. [&](const Request & /*req*/, Response &res) {
  9433. res.set_content("ok", "text/plain");
  9434. });
  9435. svr.CustomRoute("PROPFIND", "/dav",
  9436. [&](const Request & /*req*/, Response &res) {
  9437. res.status = StatusCode::MultiStatus_207;
  9438. });
  9439. // Server read timeout must be longer than the client read timeout for the
  9440. // bug to reproduce, probably to force the server to process a request
  9441. // without a trailing blank line.
  9442. const time_t client_read_timeout_sec = 1;
  9443. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9444. bool listen_thread_ok = false;
  9445. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9446. auto se = detail::scope_exit([&] {
  9447. svr.stop();
  9448. t.join();
  9449. ASSERT_FALSE(svr.is_running());
  9450. EXPECT_TRUE(listen_thread_ok);
  9451. });
  9452. svr.wait_until_ready();
  9453. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9454. }
  9455. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9456. // A certain header line causes an exception if the header property is parsed
  9457. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9458. test_raw_request(
  9459. "GET /hi HTTP/1.1\r\n"
  9460. " : "
  9461. " "
  9462. " ");
  9463. }
  9464. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9465. // A certain header line causes an exception if the header property *name* is
  9466. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9467. // greedy matcher and requires backtracking when there are a lot of ":"
  9468. // characters.
  9469. // This occurs with libc++ but not libstdc++.
  9470. test_raw_request(
  9471. "GET /hi HTTP/1.1\r\n"
  9472. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9473. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9474. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9475. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9476. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9477. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9478. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9479. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9480. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9481. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9482. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9483. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9484. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9485. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9486. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9487. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9488. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9489. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9490. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9491. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9492. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9493. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9494. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9495. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9496. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9497. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9498. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9499. "&&&%%%");
  9500. }
  9501. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9502. // Make sure this doesn't crash the server.
  9503. // In a previous version of the header line regex, the "\r" rendered the line
  9504. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9505. // a new position where the leading white space ended and the field value
  9506. // began.
  9507. // The crash occurs with libc++ but not libstdc++.
  9508. test_raw_request("GET /hi HTTP/1.1\r\n"
  9509. "a:" +
  9510. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9511. "\r\n"
  9512. "\r\n");
  9513. }
  9514. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9515. const char *rejected[] = {
  9516. // RFC 9112 §3: one SP between the parts, and nothing else
  9517. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9518. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9519. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9520. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9521. // A request-target has no fragment
  9522. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9523. // An HTTP/1.1 request needs a Host
  9524. "GET /hi HTTP/1.1\r\n\r\n",
  9525. };
  9526. for (auto request : rejected) {
  9527. std::string out;
  9528. test_raw_request(request, &out);
  9529. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9530. }
  9531. std::string out;
  9532. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9533. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9534. }
  9535. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9536. // RFC 9112 §6.1
  9537. const char *requests[] = {
  9538. "PUT /put_hi HTTP/1.1\r\n"
  9539. "Host: localhost\r\n"
  9540. "Content-Length: 0\r\n"
  9541. "Transfer-Encoding: chunked\r\n"
  9542. "\r\n"
  9543. "0\r\n\r\n",
  9544. "PUT /put_hi HTTP/1.0\r\n"
  9545. "Connection: keep-alive\r\n"
  9546. "Transfer-Encoding: chunked\r\n"
  9547. "\r\n"
  9548. "0\r\n\r\n",
  9549. };
  9550. for (auto request : requests) {
  9551. std::string out;
  9552. test_raw_request(request, &out);
  9553. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9554. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9555. }
  9556. }
  9557. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9558. std::string out;
  9559. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9560. "Content-Type: text/plain\r\n"
  9561. "Transfer-Encoding: chunked\r\n"
  9562. "\r\n"
  9563. "nothex\r\n",
  9564. &out);
  9565. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9566. }
  9567. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9568. std::string out;
  9569. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9570. "Content-Type: text/plain\r\n"
  9571. "Transfer-Encoding: chunked\r\n"
  9572. "\r\n"
  9573. "3\r\n"
  9574. "xyz\r\n"
  9575. "NaN\r\n",
  9576. &out);
  9577. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9578. }
  9579. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9580. std::string out;
  9581. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9582. "Content-Type: text/plain\r\n"
  9583. "Transfer-Encoding: chunked\r\n"
  9584. "\r\n"
  9585. // Length is too large for 64 bits.
  9586. "1ffffffffffffffff\r\n"
  9587. "xyz\r\n",
  9588. &out);
  9589. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9590. }
  9591. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9592. test_raw_request("GET /hi HTTP/1.1\r\n"
  9593. "Content-Type: text/plain\r\n\r");
  9594. }
  9595. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9596. std::string out;
  9597. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9598. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9599. }
  9600. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9601. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9602. std::string out;
  9603. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9604. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9605. }
  9606. }
  9607. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9608. std::string out;
  9609. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9610. "Host: localhost\r\n"
  9611. "Connection: close\r\n\r\n",
  9612. &out);
  9613. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9614. }
  9615. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9616. Server svr;
  9617. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9618. EXPECT_TRUE(!req.remote_addr.empty());
  9619. });
  9620. thread t = thread([&] { svr.listen(HOST, PORT); });
  9621. auto se = detail::scope_exit([&] {
  9622. svr.stop();
  9623. t.join();
  9624. ASSERT_FALSE(svr.is_running());
  9625. });
  9626. svr.wait_until_ready();
  9627. // Send an invalid request line to trigger Bad Request
  9628. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9629. std::string out;
  9630. ASSERT_TRUE(send_request(5, bad_req, &out));
  9631. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9632. }
  9633. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9634. // answered right away rather than blocking on a read that waits for EOF.
  9635. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9636. std::string out;
  9637. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9638. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9639. }
  9640. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9641. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9642. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9643. for (const auto *method : methods) {
  9644. Server svr;
  9645. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9646. EXPECT_FALSE(svr.is_valid()) << method;
  9647. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9648. }
  9649. }
  9650. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9651. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9652. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9653. for (const auto *method : methods) {
  9654. Server svr;
  9655. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9656. EXPECT_FALSE(svr.is_valid()) << method;
  9657. }
  9658. }
  9659. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9660. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9661. "COPY", "MOVE", "LOCK",
  9662. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9663. Server svr;
  9664. for (const auto *method : methods) {
  9665. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9666. }
  9667. EXPECT_TRUE(svr.is_valid());
  9668. }
  9669. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9670. Server svr;
  9671. svr.CustomRoute("POST", "/x",
  9672. [](const Request &, Response &, const ContentReader &) {});
  9673. EXPECT_FALSE(svr.is_valid());
  9674. }
  9675. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9676. Server svr;
  9677. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9678. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9679. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9680. EXPECT_FALSE(svr.is_valid());
  9681. }
  9682. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9683. Server svr;
  9684. auto captured = Error::Success;
  9685. svr.set_error_logger(
  9686. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9687. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9688. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9689. }
  9690. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9691. std::string out;
  9692. std::string request(
  9693. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9694. test_raw_request(request, &out);
  9695. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9696. }
  9697. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9698. std::string out;
  9699. std::string request(
  9700. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9701. test_raw_request(request, &out);
  9702. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9703. }
  9704. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9705. std::string out;
  9706. std::string request(
  9707. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9708. test_raw_request(request, &out);
  9709. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9710. }
  9711. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9712. std::string out;
  9713. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9714. "Host: localhost\r\n"
  9715. "Test: \r\n\r\n",
  9716. &out);
  9717. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9718. }
  9719. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9720. Server svr;
  9721. std::string x_custom;
  9722. std::string cookie;
  9723. std::string xff;
  9724. std::string x_unicode;
  9725. std::string x_iis;
  9726. svr.Get("/check", [&](const Request &req, Response &res) {
  9727. x_custom = req.get_header_value("X-Custom");
  9728. cookie = req.get_header_value("Cookie");
  9729. xff = req.get_header_value("X-Forwarded-For");
  9730. x_unicode = req.get_header_value("X-Unicode");
  9731. x_iis = req.get_header_value("X-IIS");
  9732. res.set_content("ok", "text/plain");
  9733. });
  9734. thread t = thread([&] { svr.listen(HOST, PORT); });
  9735. auto se = detail::scope_exit([&] {
  9736. svr.stop();
  9737. t.join();
  9738. ASSERT_FALSE(svr.is_running());
  9739. });
  9740. svr.wait_until_ready();
  9741. const std::string req = "GET /check HTTP/1.1\r\n"
  9742. "Host: localhost\r\n"
  9743. "X-Custom: a%0D%0AInjected: b\r\n"
  9744. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9745. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9746. "X-Unicode: %E3%81%82\r\n"
  9747. "X-IIS: %u00E9\r\n"
  9748. "Connection: close\r\n"
  9749. "\r\n";
  9750. std::string res;
  9751. ASSERT_TRUE(send_request(5, req, &res));
  9752. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9753. // Every value must be returned verbatim (wire form), with no decoding.
  9754. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9755. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9756. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9757. EXPECT_EQ("%E3%81%82", x_unicode);
  9758. EXPECT_EQ("%u00E9", x_iis);
  9759. }
  9760. // Applications that previously relied on automatic percent-decoding can
  9761. // reproduce the old behavior by explicitly calling decode_path_component()
  9762. // or, for RFC 3986 conformance, decode_uri_component().
  9763. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9764. Server svr;
  9765. std::string decoded;
  9766. svr.Get("/check", [&](const Request &req, Response &res) {
  9767. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9768. res.set_content("ok", "text/plain");
  9769. });
  9770. thread t = thread([&] { svr.listen(HOST, PORT); });
  9771. auto se = detail::scope_exit([&] {
  9772. svr.stop();
  9773. t.join();
  9774. ASSERT_FALSE(svr.is_running());
  9775. });
  9776. svr.wait_until_ready();
  9777. const std::string req = "GET /check HTTP/1.1\r\n"
  9778. "Host: localhost\r\n"
  9779. "X-Custom: hello%20world\r\n"
  9780. "Connection: close\r\n"
  9781. "\r\n";
  9782. std::string res;
  9783. ASSERT_TRUE(send_request(5, req, &res));
  9784. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9785. EXPECT_EQ("hello world", decoded);
  9786. }
  9787. // Regression test for #2033. Browsers send Referer values that include
  9788. // percent-encoded characters such as %0A inside the URL. Decoding the
  9789. // header value would either trip the post-decode CR/LF/NUL guard (the
  9790. // original bug, returning 400) or, after that guard was relaxed, silently
  9791. // store a literal LF — both unacceptable. The wire form must round-trip.
  9792. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9793. Server svr;
  9794. std::string referer;
  9795. svr.Get("/check", [&](const Request &req, Response &res) {
  9796. referer = req.get_header_value("Referer");
  9797. res.set_content("ok", "text/plain");
  9798. });
  9799. thread t = thread([&] { svr.listen(HOST, PORT); });
  9800. auto se = detail::scope_exit([&] {
  9801. svr.stop();
  9802. t.join();
  9803. ASSERT_FALSE(svr.is_running());
  9804. });
  9805. svr.wait_until_ready();
  9806. const std::string req = "GET /check HTTP/1.1\r\n"
  9807. "Host: localhost\r\n"
  9808. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9809. "Connection: close\r\n"
  9810. "\r\n";
  9811. std::string res;
  9812. ASSERT_TRUE(send_request(5, req, &res));
  9813. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9814. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9815. }
  9816. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9817. Server svr;
  9818. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9819. res.set_header("Cache-Control", "no-cache");
  9820. res.set_chunked_content_provider(
  9821. "text/event-stream", [](size_t offset, DataSink &sink) {
  9822. std::string s = "data:";
  9823. s += std::to_string(offset);
  9824. s += "\n\n";
  9825. auto ret = sink.write(s.data(), s.size());
  9826. EXPECT_TRUE(ret);
  9827. std::this_thread::sleep_for(std::chrono::seconds(1));
  9828. return true;
  9829. });
  9830. });
  9831. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9832. svr.wait_until_ready();
  9833. Client client(HOST, PORT);
  9834. const Headers headers = {{"Accept", "text/event-stream"}};
  9835. auto get_thread = std::thread([&client, &headers]() {
  9836. auto res = client.Get(
  9837. "/events", headers,
  9838. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9839. });
  9840. auto se = detail::scope_exit([&] {
  9841. svr.stop();
  9842. get_thread.join();
  9843. listen_thread.join();
  9844. ASSERT_FALSE(svr.is_running());
  9845. });
  9846. // Give GET time to get a few messages.
  9847. std::this_thread::sleep_for(std::chrono::seconds(2));
  9848. }
  9849. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9850. httplib::Server svr;
  9851. svr.Post("/hi",
  9852. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9853. res.status = StatusCode::OK_200;
  9854. });
  9855. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9856. svr.wait_until_ready();
  9857. Client cli(HOST, PORT);
  9858. auto res = cli.Post("/hi", "data", "text/plain");
  9859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9860. EXPECT_EQ(StatusCode::OK_200, res->status);
  9861. svr.stop();
  9862. thread.join();
  9863. ASSERT_FALSE(svr.is_running());
  9864. res = cli.Post("/hi", "data", "text/plain");
  9865. ASSERT_FALSE(res);
  9866. }
  9867. TEST(ServerStopTest, ListenFailure) {
  9868. Server svr;
  9869. auto t = thread([&]() {
  9870. auto ret = svr.listen("????", PORT);
  9871. EXPECT_FALSE(ret);
  9872. });
  9873. svr.wait_until_ready();
  9874. svr.stop();
  9875. t.join();
  9876. }
  9877. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9878. TEST(ServerStopTest, Decommision) {
  9879. Server svr;
  9880. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9881. for (int i = 0; i < 4; i++) {
  9882. auto is_even = !(i % 2);
  9883. std::thread t{[&] {
  9884. try {
  9885. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9886. if (is_even) {
  9887. throw std::runtime_error("Some thing that happens to go wrong.");
  9888. }
  9889. svr.listen(HOST, PORT);
  9890. } catch (...) { svr.decommission(); }
  9891. }};
  9892. svr.wait_until_ready();
  9893. // Server is up
  9894. {
  9895. Client cli(HOST, PORT);
  9896. auto res = cli.Get("/hi");
  9897. if (is_even) {
  9898. EXPECT_FALSE(res);
  9899. } else {
  9900. EXPECT_TRUE(res);
  9901. EXPECT_EQ("hi...", res->body);
  9902. }
  9903. }
  9904. svr.stop();
  9905. t.join();
  9906. // Server is down...
  9907. {
  9908. Client cli(HOST, PORT);
  9909. auto res = cli.Get("/hi");
  9910. EXPECT_FALSE(res);
  9911. }
  9912. }
  9913. }
  9914. #endif
  9915. // Helper function for string body upload progress tests
  9916. template <typename SetupHandler, typename ClientCall>
  9917. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9918. ClientCall &&client_call,
  9919. const string &body) {
  9920. Server svr;
  9921. setup_handler(svr);
  9922. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9923. auto se = detail::scope_exit([&] {
  9924. svr.stop();
  9925. t.join();
  9926. });
  9927. svr.wait_until_ready();
  9928. Client cli(HOST, PORT);
  9929. vector<uint64_t> progress_values;
  9930. bool progress_called = false;
  9931. auto res =
  9932. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9933. progress_values.push_back(current);
  9934. progress_called = true;
  9935. return true;
  9936. });
  9937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9938. EXPECT_EQ(200, res->status);
  9939. EXPECT_TRUE(progress_called);
  9940. }
  9941. TEST(UploadProgressTest, PostStringBodyBasic) {
  9942. TestStringBodyUploadProgress(
  9943. [](Server &svr) {
  9944. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9945. res.set_content("received", "text/plain");
  9946. });
  9947. },
  9948. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9949. return cli.Post("/test", body, "text/plain", progress_callback);
  9950. },
  9951. "test data for upload progress");
  9952. }
  9953. TEST(UploadProgressTest, PutStringBodyBasic) {
  9954. TestStringBodyUploadProgress(
  9955. [](Server &svr) {
  9956. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9957. res.set_content("put received", "text/plain");
  9958. });
  9959. },
  9960. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9961. return cli.Put("/test", body, "text/plain", progress_callback);
  9962. },
  9963. "put test data for upload progress");
  9964. }
  9965. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9966. TestStringBodyUploadProgress(
  9967. [](Server &svr) {
  9968. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9969. res.set_content("patch received", "text/plain");
  9970. });
  9971. },
  9972. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9973. return cli.Patch("/test", body, "text/plain", progress_callback);
  9974. },
  9975. "patch test data for upload progress");
  9976. }
  9977. // Helper function for content provider upload progress tests
  9978. template <typename SetupHandler, typename ClientCall>
  9979. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9980. ClientCall &&client_call) {
  9981. Server svr;
  9982. setup_handler(svr);
  9983. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9984. auto se = detail::scope_exit([&] {
  9985. svr.stop();
  9986. t.join();
  9987. });
  9988. svr.wait_until_ready();
  9989. Client cli(HOST, PORT);
  9990. vector<uint64_t> progress_values;
  9991. auto res =
  9992. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9993. progress_values.push_back(current);
  9994. return true;
  9995. });
  9996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9997. EXPECT_EQ(200, res->status);
  9998. EXPECT_FALSE(progress_values.empty());
  9999. }
  10000. TEST(UploadProgressTest, PostContentProviderProgress) {
  10001. TestContentProviderUploadProgress(
  10002. [](Server &svr) {
  10003. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10004. res.set_content("provider received", "text/plain");
  10005. });
  10006. },
  10007. [](Client &cli, UploadProgress progress_callback) {
  10008. return cli.Post(
  10009. "/test", 9,
  10010. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10011. sink.os << "test data";
  10012. return true;
  10013. },
  10014. "text/plain", progress_callback);
  10015. });
  10016. }
  10017. // Helper function for multipart upload progress tests
  10018. template <typename SetupHandler, typename ClientCall>
  10019. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10020. ClientCall &&client_call,
  10021. const string &endpoint) {
  10022. Server svr;
  10023. setup_handler(svr);
  10024. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10025. auto se = detail::scope_exit([&] {
  10026. svr.stop();
  10027. t.join();
  10028. });
  10029. svr.wait_until_ready();
  10030. Client cli(HOST, PORT);
  10031. vector<uint64_t> progress_values;
  10032. UploadFormDataItems items = {
  10033. {"field1", "value1", "", ""},
  10034. {"field2", "longer value for progress tracking test", "", ""},
  10035. {"file1", "file content data for upload progress", "test.txt",
  10036. "text/plain"}};
  10037. auto res = client_call(cli, endpoint, items,
  10038. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10039. progress_values.push_back(current);
  10040. return true;
  10041. });
  10042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10043. EXPECT_EQ(200, res->status);
  10044. EXPECT_FALSE(progress_values.empty());
  10045. }
  10046. TEST(UploadProgressTest, PostMultipartProgress) {
  10047. TestMultipartUploadProgress(
  10048. [](Server &svr) {
  10049. svr.Post("/multipart", [](const Request &req, Response &res) {
  10050. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10051. res.set_content("multipart received", "text/plain");
  10052. });
  10053. },
  10054. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10055. UploadProgress progress_callback) {
  10056. return cli.Post(endpoint, items, progress_callback);
  10057. },
  10058. "/multipart");
  10059. }
  10060. // Helper function for basic download progress tests
  10061. template <typename SetupHandler, typename ClientCall>
  10062. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10063. ClientCall &&client_call, const string &endpoint,
  10064. size_t expected_content_size) {
  10065. Server svr;
  10066. setup_handler(svr);
  10067. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10068. auto se = detail::scope_exit([&] {
  10069. svr.stop();
  10070. t.join();
  10071. });
  10072. svr.wait_until_ready();
  10073. Client cli(HOST, PORT);
  10074. vector<uint64_t> progress_values;
  10075. auto res = client_call(cli, endpoint,
  10076. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10077. progress_values.push_back(current);
  10078. return true;
  10079. });
  10080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10081. EXPECT_EQ(200, res->status);
  10082. EXPECT_FALSE(progress_values.empty());
  10083. EXPECT_EQ(expected_content_size, res->body.size());
  10084. }
  10085. TEST(DownloadProgressTest, GetBasic) {
  10086. TestBasicDownloadProgress(
  10087. [](Server &svr) {
  10088. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10089. string content(1000, 'D');
  10090. res.set_content(content, "text/plain");
  10091. });
  10092. },
  10093. [](Client &cli, const string &endpoint,
  10094. DownloadProgress progress_callback) {
  10095. return cli.Get(endpoint, progress_callback);
  10096. },
  10097. "/download", 1000u);
  10098. }
  10099. // Helper function for content receiver download progress tests
  10100. template <typename SetupHandler, typename ClientCall>
  10101. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10102. ClientCall &&client_call,
  10103. const string &endpoint,
  10104. size_t expected_content_size) {
  10105. Server svr;
  10106. setup_handler(svr);
  10107. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10108. auto se = detail::scope_exit([&] {
  10109. svr.stop();
  10110. t.join();
  10111. });
  10112. svr.wait_until_ready();
  10113. Client cli(HOST, PORT);
  10114. vector<uint64_t> progress_values;
  10115. string received_body;
  10116. auto res = client_call(
  10117. cli, endpoint,
  10118. [&](const char *data, size_t data_length) -> bool {
  10119. received_body.append(data, data_length);
  10120. return true;
  10121. },
  10122. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10123. progress_values.push_back(current);
  10124. return true;
  10125. });
  10126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10127. EXPECT_EQ(200, res->status);
  10128. EXPECT_FALSE(progress_values.empty());
  10129. EXPECT_EQ(expected_content_size, received_body.size());
  10130. EXPECT_TRUE(res->body.empty());
  10131. }
  10132. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10133. TestContentReceiverDownloadProgress(
  10134. [](Server &svr) {
  10135. svr.Get("/download-receiver",
  10136. [](const Request & /*req*/, Response &res) {
  10137. string content(2000, 'R');
  10138. res.set_content(content, "text/plain");
  10139. });
  10140. },
  10141. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10142. DownloadProgress progress_callback) {
  10143. return cli.Get(endpoint, content_receiver, progress_callback);
  10144. },
  10145. "/download-receiver", 2000u);
  10146. }
  10147. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10148. // A provider reaching a pass with nothing to hand over - an empty buffer
  10149. // popped off a queue, say - must not be taken to mean the body is finished.
  10150. // It used to end the loop with the terminating chunk unwritten while the
  10151. // server still considered the response complete, so the peer waited for an
  10152. // end that never arrived.
  10153. Server svr;
  10154. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10155. auto step = std::make_shared<int>(0);
  10156. res.set_chunked_content_provider("text/plain",
  10157. [step](size_t /*offset*/, DataSink &sink) {
  10158. switch ((*step)++) {
  10159. case 0: sink.write("", 0); break;
  10160. case 1: sink.write("hello", 5); break;
  10161. default: sink.done(); break;
  10162. }
  10163. return true;
  10164. });
  10165. });
  10166. auto port = svr.bind_to_any_port(HOST);
  10167. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10168. auto listen_se = detail::scope_exit([&] {
  10169. svr.stop();
  10170. listen_thread.join();
  10171. ASSERT_FALSE(svr.is_running());
  10172. });
  10173. svr.wait_until_ready();
  10174. Client cli(HOST, port);
  10175. // Without the fix the body is never terminated, so bound the wait rather
  10176. // than letting the test hang on the default read timeout.
  10177. cli.set_read_timeout(5, 0);
  10178. auto res = cli.Get("/stream");
  10179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10180. EXPECT_EQ(StatusCode::OK_200, res->status);
  10181. EXPECT_EQ("hello", res->body);
  10182. }
  10183. TEST(StreamingTest, NoContentLengthStreaming) {
  10184. Server svr;
  10185. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10186. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10187. if (offset < 6) {
  10188. sink.os << (offset < 3 ? "a" : "b");
  10189. } else {
  10190. sink.done();
  10191. }
  10192. return true;
  10193. });
  10194. });
  10195. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10196. auto listen_se = detail::scope_exit([&] {
  10197. svr.stop();
  10198. listen_thread.join();
  10199. ASSERT_FALSE(svr.is_running());
  10200. });
  10201. svr.wait_until_ready();
  10202. Client client(HOST, PORT);
  10203. auto get_thread = std::thread([&client]() {
  10204. std::string s;
  10205. auto res =
  10206. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10207. s += std::string(data, len);
  10208. return true;
  10209. });
  10210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10211. EXPECT_EQ(StatusCode::OK_200, res->status);
  10212. EXPECT_EQ("aaabbb", s);
  10213. });
  10214. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10215. // Give GET time to get a few messages.
  10216. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10217. }
  10218. TEST(MountTest, Unmount) {
  10219. Server svr;
  10220. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10221. auto se = detail::scope_exit([&] {
  10222. svr.stop();
  10223. listen_thread.join();
  10224. ASSERT_FALSE(svr.is_running());
  10225. });
  10226. svr.wait_until_ready();
  10227. Client cli("localhost", PORT);
  10228. svr.set_mount_point("/mount2", "./www2");
  10229. auto res = cli.Get("/");
  10230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10231. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10232. res = cli.Get("/mount2/dir/test.html");
  10233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10234. EXPECT_EQ(StatusCode::OK_200, res->status);
  10235. svr.set_mount_point("/", "./www");
  10236. res = cli.Get("/dir/");
  10237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10238. EXPECT_EQ(StatusCode::OK_200, res->status);
  10239. svr.remove_mount_point("/");
  10240. res = cli.Get("/dir/");
  10241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10242. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10243. svr.remove_mount_point("/mount2");
  10244. res = cli.Get("/mount2/dir/test.html");
  10245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10246. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10247. }
  10248. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10249. Server svr;
  10250. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10251. svr.Get("/api/hello", [](const Request &, Response &res) {
  10252. res.set_content("api", "text/plain");
  10253. });
  10254. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10255. auto se = detail::scope_exit([&] {
  10256. svr.stop();
  10257. listen_thread.join();
  10258. ASSERT_FALSE(svr.is_running());
  10259. });
  10260. svr.wait_until_ready();
  10261. Client cli(HOST, PORT);
  10262. auto res = cli.Get("/dir/test.html");
  10263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10264. EXPECT_EQ(StatusCode::OK_200, res->status);
  10265. res = cli.Get("/api/hello");
  10266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10267. EXPECT_EQ(StatusCode::OK_200, res->status);
  10268. EXPECT_EQ("api", res->body);
  10269. }
  10270. TEST(MountTest, PathSegmentBoundary) {
  10271. Server svr;
  10272. svr.set_mount_point("/mount2", "./www2");
  10273. svr.set_mount_point("/", "./www");
  10274. auto port = svr.bind_to_any_port(HOST);
  10275. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10276. auto se = detail::scope_exit([&] {
  10277. svr.stop();
  10278. listen_thread.join();
  10279. ASSERT_FALSE(svr.is_running());
  10280. });
  10281. svr.wait_until_ready();
  10282. Client cli(HOST, port);
  10283. auto res = cli.Get("/mount2/dir/test.html");
  10284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10285. EXPECT_EQ(StatusCode::OK_200, res->status);
  10286. // "/mount2" must not match part-way through a path segment.
  10287. res = cli.Get("/mount2dir/test.html");
  10288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10289. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10290. // A mount point ending in '/' keeps matching every path below it.
  10291. res = cli.Get("/dir/test.html");
  10292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10293. EXPECT_EQ(StatusCode::OK_200, res->status);
  10294. }
  10295. TEST(MountTest, Redicect) {
  10296. Server svr;
  10297. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10298. auto se = detail::scope_exit([&] {
  10299. svr.stop();
  10300. listen_thread.join();
  10301. ASSERT_FALSE(svr.is_running());
  10302. });
  10303. svr.set_mount_point("/", "./www");
  10304. svr.wait_until_ready();
  10305. Client cli("localhost", PORT);
  10306. auto res = cli.Get("/dir/");
  10307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10308. EXPECT_EQ(StatusCode::OK_200, res->status);
  10309. res = cli.Get("/dir");
  10310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10311. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10312. res = cli.Get("/file");
  10313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10314. EXPECT_EQ(StatusCode::OK_200, res->status);
  10315. res = cli.Get("/file/");
  10316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10317. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10318. cli.set_follow_location(true);
  10319. res = cli.Get("/dir");
  10320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10321. EXPECT_EQ(StatusCode::OK_200, res->status);
  10322. }
  10323. TEST(MountTest, MultibytesPathName) {
  10324. Server svr;
  10325. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10326. auto se = detail::scope_exit([&] {
  10327. svr.stop();
  10328. listen_thread.join();
  10329. ASSERT_FALSE(svr.is_running());
  10330. });
  10331. svr.set_mount_point("/", "./www");
  10332. svr.wait_until_ready();
  10333. Client cli("localhost", PORT);
  10334. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10336. EXPECT_EQ(StatusCode::OK_200, res->status);
  10337. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10338. }
  10339. #ifdef _WIN32
  10340. // Issue #2435: mmap::open() must succeed even when another handle holds
  10341. // the file open for writing (e.g. an active log file).
  10342. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10343. const char *path = "mmap_concurrent_writer_test.txt";
  10344. const char *content = "hello";
  10345. {
  10346. std::ofstream f(path, std::ios::binary);
  10347. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10348. }
  10349. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10350. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10351. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10352. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10353. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10354. detail::mmap m(path);
  10355. ASSERT_TRUE(m.is_open());
  10356. EXPECT_EQ(strlen(content), m.size());
  10357. char buf[8];
  10358. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10359. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10360. }
  10361. #endif
  10362. #ifndef _WIN32
  10363. // A directory or a device has no size to serve.
  10364. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10365. const char *path = "./mmap_not_regular_test_dir";
  10366. ASSERT_EQ(0, ::mkdir(path, 0755));
  10367. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10368. for (auto p : {path, "/dev/null"}) {
  10369. detail::mmap m(p);
  10370. EXPECT_FALSE(m.is_open()) << p;
  10371. EXPECT_EQ(0U, m.size()) << p;
  10372. }
  10373. Server svr;
  10374. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10375. res.set_file_content("/dev/null");
  10376. });
  10377. auto port = svr.bind_to_any_port(HOST);
  10378. thread t = thread([&] { svr.listen_after_bind(); });
  10379. auto se = detail::scope_exit([&] {
  10380. svr.stop();
  10381. t.join();
  10382. });
  10383. svr.wait_until_ready();
  10384. auto res = Client(HOST, port).Get("/null");
  10385. ASSERT_TRUE(res);
  10386. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10387. }
  10388. #endif
  10389. #ifdef __linux__
  10390. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10391. TEST(MmapTest, FileIsNotMapped) {
  10392. const char *path = "mmap_not_mapped_test.txt";
  10393. {
  10394. std::ofstream f(path, std::ios::binary);
  10395. f << "hello";
  10396. }
  10397. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10398. detail::mmap m(path);
  10399. ASSERT_TRUE(m.is_open());
  10400. std::ifstream maps("/proc/self/maps");
  10401. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10402. std::istreambuf_iterator<char>());
  10403. EXPECT_EQ(std::string::npos, mappings.find(path));
  10404. }
  10405. #endif
  10406. TEST(KeepAliveTest, ReadTimeout) {
  10407. Server svr;
  10408. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10409. std::this_thread::sleep_for(std::chrono::seconds(2));
  10410. res.set_content("a", "text/plain");
  10411. });
  10412. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10413. res.set_content("b", "text/plain");
  10414. });
  10415. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10416. auto se = detail::scope_exit([&] {
  10417. svr.stop();
  10418. listen_thread.join();
  10419. ASSERT_FALSE(svr.is_running());
  10420. });
  10421. svr.wait_until_ready();
  10422. Client cli("localhost", PORT);
  10423. cli.set_keep_alive(true);
  10424. cli.set_read_timeout(std::chrono::seconds(1));
  10425. auto resa = cli.Get("/a");
  10426. ASSERT_FALSE(resa);
  10427. EXPECT_EQ(Error::Read, resa.error());
  10428. auto resb = cli.Get("/b");
  10429. ASSERT_TRUE(resb);
  10430. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10431. EXPECT_EQ("b", resb->body);
  10432. }
  10433. TEST(KeepAliveTest, MaxCount) {
  10434. size_t keep_alive_max_count = 3;
  10435. Server svr;
  10436. svr.set_keep_alive_max_count(keep_alive_max_count);
  10437. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10438. res.set_content("Hello World!", "text/plain");
  10439. });
  10440. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10441. auto se = detail::scope_exit([&] {
  10442. svr.stop();
  10443. listen_thread.join();
  10444. ASSERT_FALSE(svr.is_running());
  10445. });
  10446. svr.wait_until_ready();
  10447. Client cli(HOST, PORT);
  10448. cli.set_keep_alive(true);
  10449. for (size_t i = 0; i < 5; i++) {
  10450. auto result = cli.Get("/hi");
  10451. ASSERT_TRUE(result);
  10452. EXPECT_EQ(StatusCode::OK_200, result->status);
  10453. if (i == keep_alive_max_count - 1) {
  10454. EXPECT_EQ("close", result->get_header_value("Connection"));
  10455. } else {
  10456. EXPECT_FALSE(result->has_header("Connection"));
  10457. }
  10458. }
  10459. }
  10460. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10461. // can pull the next one into the server's buffer. The server must serve it
  10462. // without waiting for the socket to become readable again. The keep-alive
  10463. // timeout outlasts the client's read timeout, so a request left waiting for it
  10464. // shows up as a missing response.
  10465. static void serve_pipelining_routes(Server &svr,
  10466. const std::function<void(int)> &client) {
  10467. svr.set_keep_alive_timeout(5);
  10468. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10469. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10470. });
  10471. svr.Post("/echo", [](const Request &req, Response &res) {
  10472. res.set_content("echo " + req.body, "text/plain");
  10473. });
  10474. auto port = svr.bind_to_any_port(HOST);
  10475. thread t = thread([&] { svr.listen_after_bind(); });
  10476. auto se = detail::scope_exit([&] {
  10477. svr.stop();
  10478. t.join();
  10479. });
  10480. svr.wait_until_ready();
  10481. client(port);
  10482. }
  10483. static std::string
  10484. send_pipelined_requests(const std::vector<std::string> &parts) {
  10485. Server svr;
  10486. std::string res;
  10487. serve_pipelining_routes(svr, [&](int port) {
  10488. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10489. });
  10490. return res;
  10491. }
  10492. static void expect_in_order(const std::string &res,
  10493. const std::vector<std::string> &bodies) {
  10494. size_t pos = 0;
  10495. for (const auto &body : bodies) {
  10496. pos = res.find(body, pos);
  10497. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10498. pos += body.size();
  10499. }
  10500. }
  10501. TEST(KeepAliveTest, PipelinedRequests) {
  10502. auto res = send_pipelined_requests(
  10503. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10504. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10505. "Content-Length: 4\r\n\r\nbody"
  10506. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10507. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10508. }
  10509. // The second request starts in the server's buffer and ends on the socket.
  10510. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10511. auto res =
  10512. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10513. "GET /hi/2 HTTP/1.1\r\nHo",
  10514. "st: localhost\r\nConnection: close\r\n\r\n"});
  10515. expect_in_order(res, {"hi 1", "hi 2"});
  10516. }
  10517. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10518. // CRLF after a body does not turn into a 400 for the next request.
  10519. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10520. auto res = send_pipelined_requests(
  10521. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10522. "Content-Length: 4\r\n\r\nbody\r\n"
  10523. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10524. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10525. expect_in_order(res, {"echo body", "hi 2"});
  10526. }
  10527. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10528. // must not be served as the next request.
  10529. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10530. auto res = send_pipelined_requests(
  10531. {"INVALID REQUEST LINE\r\n\r\n"
  10532. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10533. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10534. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10535. }
  10536. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10537. // Over TLS, the next request is held by the TLS library as already decrypted
  10538. // data rather than on the socket.
  10539. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10540. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10541. std::string res;
  10542. serve_pipelining_routes(svr, [&](int port) {
  10543. // One part, so all three requests arrive in one TLS record
  10544. EXPECT_TRUE(send_ssl_request_in_parts(
  10545. 2,
  10546. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10547. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10548. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10549. &res, port));
  10550. });
  10551. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10552. }
  10553. #endif
  10554. TEST(KeepAliveTest, Issue1041) {
  10555. Server svr;
  10556. svr.set_keep_alive_timeout(3);
  10557. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10558. res.set_content("Hello World!", "text/plain");
  10559. });
  10560. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10561. auto se = detail::scope_exit([&] {
  10562. svr.stop();
  10563. listen_thread.join();
  10564. ASSERT_FALSE(svr.is_running());
  10565. });
  10566. svr.wait_until_ready();
  10567. Client cli(HOST, PORT);
  10568. cli.set_keep_alive(true);
  10569. auto result = cli.Get("/hi");
  10570. ASSERT_TRUE(result);
  10571. EXPECT_EQ(StatusCode::OK_200, result->status);
  10572. std::this_thread::sleep_for(std::chrono::seconds(5));
  10573. result = cli.Get("/hi");
  10574. ASSERT_TRUE(result);
  10575. EXPECT_EQ(StatusCode::OK_200, result->status);
  10576. }
  10577. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10578. Server svr;
  10579. svr.set_keep_alive_max_count(0);
  10580. std::set<int> remote_ports;
  10581. svr.Get("/hi", [&](const Request &req, Response &res) {
  10582. remote_ports.insert(req.remote_port);
  10583. res.set_content("hi", "text/plain");
  10584. });
  10585. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10586. auto se = detail::scope_exit([&] {
  10587. svr.stop();
  10588. listen_thread.join();
  10589. ASSERT_FALSE(svr.is_running());
  10590. });
  10591. svr.wait_until_ready();
  10592. Client cli(HOST, PORT);
  10593. cli.set_keep_alive(true);
  10594. for (int i = 0; i < 3; i++) {
  10595. auto res = cli.Get("/hi");
  10596. ASSERT_TRUE(res);
  10597. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10598. }
  10599. // All three over one connection
  10600. EXPECT_EQ(1u, remote_ports.size());
  10601. }
  10602. TEST(KeepAliveTest, Issue1959) {
  10603. Server svr;
  10604. svr.set_keep_alive_timeout(5);
  10605. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10606. res.set_content("a", "text/plain");
  10607. });
  10608. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10609. auto se = detail::scope_exit([&] {
  10610. if (!svr.is_running()) return;
  10611. svr.stop();
  10612. listen_thread.join();
  10613. ASSERT_FALSE(svr.is_running());
  10614. });
  10615. svr.wait_until_ready();
  10616. Client cli("localhost", PORT);
  10617. cli.set_keep_alive(true);
  10618. using namespace std::chrono;
  10619. auto start = steady_clock::now();
  10620. cli.Get("/a");
  10621. svr.stop();
  10622. listen_thread.join();
  10623. auto end = steady_clock::now();
  10624. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10625. EXPECT_LT(elapsed, 5000);
  10626. }
  10627. #ifdef CPPHTTPLIB_SSL_ENABLED
  10628. TEST(KeepAliveTest, SSLClientReconnection) {
  10629. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10630. ASSERT_TRUE(svr.is_valid());
  10631. svr.set_keep_alive_timeout(1);
  10632. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10633. res.set_content("Hello World!", "text/plain");
  10634. });
  10635. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10636. auto se = detail::scope_exit([&] {
  10637. svr.stop();
  10638. listen_thread.join();
  10639. ASSERT_FALSE(svr.is_running());
  10640. });
  10641. svr.wait_until_ready();
  10642. SSLClient cli(HOST, PORT);
  10643. cli.enable_server_certificate_verification(false);
  10644. cli.set_keep_alive(true);
  10645. auto result = cli.Get("/hi");
  10646. ASSERT_TRUE(result);
  10647. EXPECT_EQ(StatusCode::OK_200, result->status);
  10648. result = cli.Get("/hi");
  10649. ASSERT_TRUE(result);
  10650. EXPECT_EQ(StatusCode::OK_200, result->status);
  10651. std::this_thread::sleep_for(std::chrono::seconds(2));
  10652. // Recoonect
  10653. result = cli.Get("/hi");
  10654. ASSERT_TRUE(result);
  10655. EXPECT_EQ(StatusCode::OK_200, result->status);
  10656. result = cli.Get("/hi");
  10657. ASSERT_TRUE(result);
  10658. EXPECT_EQ(StatusCode::OK_200, result->status);
  10659. }
  10660. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10661. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10662. ASSERT_TRUE(svr.is_valid());
  10663. svr.set_keep_alive_timeout(1);
  10664. std::string content = "reconnect";
  10665. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10666. res.set_content("Hello World!", "text/plain");
  10667. });
  10668. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10669. auto se = detail::scope_exit([&] {
  10670. svr.stop();
  10671. listen_thread.join();
  10672. ASSERT_FALSE(svr.is_running());
  10673. });
  10674. svr.wait_until_ready();
  10675. SSLClient cli(HOST, PORT);
  10676. cli.enable_server_certificate_verification(false);
  10677. cli.set_keep_alive(true);
  10678. auto result = cli.Post(
  10679. "/hi", content.size(),
  10680. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10681. sink.write(content.c_str(), content.size());
  10682. return true;
  10683. },
  10684. "text/plain");
  10685. ASSERT_TRUE(result);
  10686. EXPECT_EQ(200, result->status);
  10687. std::this_thread::sleep_for(std::chrono::seconds(2));
  10688. // Recoonect
  10689. result = cli.Post(
  10690. "/hi", content.size(),
  10691. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10692. sink.write(content.c_str(), content.size());
  10693. return true;
  10694. },
  10695. "text/plain");
  10696. ASSERT_TRUE(result);
  10697. EXPECT_EQ(200, result->status);
  10698. result = cli.Post(
  10699. "/hi", content.size(),
  10700. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10701. sink.write(content.c_str(), content.size());
  10702. return true;
  10703. },
  10704. "text/plain");
  10705. ASSERT_TRUE(result);
  10706. EXPECT_EQ(200, result->status);
  10707. }
  10708. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10709. using namespace httplib::tls;
  10710. {
  10711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10712. ASSERT_TRUE(svr.is_valid());
  10713. svr.Get("/sni", [&](const Request &req, Response &res) {
  10714. std::string expected = req.sni();
  10715. EXPECT_EQ(expected, req.get_param_value("expected"));
  10716. res.set_content("ok", "text/plain");
  10717. });
  10718. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10719. auto se = detail::scope_exit([&] {
  10720. svr.stop();
  10721. listen_thread.join();
  10722. ASSERT_FALSE(svr.is_running());
  10723. });
  10724. svr.wait_until_ready();
  10725. {
  10726. SSLClient cli("localhost", PORT);
  10727. cli.enable_server_certificate_verification(false);
  10728. auto res = cli.Get("/sni?expected=localhost");
  10729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10730. }
  10731. {
  10732. SSLClient cli("::1", PORT);
  10733. cli.enable_server_certificate_verification(false);
  10734. auto res = cli.Get("/sni?expected=");
  10735. // NOTE: This may fail if the server is listening on IPv4 only
  10736. // (e.g., when localhost resolves to 127.0.0.1 only)
  10737. if (res) {
  10738. EXPECT_EQ(StatusCode::OK_200, res->status);
  10739. } else {
  10740. EXPECT_EQ(Error::Connection, res.error());
  10741. }
  10742. }
  10743. }
  10744. }
  10745. #endif
  10746. TEST(ClientProblemDetectionTest, ContentProvider) {
  10747. Server svr;
  10748. size_t content_length = 1024 * 1024;
  10749. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10750. res.set_content_provider(
  10751. content_length, "text/plain",
  10752. [&](size_t offset, size_t length, DataSink &sink) {
  10753. auto out_len = std::min(length, static_cast<size_t>(1024));
  10754. std::string out(out_len, '@');
  10755. sink.write(out.data(), out_len);
  10756. return offset < 4096;
  10757. },
  10758. [](bool success) { ASSERT_FALSE(success); });
  10759. });
  10760. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10761. res.set_content_provider(
  10762. 0, "text/plain",
  10763. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10764. EXPECT_TRUE(false);
  10765. return true;
  10766. },
  10767. [](bool success) { ASSERT_FALSE(success); });
  10768. });
  10769. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10770. auto se = detail::scope_exit([&] {
  10771. svr.stop();
  10772. listen_thread.join();
  10773. ASSERT_FALSE(svr.is_running());
  10774. });
  10775. svr.wait_until_ready();
  10776. Client cli("localhost", PORT);
  10777. {
  10778. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10779. size_t /*data_length*/) { return false; });
  10780. ASSERT_FALSE(res);
  10781. }
  10782. {
  10783. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10784. size_t /*data_length*/) { return false; });
  10785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10786. }
  10787. }
  10788. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10789. // A provider that reports success without writing anything and without
  10790. // calling done() used to be handed the same offset and length again on every
  10791. // pass, so it spun for as long as the peer stayed connected.
  10792. Server svr;
  10793. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10794. res.set_content("ok", "text/plain");
  10795. });
  10796. auto port = svr.bind_to_any_port(HOST);
  10797. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10798. auto se = detail::scope_exit([&] {
  10799. svr.stop();
  10800. listen_thread.join();
  10801. ASSERT_FALSE(svr.is_running());
  10802. });
  10803. svr.wait_until_ready();
  10804. std::atomic<int> call_count{0};
  10805. Client cli(HOST, port);
  10806. auto res = cli.Post(
  10807. "/", 1024,
  10808. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10809. // Give up after enough passes to show the spin, so that losing the
  10810. // check below fails this test instead of hanging it.
  10811. return ++call_count < 100;
  10812. },
  10813. "text/plain");
  10814. ASSERT_FALSE(res);
  10815. EXPECT_EQ(Error::Write, res.error());
  10816. EXPECT_EQ(1, call_count.load());
  10817. }
  10818. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10819. // A writer only has to assign `write`. The other three used to be left as
  10820. // empty std::functions, so a provider calling one threw
  10821. // std::bad_function_call out of the thread running it and took the whole
  10822. // process down.
  10823. DataSink sink;
  10824. std::string written;
  10825. sink.write = [&](const char *data, size_t data_len) {
  10826. written.append(data, data_len);
  10827. return true;
  10828. };
  10829. EXPECT_TRUE(sink.is_writable());
  10830. sink.done();
  10831. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10832. EXPECT_TRUE(written.empty());
  10833. }
  10834. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10835. // A sink that cannot carry trailers still has to finish.
  10836. DataSink sink;
  10837. auto done_count = 0;
  10838. sink.done = [&]() { done_count++; };
  10839. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10840. EXPECT_EQ(1, done_count);
  10841. }
  10842. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10843. Server svr;
  10844. const std::string body(4096, 'x');
  10845. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10846. res.set_content_provider(body.size(), "text/plain",
  10847. [&](size_t offset, size_t length, DataSink &sink) {
  10848. sink.write(body.data() + offset, length);
  10849. sink.done();
  10850. return true;
  10851. });
  10852. });
  10853. auto port = svr.bind_to_any_port(HOST);
  10854. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10855. auto se = detail::scope_exit([&] {
  10856. svr.stop();
  10857. listen_thread.join();
  10858. ASSERT_FALSE(svr.is_running());
  10859. });
  10860. svr.wait_until_ready();
  10861. Client cli(HOST, port);
  10862. auto res = cli.Get("/");
  10863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10864. EXPECT_EQ(StatusCode::OK_200, res->status);
  10865. EXPECT_EQ(body, res->body);
  10866. }
  10867. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10868. Server svr;
  10869. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10870. res.set_content_provider(
  10871. 1024, "text/plain",
  10872. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10873. sink.write("hello", 5);
  10874. sink.done(); // short of the 1024 bytes the response promised
  10875. return true;
  10876. });
  10877. });
  10878. auto port = svr.bind_to_any_port(HOST);
  10879. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10880. auto se = detail::scope_exit([&] {
  10881. svr.stop();
  10882. listen_thread.join();
  10883. ASSERT_FALSE(svr.is_running());
  10884. });
  10885. svr.wait_until_ready();
  10886. Client cli(HOST, port);
  10887. cli.set_read_timeout(5, 0);
  10888. // The response is short of its Content-Length, so the client cannot read a
  10889. // complete body. What matters is that this returns at all: a no-op done()
  10890. // would leave the writer looping over a provider that never makes progress.
  10891. auto res = cli.Get("/");
  10892. EXPECT_FALSE(res);
  10893. }
  10894. // Read as the next response by a peer that sees it after a framed body.
  10895. static const std::string smuggled_response =
  10896. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  10897. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  10898. Server svr;
  10899. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10900. res.set_content_provider(
  10901. 5, "text/plain",
  10902. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10903. auto data = "AAAAA" + smuggled_response;
  10904. sink.write(data.data(), data.size());
  10905. return true;
  10906. });
  10907. });
  10908. thread t = thread([&] { svr.listen(HOST, PORT); });
  10909. auto se = detail::scope_exit([&] {
  10910. svr.stop();
  10911. t.join();
  10912. ASSERT_FALSE(svr.is_running());
  10913. });
  10914. svr.wait_until_ready();
  10915. std::string resp;
  10916. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  10917. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  10918. resp.clear();
  10919. ASSERT_TRUE(send_request(
  10920. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  10921. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  10922. }
  10923. TEST(NoContentTest, BodyIsNotSent) {
  10924. Server svr;
  10925. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  10926. res.status = StatusCode::NoContent_204;
  10927. res.set_content(smuggled_response, "text/plain");
  10928. });
  10929. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  10930. res.status = StatusCode::NotModified_304;
  10931. res.set_chunked_content_provider(
  10932. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  10933. sink.write(smuggled_response.data(), smuggled_response.size());
  10934. sink.done();
  10935. return true;
  10936. });
  10937. });
  10938. thread t = thread([&] { svr.listen(HOST, PORT); });
  10939. auto se = detail::scope_exit([&] {
  10940. svr.stop();
  10941. t.join();
  10942. ASSERT_FALSE(svr.is_running());
  10943. });
  10944. svr.wait_until_ready();
  10945. for (auto path : {"/204", "/304"}) {
  10946. std::string resp;
  10947. ASSERT_TRUE(send_request(
  10948. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  10949. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  10950. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  10951. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  10952. }
  10953. }
  10954. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  10955. Server svr;
  10956. std::atomic<bool> smuggled(false);
  10957. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10958. res.set_content("ok", "text/plain");
  10959. });
  10960. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  10961. smuggled = true;
  10962. });
  10963. auto port = svr.bind_to_any_port(HOST);
  10964. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10965. auto se = detail::scope_exit([&] {
  10966. svr.stop();
  10967. listen_thread.join();
  10968. ASSERT_FALSE(svr.is_running());
  10969. });
  10970. svr.wait_until_ready();
  10971. // What follows the body would be read as the next request.
  10972. Client cli(HOST, port);
  10973. auto res = cli.Post(
  10974. "/", 5,
  10975. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10976. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  10977. sink.write(data.data(), data.size());
  10978. return true;
  10979. },
  10980. "text/plain");
  10981. ASSERT_FALSE(res);
  10982. EXPECT_EQ(Error::Write, res.error());
  10983. EXPECT_FALSE(smuggled);
  10984. }
  10985. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10986. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10987. // The compressed path builds the whole body before connecting, so this
  10988. // fails client-side and never reaches a server.
  10989. Client cli(HOST, PORT);
  10990. cli.set_compress(true);
  10991. auto res = cli.Post(
  10992. "/", 1024,
  10993. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10994. sink.write("hello", 5);
  10995. sink.done(); // short of the 1024 bytes the request announced
  10996. return true;
  10997. },
  10998. "text/plain");
  10999. ASSERT_FALSE(res);
  11000. EXPECT_EQ(Error::Write, res.error());
  11001. }
  11002. #endif
  11003. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11004. Server svr;
  11005. svr.set_error_handler([](Request const &, Response &res) -> void {
  11006. res.set_chunked_content_provider(
  11007. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11008. sink.os << "hello";
  11009. sink.os << "world";
  11010. sink.done();
  11011. return true;
  11012. });
  11013. });
  11014. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11015. auto se = detail::scope_exit([&] {
  11016. svr.stop();
  11017. listen_thread.join();
  11018. ASSERT_FALSE(svr.is_running());
  11019. });
  11020. svr.wait_until_ready();
  11021. Client cli("localhost", PORT);
  11022. auto res = cli.Get("/");
  11023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11024. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11025. EXPECT_EQ("helloworld", res->body);
  11026. }
  11027. // A body set after a content provider must replace it, not be sent through it.
  11028. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11029. Server svr;
  11030. svr.set_mount_point("/", "./www");
  11031. svr.set_file_request_handler([](const Request &req, Response &res) {
  11032. if (req.path == "/dir/test.html") {
  11033. res.status = StatusCode::Forbidden_403;
  11034. res.set_content(std::string(5000, 'D'), "text/plain");
  11035. } else if (req.path == "/file") {
  11036. res.status = StatusCode::Forbidden_403;
  11037. res.body = "Denied";
  11038. }
  11039. });
  11040. auto port = svr.bind_to_any_port(HOST);
  11041. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11042. auto se = detail::scope_exit([&] {
  11043. svr.stop();
  11044. t.join();
  11045. ASSERT_FALSE(svr.is_running());
  11046. });
  11047. svr.wait_until_ready();
  11048. Client cli(HOST, port);
  11049. {
  11050. auto res = cli.Get("/dir/test.html");
  11051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11052. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11053. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11054. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11055. }
  11056. {
  11057. auto res = cli.Get("/file");
  11058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11059. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11060. EXPECT_EQ("Denied", res->body);
  11061. }
  11062. {
  11063. auto res = cli.Get("/dir/index.html");
  11064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11065. EXPECT_EQ(StatusCode::OK_200, res->status);
  11066. EXPECT_EQ(0U, res->body.find("<html>"));
  11067. }
  11068. }
  11069. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11070. Server svr;
  11071. std::vector<bool> released;
  11072. std::mutex released_mutex;
  11073. auto releaser = [&](bool success) {
  11074. std::lock_guard<std::mutex> guard(released_mutex);
  11075. released.push_back(success);
  11076. };
  11077. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11078. return sink.write(&"hello"[offset], length);
  11079. };
  11080. svr.Get("/sized", [&](const Request &, Response &res) {
  11081. res.status = StatusCode::NotFound_404;
  11082. res.set_content_provider(5, "text/plain", provider, releaser);
  11083. });
  11084. svr.Get("/chunked", [&](const Request &, Response &res) {
  11085. res.status = StatusCode::ServiceUnavailable_503;
  11086. res.set_chunked_content_provider(
  11087. "text/plain",
  11088. [](size_t, DataSink &sink) {
  11089. sink.os << "chunk";
  11090. sink.done();
  11091. return true;
  11092. },
  11093. releaser);
  11094. });
  11095. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11096. res.set_content_provider(5, "text/plain", provider, releaser);
  11097. throw std::runtime_error("after the provider");
  11098. });
  11099. svr.set_error_handler([](const Request &req, Response &res) {
  11100. // Leave the exception handler's content to it.
  11101. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11102. res.set_content(std::string(1000, 'E'), "text/html");
  11103. return Server::HandlerResponse::Handled;
  11104. });
  11105. svr.set_exception_handler(
  11106. [](const Request &, Response &res, std::exception_ptr) {
  11107. res.status = StatusCode::InternalServerError_500;
  11108. res.set_content(std::string(1000, 'X'), "text/html");
  11109. });
  11110. auto port = svr.bind_to_any_port(HOST);
  11111. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11112. auto se = detail::scope_exit([&] {
  11113. svr.stop();
  11114. t.join();
  11115. ASSERT_FALSE(svr.is_running());
  11116. });
  11117. svr.wait_until_ready();
  11118. Client cli(HOST, port);
  11119. {
  11120. auto res = cli.Get("/sized");
  11121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11122. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11123. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11124. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11125. }
  11126. {
  11127. auto res = cli.Get("/chunked");
  11128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11129. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11130. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11131. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11132. }
  11133. {
  11134. auto res = cli.Get("/throw");
  11135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11136. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11137. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11138. }
  11139. std::lock_guard<std::mutex> guard(released_mutex);
  11140. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11141. }
  11142. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11143. Server svr;
  11144. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11145. return sink.write(&"abc"[offset], length);
  11146. };
  11147. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11148. res.set_file_content("./www/dir/test.html");
  11149. res.set_content("body", "text/plain");
  11150. });
  11151. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11152. res.set_content(std::string(100, 'B'), "text/plain");
  11153. res.set_file_content("./www/dir/test.html");
  11154. });
  11155. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11156. res.set_content(std::string(100, 'B'), "text/plain");
  11157. res.set_content_provider(3, "text/plain", abc);
  11158. });
  11159. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11160. res.set_content_provider(3, "text/plain", abc);
  11161. res.set_content(std::string(100, 'B'), "text/plain");
  11162. });
  11163. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11164. res.set_content_provider(3, "text/plain", abc);
  11165. res.body = "direct";
  11166. });
  11167. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11168. res.set_file_content("./www/dir/test.html");
  11169. res.body = "direct";
  11170. });
  11171. auto port = svr.bind_to_any_port(HOST);
  11172. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11173. auto se = detail::scope_exit([&] {
  11174. svr.stop();
  11175. t.join();
  11176. ASSERT_FALSE(svr.is_running());
  11177. });
  11178. svr.wait_until_ready();
  11179. Client cli(HOST, port);
  11180. auto expect_body = [&](const char *path, const std::string &body) {
  11181. // Uncompressed, so Content-Length can be compared with the body.
  11182. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11183. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11184. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11185. EXPECT_EQ(body, res->body) << path;
  11186. EXPECT_EQ(std::to_string(body.size()),
  11187. res->get_header_value("Content-Length"))
  11188. << path;
  11189. };
  11190. expect_body("/file-then-body", "body");
  11191. expect_body("/body-then-file", "test.html");
  11192. expect_body("/body-then-provider", "abc");
  11193. expect_body("/provider-then-body", std::string(100, 'B'));
  11194. expect_body("/provider-then-direct-body", "direct");
  11195. expect_body("/file-then-direct-body", "direct");
  11196. // Ranges are checked against the body, not the dropped provider.
  11197. {
  11198. auto res = cli.Get("/provider-then-direct-body",
  11199. Headers{{make_range_header({{1, 2}})}});
  11200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11201. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11202. EXPECT_EQ("ir", res->body);
  11203. }
  11204. {
  11205. auto res = cli.Get("/file-then-direct-body",
  11206. Headers{{make_range_header({{7, 8}})}});
  11207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11208. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11209. }
  11210. }
  11211. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11212. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11213. const char *path = "./truncated_while_served.txt";
  11214. const size_t size = 32 * 1024 * 1024;
  11215. {
  11216. std::ofstream f(path, std::ios::binary);
  11217. f << std::string(size, 'x');
  11218. }
  11219. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11220. // Over TLS, where the bytes are encrypted in this process rather than
  11221. // copied by send().
  11222. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11223. svr.Get("/file", [&](const Request &, Response &res) {
  11224. res.set_file_content(path, "text/plain");
  11225. });
  11226. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11227. auto se = detail::scope_exit([&] {
  11228. svr.stop();
  11229. thread.join();
  11230. ASSERT_FALSE(svr.is_running());
  11231. });
  11232. svr.wait_until_ready();
  11233. // The file shrinks once the first bytes are in, as a rewrite in place
  11234. // would, and reading the mapping past its new end used to raise SIGBUS.
  11235. SSLClient cli(HOST, PORT);
  11236. cli.enable_server_certificate_verification(false);
  11237. size_t received = 0;
  11238. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11239. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11240. received += len;
  11241. return true;
  11242. });
  11243. EXPECT_FALSE(res);
  11244. EXPECT_LT(received, size);
  11245. }
  11246. #endif
  11247. // Forward declaration (see the base64_encode note).
  11248. namespace httplib {
  11249. namespace detail {
  11250. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11251. const std::string &content_type,
  11252. EncodingType encoding);
  11253. } // namespace detail
  11254. } // namespace httplib
  11255. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11256. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11257. ASSERT_TRUE(mm->is_open());
  11258. Response res;
  11259. detail::set_file_content_provider(res, mm, "text/html",
  11260. detail::EncodingType::None);
  11261. std::string out;
  11262. DataSink sink;
  11263. sink.write = [&](const char *d, size_t l) {
  11264. out.append(d, l);
  11265. return true;
  11266. };
  11267. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11268. EXPECT_EQ("test.html", out);
  11269. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11270. EXPECT_EQ("test.html", out);
  11271. }
  11272. TEST(LongPollingTest, ClientCloseDetection) {
  11273. Server svr;
  11274. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11275. res.set_chunked_content_provider(
  11276. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11277. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11278. sink.os << "hello";
  11279. auto count = 10;
  11280. while (count > 0 && sink.is_writable()) {
  11281. this_thread::sleep_for(chrono::milliseconds(10));
  11282. count--;
  11283. }
  11284. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11285. return true;
  11286. });
  11287. });
  11288. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11289. auto se = detail::scope_exit([&] {
  11290. svr.stop();
  11291. listen_thread.join();
  11292. ASSERT_FALSE(svr.is_running());
  11293. });
  11294. svr.wait_until_ready();
  11295. Client cli("localhost", PORT);
  11296. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11297. EXPECT_EQ("hello", string(data, data_length));
  11298. return false; // close the socket immediately.
  11299. });
  11300. ASSERT_FALSE(res);
  11301. }
  11302. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11303. Server svr;
  11304. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11305. res.set_chunked_content_provider(
  11306. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11307. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11308. sink.os << "hello";
  11309. EXPECT_TRUE(sink.os.good());
  11310. // Wait for the client to close the connection
  11311. auto count = 10;
  11312. while (count > 0 && sink.is_writable()) {
  11313. this_thread::sleep_for(chrono::milliseconds(10));
  11314. count--;
  11315. }
  11316. // After client disconnect, write repeatedly until the socket
  11317. // write actually fails (small writes may be absorbed by the
  11318. // kernel buffer)
  11319. std::string chunk(1024, 'x');
  11320. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11321. sink.os << chunk;
  11322. }
  11323. EXPECT_TRUE(sink.os.fail());
  11324. return true;
  11325. });
  11326. });
  11327. auto port = svr.bind_to_any_port("localhost");
  11328. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11329. auto se = detail::scope_exit([&] {
  11330. svr.stop();
  11331. listen_thread.join();
  11332. ASSERT_FALSE(svr.is_running());
  11333. });
  11334. svr.wait_until_ready();
  11335. Client cli("localhost", port);
  11336. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11337. EXPECT_EQ("hello", string(data, data_length));
  11338. return false; // close the socket immediately.
  11339. });
  11340. ASSERT_FALSE(res);
  11341. }
  11342. TEST(GetWithParametersTest, GetWithParameters) {
  11343. Server svr;
  11344. svr.Get("/", [&](const Request &req, Response &) {
  11345. EXPECT_EQ("world", req.get_param_value("hello"));
  11346. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11347. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11348. });
  11349. svr.Get("/params", [&](const Request &req, Response &) {
  11350. EXPECT_EQ("world", req.get_param_value("hello"));
  11351. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11352. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11353. });
  11354. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11355. EXPECT_EQ("resource-id", req.matches[1]);
  11356. EXPECT_EQ("foo", req.get_param_value("param1"));
  11357. EXPECT_EQ("bar", req.get_param_value("param2"));
  11358. });
  11359. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11360. EXPECT_EQ("user-id", req.path_params.at("id"));
  11361. EXPECT_EQ("foo", req.get_param_value("param1"));
  11362. EXPECT_EQ("bar", req.get_param_value("param2"));
  11363. });
  11364. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11365. auto se = detail::scope_exit([&] {
  11366. svr.stop();
  11367. listen_thread.join();
  11368. ASSERT_FALSE(svr.is_running());
  11369. });
  11370. svr.wait_until_ready();
  11371. {
  11372. Client cli(HOST, PORT);
  11373. Params params;
  11374. params.emplace("hello", "world");
  11375. params.emplace("hello2", "world2");
  11376. params.emplace("hello3", "world3");
  11377. auto res = cli.Get("/", params, Headers{});
  11378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11379. EXPECT_EQ(StatusCode::OK_200, res->status);
  11380. }
  11381. {
  11382. Client cli(HOST, PORT);
  11383. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11385. EXPECT_EQ(StatusCode::OK_200, res->status);
  11386. }
  11387. {
  11388. Client cli(HOST, PORT);
  11389. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11391. EXPECT_EQ(StatusCode::OK_200, res->status);
  11392. }
  11393. {
  11394. Client cli(HOST, PORT);
  11395. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11397. EXPECT_EQ(StatusCode::OK_200, res->status);
  11398. }
  11399. }
  11400. TEST(GetWithParametersTest, GetWithParameters2) {
  11401. Server svr;
  11402. svr.Get("/", [&](const Request &req, Response &res) {
  11403. auto text = req.get_param_value("hello");
  11404. res.set_content(text, "text/plain");
  11405. });
  11406. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11407. auto se = detail::scope_exit([&] {
  11408. svr.stop();
  11409. listen_thread.join();
  11410. ASSERT_FALSE(svr.is_running());
  11411. });
  11412. svr.wait_until_ready();
  11413. Client cli("localhost", PORT);
  11414. Params params;
  11415. params.emplace("hello", "world");
  11416. std::string body;
  11417. auto res = cli.Get("/", params, Headers{},
  11418. [&](const char *data, size_t data_length) {
  11419. body.append(data, data_length);
  11420. return true;
  11421. });
  11422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11423. EXPECT_EQ(StatusCode::OK_200, res->status);
  11424. EXPECT_EQ("world", body);
  11425. }
  11426. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11427. Server svr;
  11428. svr.Get("/search", [&](const Request &req, Response &res) {
  11429. auto q = req.get_param_value("q");
  11430. res.set_content(q, "text/plain");
  11431. });
  11432. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11433. auto se = detail::scope_exit([&] {
  11434. svr.stop();
  11435. listen_thread.join();
  11436. ASSERT_FALSE(svr.is_running());
  11437. });
  11438. svr.wait_until_ready();
  11439. Client cli("localhost", PORT);
  11440. // Verify that Get(path, params) works without requiring Headers argument
  11441. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11443. EXPECT_EQ(StatusCode::OK_200, res->status);
  11444. EXPECT_EQ("cpp-httplib", res->body);
  11445. }
  11446. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11447. auto host = "httpbingo.org";
  11448. auto path = std::string{"/range/32"};
  11449. #ifdef CPPHTTPLIB_SSL_ENABLED
  11450. SSLClient cli(host);
  11451. #else
  11452. Client cli(host);
  11453. #endif
  11454. cli.set_default_headers({make_range_header({{1, 10}})});
  11455. cli.set_connection_timeout(5);
  11456. {
  11457. auto res = cli.Get(path);
  11458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11459. EXPECT_EQ("bcdefghijk", res->body);
  11460. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11461. }
  11462. {
  11463. auto res = cli.Get(path);
  11464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11465. EXPECT_EQ("bcdefghijk", res->body);
  11466. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11467. }
  11468. }
  11469. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11470. Server svr;
  11471. svr.set_default_headers({{"Hello", "World"}});
  11472. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11473. res.set_content("ok", "text/plain");
  11474. });
  11475. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11476. auto se = detail::scope_exit([&] {
  11477. svr.stop();
  11478. listen_thread.join();
  11479. ASSERT_FALSE(svr.is_running());
  11480. });
  11481. svr.wait_until_ready();
  11482. Client cli("localhost", PORT);
  11483. auto res = cli.Get("/");
  11484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11485. EXPECT_EQ(StatusCode::OK_200, res->status);
  11486. EXPECT_EQ("ok", res->body);
  11487. EXPECT_EQ("World", res->get_header_value("Hello"));
  11488. }
  11489. #ifdef CPPHTTPLIB_SSL_ENABLED
  11490. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11491. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11492. ASSERT_TRUE(svr.is_valid());
  11493. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11494. std::this_thread::sleep_for(std::chrono::seconds(2));
  11495. res.set_content("a", "text/plain");
  11496. });
  11497. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11498. res.set_content("b", "text/plain");
  11499. });
  11500. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11501. auto se = detail::scope_exit([&] {
  11502. svr.stop();
  11503. listen_thread.join();
  11504. ASSERT_FALSE(svr.is_running());
  11505. });
  11506. svr.wait_until_ready();
  11507. SSLClient cli("localhost", PORT);
  11508. cli.enable_server_certificate_verification(false);
  11509. cli.set_keep_alive(true);
  11510. cli.set_read_timeout(std::chrono::seconds(1));
  11511. auto resa = cli.Get("/a");
  11512. ASSERT_TRUE(!resa);
  11513. EXPECT_EQ(Error::Read, resa.error());
  11514. auto resb = cli.Get("/b");
  11515. ASSERT_TRUE(resb);
  11516. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11517. EXPECT_EQ("b", resb->body);
  11518. }
  11519. // Closing an idle keep-alive connection sends close_notify and returns. The
  11520. // server must not wait for the client's close_notify: an idle client never
  11521. // sends one, so the worker would be held until the read timeout expires, and
  11522. // stop() would wait for it.
  11523. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11524. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11525. ASSERT_TRUE(svr.is_valid());
  11526. svr.set_keep_alive_timeout(1);
  11527. svr.set_read_timeout(10, 0);
  11528. svr.Get("/", [](const Request &, Response &res) {
  11529. res.set_content("ok", "text/plain");
  11530. });
  11531. auto port = svr.bind_to_any_port(HOST);
  11532. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11533. auto se = detail::scope_exit([&] {
  11534. if (listen_thread.joinable()) {
  11535. svr.stop();
  11536. listen_thread.join();
  11537. }
  11538. });
  11539. svr.wait_until_ready();
  11540. SSLClient cli(HOST, port);
  11541. cli.enable_server_certificate_verification(false);
  11542. cli.set_keep_alive(true);
  11543. auto res = cli.Get("/");
  11544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11545. EXPECT_EQ(StatusCode::OK_200, res->status);
  11546. // Stay idle past the keep-alive timeout so the server closes the connection.
  11547. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11548. auto start = std::chrono::steady_clock::now();
  11549. svr.stop();
  11550. listen_thread.join();
  11551. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11552. std::chrono::steady_clock::now() - start)
  11553. .count();
  11554. EXPECT_LT(elapsed, 3000);
  11555. }
  11556. #endif
  11557. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11558. protected:
  11559. ServerTestWithAI_PASSIVE()
  11560. : cli_(HOST, PORT)
  11561. #ifdef CPPHTTPLIB_SSL_ENABLED
  11562. ,
  11563. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11564. #endif
  11565. {
  11566. #ifdef CPPHTTPLIB_SSL_ENABLED
  11567. cli_.enable_server_certificate_verification(false);
  11568. #endif
  11569. }
  11570. virtual void SetUp() {
  11571. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11572. res.set_content("Hello World!", "text/plain");
  11573. });
  11574. t_ = thread(
  11575. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11576. svr_.wait_until_ready();
  11577. }
  11578. virtual void TearDown() {
  11579. svr_.stop();
  11580. t_.join();
  11581. }
  11582. #ifdef CPPHTTPLIB_SSL_ENABLED
  11583. SSLClient cli_;
  11584. SSLServer svr_;
  11585. #else
  11586. Client cli_;
  11587. Server svr_;
  11588. #endif
  11589. thread t_;
  11590. };
  11591. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11592. auto res = cli_.Get("/hi");
  11593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11594. EXPECT_EQ(StatusCode::OK_200, res->status);
  11595. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11596. EXPECT_EQ("Hello World!", res->body);
  11597. }
  11598. class ServerUpDownTest : public ::testing::Test {
  11599. protected:
  11600. ServerUpDownTest() : cli_(HOST, PORT) {}
  11601. virtual void SetUp() {
  11602. t_ = thread([&]() {
  11603. svr_.bind_to_any_port(HOST);
  11604. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11605. ASSERT_TRUE(svr_.listen_after_bind());
  11606. });
  11607. svr_.wait_until_ready();
  11608. }
  11609. virtual void TearDown() {
  11610. svr_.stop();
  11611. t_.join();
  11612. }
  11613. Client cli_;
  11614. Server svr_;
  11615. thread t_;
  11616. };
  11617. TEST_F(ServerUpDownTest, QuickStartStop) {
  11618. // Should not crash, especially when run with
  11619. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11620. }
  11621. class PayloadMaxLengthTest : public ::testing::Test {
  11622. protected:
  11623. PayloadMaxLengthTest()
  11624. : cli_(HOST, PORT)
  11625. #ifdef CPPHTTPLIB_SSL_ENABLED
  11626. ,
  11627. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11628. #endif
  11629. {
  11630. #ifdef CPPHTTPLIB_SSL_ENABLED
  11631. cli_.enable_server_certificate_verification(false);
  11632. #endif
  11633. }
  11634. virtual void SetUp() {
  11635. svr_.set_payload_max_length(8);
  11636. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11637. res.set_content("test", "text/plain");
  11638. });
  11639. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11640. svr_.wait_until_ready();
  11641. }
  11642. virtual void TearDown() {
  11643. svr_.stop();
  11644. t_.join();
  11645. }
  11646. #ifdef CPPHTTPLIB_SSL_ENABLED
  11647. SSLClient cli_;
  11648. SSLServer svr_;
  11649. #else
  11650. Client cli_;
  11651. Server svr_;
  11652. #endif
  11653. thread t_;
  11654. };
  11655. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11656. auto res = cli_.Post("/test", "123456789", "text/plain");
  11657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11658. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11659. res = cli_.Post("/test", "12345678", "text/plain");
  11660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11661. EXPECT_EQ(StatusCode::OK_200, res->status);
  11662. }
  11663. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11664. // Test chunked encoding with payload exceeding the 8-byte limit
  11665. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11666. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11668. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11669. }
  11670. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11671. // Test chunked encoding with payload within the 8-byte limit
  11672. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11673. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11675. EXPECT_EQ(StatusCode::OK_200, res->status);
  11676. }
  11677. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11678. // Test using send_request to send chunked data exceeding payload limit
  11679. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11680. "Host: " +
  11681. std::string(HOST) + ":" + std::to_string(PORT) +
  11682. "\r\n"
  11683. "Transfer-Encoding: chunked\r\n"
  11684. "Connection: close\r\n"
  11685. "\r\n"
  11686. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11687. "0123456789\r\n"
  11688. "0\r\n" // End chunk
  11689. "\r\n";
  11690. std::string response;
  11691. bool result = send_request(1, chunked_request, &response);
  11692. if (!result) {
  11693. // If send_request fails, it might be because the server closed the
  11694. // connection due to payload limit enforcement, which is acceptable
  11695. SUCCEED()
  11696. << "Server rejected oversized chunked request (connection closed)";
  11697. } else {
  11698. // If we got a response, check if it's an error response or connection was
  11699. // closed early Short response length indicates connection was closed due to
  11700. // payload limit
  11701. if (response.length() <= 10) {
  11702. SUCCEED() << "Server closed connection for oversized chunked request";
  11703. } else {
  11704. // Check for error status codes
  11705. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11706. response.find("Payload Too Large") != std::string::npos ||
  11707. response.find("400") != std::string::npos);
  11708. }
  11709. }
  11710. }
  11711. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11712. // Test request without Content-Length header exceeding payload limit
  11713. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11714. "Host: " +
  11715. std::string(HOST) + ":" +
  11716. std::to_string(PORT) +
  11717. "\r\n"
  11718. "Connection: close\r\n"
  11719. "\r\n";
  11720. // Add payload exceeding the 8-byte limit
  11721. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11722. request_without_content_length += large_payload;
  11723. std::string response;
  11724. bool result = send_request(1, request_without_content_length, &response);
  11725. if (!result) {
  11726. // If send_request fails, server likely closed connection due to payload
  11727. // limit
  11728. SUCCEED() << "Server rejected oversized request without Content-Length "
  11729. "(connection closed)";
  11730. } else {
  11731. // Check if server responded with error or closed connection early
  11732. if (response.length() <= 10) {
  11733. SUCCEED() << "Server closed connection for oversized request without "
  11734. "Content-Length";
  11735. } else {
  11736. // Check for error status codes
  11737. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11738. response.find("Payload Too Large") != std::string::npos ||
  11739. response.find("400") != std::string::npos);
  11740. }
  11741. }
  11742. }
  11743. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11744. // Test request without Content-Length header within payload limit
  11745. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11746. "Host: " +
  11747. std::string(HOST) + ":" +
  11748. std::to_string(PORT) +
  11749. "\r\n"
  11750. "Connection: close\r\n"
  11751. "\r\n";
  11752. // Add payload within the 8-byte limit
  11753. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11754. request_without_content_length += small_payload;
  11755. std::string response;
  11756. bool result = send_request(1, request_without_content_length, &response);
  11757. // For requests without Content-Length, the server may have different behavior
  11758. // The key is that it should not reject due to payload limit for small
  11759. // payloads
  11760. if (result) {
  11761. // Check for any HTTP response (success or error, but not connection closed)
  11762. if (response.length() > 10) {
  11763. SUCCEED()
  11764. << "Server processed request without Content-Length within limit";
  11765. } else {
  11766. // Short response might indicate connection closed, which is acceptable
  11767. SUCCEED() << "Server closed connection for request without "
  11768. "Content-Length (acceptable behavior)";
  11769. }
  11770. } else {
  11771. // Connection failure might be due to protocol requirements
  11772. SUCCEED() << "Connection issue with request without Content-Length "
  11773. "(environment-specific)";
  11774. }
  11775. }
  11776. class LargePayloadMaxLengthTest : public ::testing::Test {
  11777. protected:
  11778. LargePayloadMaxLengthTest()
  11779. : cli_(HOST, PORT)
  11780. #ifdef CPPHTTPLIB_SSL_ENABLED
  11781. ,
  11782. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11783. #endif
  11784. {
  11785. #ifdef CPPHTTPLIB_SSL_ENABLED
  11786. cli_.enable_server_certificate_verification(false);
  11787. #endif
  11788. }
  11789. virtual void SetUp() {
  11790. // Set 10MB payload limit
  11791. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11792. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11793. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11794. res.set_content("Large payload test", "text/plain");
  11795. });
  11796. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11797. svr_.wait_until_ready();
  11798. }
  11799. virtual void TearDown() {
  11800. svr_.stop();
  11801. t_.join();
  11802. }
  11803. #ifdef CPPHTTPLIB_SSL_ENABLED
  11804. SSLClient cli_;
  11805. SSLServer svr_;
  11806. #else
  11807. Client cli_;
  11808. Server svr_;
  11809. #endif
  11810. thread t_;
  11811. };
  11812. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11813. // Test chunked encoding with payload within 10MB limit
  11814. std::string medium_payload(5 * 1024 * 1024,
  11815. 'A'); // 5MB payload, within 10MB limit
  11816. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11818. EXPECT_EQ(StatusCode::OK_200, res->status);
  11819. }
  11820. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11821. // Test chunked encoding with payload exceeding 10MB limit
  11822. std::string large_payload(12 * 1024 * 1024,
  11823. 'B'); // 12MB payload, exceeds 10MB limit
  11824. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11825. // Server may either return 413 or close the connection
  11826. if (res) {
  11827. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11828. } else {
  11829. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11830. }
  11831. }
  11832. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11833. // Test request without Content-Length header within 10MB limit
  11834. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11835. "Host: " +
  11836. std::string(HOST) + ":" +
  11837. std::to_string(PORT) +
  11838. "\r\n"
  11839. "Connection: close\r\n"
  11840. "\r\n";
  11841. // Add 1MB payload (within 10MB limit)
  11842. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11843. request_without_content_length += medium_payload;
  11844. std::string response;
  11845. bool result = send_request(5, request_without_content_length, &response);
  11846. if (result) {
  11847. // Should get a proper HTTP response for payloads within limit
  11848. if (response.length() > 10) {
  11849. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11850. "10MB limit";
  11851. } else {
  11852. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11853. "Content-Length)";
  11854. }
  11855. } else {
  11856. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11857. }
  11858. }
  11859. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11860. // Test request without Content-Length header exceeding 10MB limit
  11861. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11862. "Host: " +
  11863. std::string(HOST) + ":" +
  11864. std::to_string(PORT) +
  11865. "\r\n"
  11866. "Connection: close\r\n"
  11867. "\r\n";
  11868. // Add 12MB payload (exceeds 10MB limit)
  11869. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11870. request_without_content_length += large_payload;
  11871. std::string response;
  11872. bool result = send_request(10, request_without_content_length, &response);
  11873. if (!result) {
  11874. // Server should close connection due to payload limit
  11875. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11876. "(connection closed)";
  11877. } else {
  11878. // Check for error response
  11879. if (response.length() <= 10) {
  11880. SUCCEED()
  11881. << "Server closed connection for 12MB request exceeding 10MB limit";
  11882. } else {
  11883. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11884. response.find("Payload Too Large") != std::string::npos ||
  11885. response.find("400") != std::string::npos);
  11886. }
  11887. }
  11888. }
  11889. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11890. Server svr;
  11891. svr.Get("/", [](const Request &, Response &res) {
  11892. // Claims far more than it sends, then drops the connection.
  11893. res.set_content_provider(size_t(1) << 41, "text/plain",
  11894. [](size_t, size_t, DataSink &sink) {
  11895. sink.write("abc", 3);
  11896. return false;
  11897. });
  11898. });
  11899. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11900. auto se = detail::scope_exit([&] {
  11901. svr.stop();
  11902. thread.join();
  11903. ASSERT_FALSE(svr.is_running());
  11904. });
  11905. svr.wait_until_ready();
  11906. Client cli(HOST, PORT);
  11907. cli.set_payload_max_length(0);
  11908. EXPECT_FALSE(cli.Get("/"));
  11909. }
  11910. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11911. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11912. // path.
  11913. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11914. Server svr;
  11915. const size_t LIMIT = 64 * 1024; // 64KB
  11916. svr.set_payload_max_length(LIMIT);
  11917. size_t total = 0;
  11918. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11919. const ContentReader &content_reader) {
  11920. content_reader([&](const char * /*data*/, size_t len) {
  11921. total += len;
  11922. return true;
  11923. });
  11924. res.status = 200;
  11925. res.set_content("stream_ok", "text/plain");
  11926. });
  11927. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11928. auto se = detail::scope_exit([&] {
  11929. svr.stop();
  11930. thread.join();
  11931. ASSERT_FALSE(svr.is_running());
  11932. });
  11933. svr.wait_until_ready();
  11934. // Prepare 256KB raw data and gzip-compress it
  11935. std::string raw(256 * 1024, 'A');
  11936. std::string gz;
  11937. {
  11938. z_stream zs{};
  11939. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11940. Z_DEFAULT_STRATEGY);
  11941. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11942. zs.avail_in = static_cast<uInt>(raw.size());
  11943. char outbuf[4096];
  11944. int ret;
  11945. do {
  11946. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11947. zs.avail_out = sizeof(outbuf);
  11948. ret = deflate(&zs, Z_FINISH);
  11949. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11950. } while (ret != Z_STREAM_END);
  11951. deflateEnd(&zs);
  11952. }
  11953. Client cli(HOST, PORT);
  11954. cli.set_connection_timeout(std::chrono::seconds(5));
  11955. Headers headers = {{"Content-Encoding", "gzip"}};
  11956. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11957. "application/octet-stream");
  11958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11959. // Server must reject oversized decompressed payloads with 413.
  11960. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11961. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11962. EXPECT_LE(total, LIMIT);
  11963. }
  11964. #ifndef CPPHTTPLIB_SSL_ENABLED
  11965. // For a request with neither Content-Length nor Transfer-Encoding, the
  11966. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11967. // compressed wire bytes straight to the ContentReader without ever routing
  11968. // them through the decompressor, so payload_max_length_ only bounded the
  11969. // compressed size on the wire, not the decompressed size.
  11970. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11971. Server svr;
  11972. const size_t LIMIT = 64 * 1024; // 64KB
  11973. svr.set_payload_max_length(LIMIT);
  11974. size_t total = 0;
  11975. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11976. const ContentReader &content_reader) {
  11977. content_reader([&](const char * /*data*/, size_t len) {
  11978. total += len;
  11979. return true;
  11980. });
  11981. res.status = 200;
  11982. res.set_content("stream_ok", "text/plain");
  11983. });
  11984. auto port = svr.bind_to_any_port(HOST);
  11985. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11986. auto se = detail::scope_exit([&] {
  11987. svr.stop();
  11988. thread.join();
  11989. ASSERT_FALSE(svr.is_running());
  11990. });
  11991. svr.wait_until_ready();
  11992. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11993. // StreamingGzipDecompression test above.
  11994. std::string raw(256 * 1024, 'A');
  11995. std::string gz;
  11996. {
  11997. httplib::detail::gzip_compressor compressor;
  11998. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11999. [&](const char *chunk, size_t len) {
  12000. gz.append(chunk, len);
  12001. return true;
  12002. });
  12003. ASSERT_TRUE(result);
  12004. }
  12005. // Send the gzip body over raw TCP with neither Content-Length nor
  12006. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12007. // kicks in.
  12008. std::string req = "POST /stream HTTP/1.1\r\n"
  12009. "Host: " +
  12010. std::string(HOST) + ":" + std::to_string(port) +
  12011. "\r\n"
  12012. "Content-Encoding: gzip\r\n"
  12013. "Connection: close\r\n"
  12014. "\r\n" +
  12015. gz;
  12016. std::string response;
  12017. ASSERT_TRUE(send_request(5, req, &response, port));
  12018. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12019. EXPECT_LE(total, LIMIT);
  12020. }
  12021. #endif
  12022. #endif
  12023. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12024. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12025. // the payload must be passed through untouched instead of being rejected.
  12026. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12027. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12028. Server svr;
  12029. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12030. res.set_content(body, "image/jpeg");
  12031. res.set_header("Content-Encoding", "UTF-8");
  12032. });
  12033. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12034. res.set_content(body, "image/jpeg");
  12035. res.set_header("Content-Encoding", "identity");
  12036. });
  12037. svr.Post("/echo", [](const Request &req, Response &res) {
  12038. res.set_content(req.body, "image/jpeg");
  12039. });
  12040. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12041. auto se = detail::scope_exit([&] {
  12042. svr.stop();
  12043. t.join();
  12044. ASSERT_FALSE(svr.is_running());
  12045. });
  12046. svr.wait_until_ready();
  12047. Client cli(HOST, PORT);
  12048. {
  12049. auto res = cli.Get("/image");
  12050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12051. EXPECT_EQ(StatusCode::OK_200, res->status);
  12052. EXPECT_EQ(body, res->body);
  12053. }
  12054. {
  12055. auto res = cli.Get("/identity");
  12056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12057. EXPECT_EQ(StatusCode::OK_200, res->status);
  12058. EXPECT_EQ(body, res->body);
  12059. }
  12060. {
  12061. // The same applies to a request body reaching the server.
  12062. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12063. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12065. EXPECT_EQ(StatusCode::OK_200, res->status);
  12066. EXPECT_EQ(body, res->body);
  12067. }
  12068. }
  12069. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12070. // gzip-encoded response even when the build has no zlib support.
  12071. static const char GZIPPED_HELLO_WORLD[] = {
  12072. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12073. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12074. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12075. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12076. // A content coding is a whole token, not something the field value merely
  12077. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12078. // as "fibre" look like Brotli, and turned a multi-coding value like
  12079. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12080. // it was never meant to see.
  12081. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12082. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12083. Server svr;
  12084. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12085. res.set_content(body, "image/jpeg");
  12086. res.set_header("Content-Encoding", "fibre");
  12087. });
  12088. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12089. res.set_content(body, "image/jpeg");
  12090. res.set_header("Content-Encoding", "gzip, br");
  12091. });
  12092. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12093. res.set_content(body, "image/jpeg");
  12094. res.set_header("Content-Encoding", "x-zstd-ish");
  12095. });
  12096. auto port = svr.bind_to_any_port(HOST);
  12097. thread t = thread([&]() { svr.listen_after_bind(); });
  12098. auto se = detail::scope_exit([&] {
  12099. svr.stop();
  12100. t.join();
  12101. ASSERT_FALSE(svr.is_running());
  12102. });
  12103. svr.wait_until_ready();
  12104. Client cli(HOST, port);
  12105. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12106. auto res = cli.Get(path);
  12107. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12108. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12109. // Not a coding we recognize, so the payload comes back untouched
  12110. EXPECT_EQ(body, res->body) << path;
  12111. }
  12112. }
  12113. // A content coding cpp-httplib recognizes but was not built with must be
  12114. // reported as such. Handing the still-compressed payload back to the caller
  12115. // would silently corrupt it.
  12116. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12117. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12118. Server svr;
  12119. // "image/jpeg" keeps the server from applying a content coding of its own,
  12120. // so the hand-crafted Content-Encoding below survives.
  12121. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12122. res.set_content(gzipped, "image/jpeg");
  12123. res.set_header("Content-Encoding", "gzip");
  12124. });
  12125. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12126. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12127. res.set_content(gzipped, "image/jpeg");
  12128. res.set_header("Content-Encoding", "GZIP");
  12129. });
  12130. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12131. auto se = detail::scope_exit([&] {
  12132. svr.stop();
  12133. t.join();
  12134. ASSERT_FALSE(svr.is_running());
  12135. });
  12136. svr.wait_until_ready();
  12137. Client cli(HOST, PORT);
  12138. {
  12139. auto res = cli.Get("/gzipped");
  12140. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12142. EXPECT_EQ("Hello World!", res->body);
  12143. #else
  12144. ASSERT_FALSE(res);
  12145. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12146. #endif
  12147. }
  12148. {
  12149. // open_stream() must behave the same way.
  12150. auto handle = cli.open_stream("GET", "/gzipped");
  12151. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12152. ASSERT_TRUE(handle.is_valid());
  12153. std::string received;
  12154. char buf[256];
  12155. ssize_t n;
  12156. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12157. received.append(buf, static_cast<size_t>(n));
  12158. }
  12159. EXPECT_EQ("Hello World!", received);
  12160. #else
  12161. EXPECT_FALSE(handle.is_valid());
  12162. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12163. #endif
  12164. }
  12165. {
  12166. // A differently-cased coding must not be mistaken for an unknown one, or
  12167. // the body would be handed back still compressed.
  12168. auto res = cli.Get("/gzipped-uppercase");
  12169. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12171. EXPECT_EQ("Hello World!", res->body);
  12172. #else
  12173. ASSERT_FALSE(res);
  12174. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12175. #endif
  12176. }
  12177. }
  12178. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12179. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12180. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12181. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12182. // body a second time and appending a second Content-Encoding field line, so
  12183. // clients that decode one coding per listed value handed back raw gzip bytes.
  12184. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12185. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12186. Server svr;
  12187. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12188. // keeps the server from applying a coding of its own.
  12189. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12190. res.set_content(gzipped, "text/plain");
  12191. res.set_header("Content-Encoding", "gzip");
  12192. });
  12193. auto port = svr.bind_to_any_port(HOST);
  12194. thread t = thread([&]() { svr.listen_after_bind(); });
  12195. auto se = detail::scope_exit([&] {
  12196. svr.stop();
  12197. t.join();
  12198. ASSERT_FALSE(svr.is_running());
  12199. });
  12200. svr.wait_until_ready();
  12201. Client cli(HOST, port);
  12202. Headers headers = {{"Accept-Encoding", "gzip"}};
  12203. auto res = cli.Get("/pre-gzipped", headers);
  12204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12205. EXPECT_EQ(StatusCode::OK_200, res->status);
  12206. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12207. EXPECT_EQ("Hello World!", res->body);
  12208. }
  12209. // A chunked provider settles its coding where the headers are written and
  12210. // reuses it at write time. Both ends of that have to hold: a handler's own
  12211. // Content-Encoding suppresses the coding, and a response without one is still
  12212. // compressed as it always was.
  12213. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12214. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12215. const std::string plain = "Hello World! Hello World! Hello World!";
  12216. Server svr;
  12217. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12218. res.set_header("Content-Encoding", "gzip");
  12219. res.set_chunked_content_provider(
  12220. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12221. sink.write(gzipped.data(), gzipped.size());
  12222. sink.done();
  12223. return true;
  12224. });
  12225. });
  12226. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12227. res.set_chunked_content_provider(
  12228. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12229. sink.write(plain.data(), plain.size());
  12230. sink.done();
  12231. return true;
  12232. });
  12233. });
  12234. auto port = svr.bind_to_any_port(HOST);
  12235. thread t = thread([&]() { svr.listen_after_bind(); });
  12236. auto se = detail::scope_exit([&] {
  12237. svr.stop();
  12238. t.join();
  12239. ASSERT_FALSE(svr.is_running());
  12240. });
  12241. svr.wait_until_ready();
  12242. Client cli(HOST, port);
  12243. Headers headers = {{"Accept-Encoding", "gzip"}};
  12244. {
  12245. auto res = cli.Get("/pre-gzipped", headers);
  12246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12247. EXPECT_EQ(StatusCode::OK_200, res->status);
  12248. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12249. EXPECT_EQ("Hello World!", res->body);
  12250. }
  12251. {
  12252. auto res = cli.Get("/negotiated", headers);
  12253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12254. EXPECT_EQ(StatusCode::OK_200, res->status);
  12255. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12256. EXPECT_EQ(plain, res->body);
  12257. }
  12258. }
  12259. #endif
  12260. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12261. // the same message as the comma-joined one, so both have to be read the same
  12262. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12263. // single gzip coding, and a body the sender says was encoded twice was handed
  12264. // back after one pass, still compressed but presented as decoded.
  12265. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12266. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12267. Server svr;
  12268. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12269. res.set_content(body, "image/jpeg");
  12270. res.headers.emplace("Content-Encoding", "gzip");
  12271. res.headers.emplace("Content-Encoding", "gzip");
  12272. });
  12273. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12274. res.set_content(body, "image/jpeg");
  12275. res.set_header("Content-Encoding", "gzip, gzip");
  12276. });
  12277. auto port = svr.bind_to_any_port(HOST);
  12278. thread t = thread([&]() { svr.listen_after_bind(); });
  12279. auto se = detail::scope_exit([&] {
  12280. svr.stop();
  12281. t.join();
  12282. ASSERT_FALSE(svr.is_running());
  12283. });
  12284. svr.wait_until_ready();
  12285. Client cli(HOST, port);
  12286. // Two codings is not something cpp-httplib decodes, so both representations
  12287. // take the pass-through path rather than one of them being gunzipped once.
  12288. for (const char *path : {"/split", "/joined"}) {
  12289. auto res = cli.Get(path);
  12290. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12291. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12292. EXPECT_EQ(body, res->body) << path;
  12293. }
  12294. }
  12295. // Regression test for DoS vulnerability: a malicious server sending a response
  12296. // without Content-Length header must not cause unbounded memory consumption on
  12297. // the client side. The client should stop reading after a reasonable limit,
  12298. // similar to the server-side set_payload_max_length protection.
  12299. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12300. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12301. #ifndef _WIN32
  12302. signal(SIGPIPE, SIG_IGN);
  12303. #endif
  12304. auto server_thread = std::thread([] {
  12305. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12306. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12307. default_socket_options(srv);
  12308. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12309. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12310. sockaddr_in addr{};
  12311. addr.sin_family = AF_INET;
  12312. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12313. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12314. int opt = 1;
  12315. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12316. #ifdef _WIN32
  12317. reinterpret_cast<const char *>(&opt),
  12318. #else
  12319. &opt,
  12320. #endif
  12321. sizeof(opt));
  12322. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12323. ::listen(srv, 1);
  12324. sockaddr_in cli_addr{};
  12325. socklen_t cli_len = sizeof(cli_addr);
  12326. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12327. if (cli != INVALID_SOCKET) {
  12328. char buf[4096];
  12329. ::recv(cli, buf, sizeof(buf), 0);
  12330. // Malicious response: no Content-Length, no chunked encoding
  12331. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12332. "Connection: close\r\n"
  12333. "\r\n";
  12334. ::send(cli,
  12335. #ifdef _WIN32
  12336. static_cast<const char *>(response_header.c_str()),
  12337. static_cast<int>(response_header.size()),
  12338. #else
  12339. response_header.c_str(), response_header.size(),
  12340. #endif
  12341. 0);
  12342. // Send 10MB of data
  12343. std::string chunk(64 * 1024, 'A');
  12344. size_t total_sent = 0;
  12345. while (total_sent < MALICIOUS_DATA_SIZE) {
  12346. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12347. auto sent = ::send(cli,
  12348. #ifdef _WIN32
  12349. static_cast<const char *>(chunk.c_str()),
  12350. static_cast<int>(to_send),
  12351. #else
  12352. chunk.c_str(), to_send,
  12353. #endif
  12354. 0);
  12355. if (sent <= 0) break;
  12356. total_sent += static_cast<size_t>(sent);
  12357. }
  12358. detail::close_socket(cli);
  12359. }
  12360. detail::close_socket(srv);
  12361. });
  12362. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12363. size_t total_read = 0;
  12364. {
  12365. Client cli("127.0.0.1", PORT + 2);
  12366. cli.set_read_timeout(5, 0);
  12367. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12368. auto stream = cli.open_stream("GET", "/malicious");
  12369. ASSERT_TRUE(stream.is_valid());
  12370. char buffer[64 * 1024];
  12371. ssize_t n;
  12372. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12373. total_read += static_cast<size_t>(n);
  12374. }
  12375. } // StreamHandle and Client destroyed here, closing the socket
  12376. server_thread.join();
  12377. // With set_payload_max_length, the client must stop reading before consuming
  12378. // all 10MB. The read loop should be cut off at or near the configured limit.
  12379. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12380. << "Client read " << total_read << " bytes, exceeding the configured "
  12381. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12382. }
  12383. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12384. // the entire response body without truncation.
  12385. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12386. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12387. #ifndef _WIN32
  12388. signal(SIGPIPE, SIG_IGN);
  12389. #endif
  12390. auto server_thread = std::thread([] {
  12391. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12392. default_socket_options(srv);
  12393. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12394. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12395. sockaddr_in addr{};
  12396. addr.sin_family = AF_INET;
  12397. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12398. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12399. int opt = 1;
  12400. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12401. #ifdef _WIN32
  12402. reinterpret_cast<const char *>(&opt),
  12403. #else
  12404. &opt,
  12405. #endif
  12406. sizeof(opt));
  12407. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12408. ::listen(srv, 1);
  12409. sockaddr_in cli_addr{};
  12410. socklen_t cli_len = sizeof(cli_addr);
  12411. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12412. if (cli != INVALID_SOCKET) {
  12413. char buf[4096];
  12414. ::recv(cli, buf, sizeof(buf), 0);
  12415. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12416. "Connection: close\r\n"
  12417. "\r\n";
  12418. ::send(cli,
  12419. #ifdef _WIN32
  12420. static_cast<const char *>(response_header.c_str()),
  12421. static_cast<int>(response_header.size()),
  12422. #else
  12423. response_header.c_str(), response_header.size(),
  12424. #endif
  12425. 0);
  12426. std::string chunk(64 * 1024, 'A');
  12427. size_t total_sent = 0;
  12428. while (total_sent < DATA_SIZE) {
  12429. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12430. auto sent = ::send(cli,
  12431. #ifdef _WIN32
  12432. static_cast<const char *>(chunk.c_str()),
  12433. static_cast<int>(to_send),
  12434. #else
  12435. chunk.c_str(), to_send,
  12436. #endif
  12437. 0);
  12438. if (sent <= 0) break;
  12439. total_sent += static_cast<size_t>(sent);
  12440. }
  12441. #ifdef _WIN32
  12442. ::shutdown(cli, SD_SEND);
  12443. #else
  12444. ::shutdown(cli, SHUT_WR);
  12445. #endif
  12446. // Drain until the client closes its end, ensuring all data is delivered
  12447. char drain[1024];
  12448. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12449. detail::close_socket(cli);
  12450. }
  12451. detail::close_socket(srv);
  12452. });
  12453. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12454. size_t total_read = 0;
  12455. {
  12456. Client cli("127.0.0.1", PORT + 2);
  12457. cli.set_read_timeout(5, 0);
  12458. cli.set_payload_max_length(0); // 0 means no limit
  12459. auto stream = cli.open_stream("GET", "/data");
  12460. ASSERT_TRUE(stream.is_valid());
  12461. char buffer[64 * 1024];
  12462. ssize_t n;
  12463. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12464. total_read += static_cast<size_t>(n);
  12465. }
  12466. }
  12467. server_thread.join();
  12468. EXPECT_EQ(total_read, DATA_SIZE)
  12469. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12470. << " bytes without truncation, but only read " << total_read << " bytes.";
  12471. }
  12472. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12473. // enormous Content-Length must not cause the client to pre-allocate a huge
  12474. // response body buffer. The reservation is capped at payload_max_length_, and
  12475. // the read itself fails when the body exceeds the limit.
  12476. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12477. #ifndef _WIN32
  12478. signal(SIGPIPE, SIG_IGN);
  12479. #endif
  12480. auto server_thread = std::thread([] {
  12481. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12482. default_socket_options(srv);
  12483. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12484. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12485. sockaddr_in addr{};
  12486. addr.sin_family = AF_INET;
  12487. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12488. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12489. int opt = 1;
  12490. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12491. #ifdef _WIN32
  12492. reinterpret_cast<const char *>(&opt),
  12493. #else
  12494. &opt,
  12495. #endif
  12496. sizeof(opt));
  12497. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12498. ::listen(srv, 1);
  12499. sockaddr_in cli_addr{};
  12500. socklen_t cli_len = sizeof(cli_addr);
  12501. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12502. if (cli != INVALID_SOCKET) {
  12503. char buf[4096];
  12504. ::recv(cli, buf, sizeof(buf), 0);
  12505. // Malicious response: claim a 20GB body but send only a tiny payload.
  12506. std::string response = "HTTP/1.1 200 OK\r\n"
  12507. "Content-Length: 20000000000\r\n"
  12508. "\r\n"
  12509. "abc";
  12510. ::send(cli,
  12511. #ifdef _WIN32
  12512. static_cast<const char *>(response.c_str()),
  12513. static_cast<int>(response.size()),
  12514. #else
  12515. response.c_str(), response.size(),
  12516. #endif
  12517. 0);
  12518. detail::close_socket(cli);
  12519. }
  12520. detail::close_socket(srv);
  12521. });
  12522. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12523. {
  12524. Client cli("127.0.0.1", PORT + 2);
  12525. cli.set_read_timeout(5, 0);
  12526. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12527. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12528. // (server claims more bytes than payload_max_length permits), but it must
  12529. // not exhaust memory before getting there.
  12530. auto res = cli.Get("/malicious");
  12531. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12532. }
  12533. server_thread.join();
  12534. }
  12535. // Verify that content_receiver bypasses the default payload_max_length,
  12536. // allowing streaming downloads larger than 100MB without requiring an explicit
  12537. // set_payload_max_length call.
  12538. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12539. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12540. #ifndef _WIN32
  12541. signal(SIGPIPE, SIG_IGN);
  12542. #endif
  12543. auto server_thread = std::thread([] {
  12544. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12545. default_socket_options(srv);
  12546. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12547. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12548. sockaddr_in addr{};
  12549. addr.sin_family = AF_INET;
  12550. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12551. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12552. int opt = 1;
  12553. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12554. #ifdef _WIN32
  12555. reinterpret_cast<const char *>(&opt),
  12556. #else
  12557. &opt,
  12558. #endif
  12559. sizeof(opt));
  12560. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12561. ::listen(srv, 1);
  12562. sockaddr_in cli_addr{};
  12563. socklen_t cli_len = sizeof(cli_addr);
  12564. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12565. if (cli != INVALID_SOCKET) {
  12566. char buf[4096];
  12567. ::recv(cli, buf, sizeof(buf), 0);
  12568. // Response with Content-Length larger than default 100MB limit
  12569. auto content_length = std::to_string(DATA_SIZE);
  12570. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12571. "Content-Length: " +
  12572. content_length +
  12573. "\r\n"
  12574. "Connection: close\r\n"
  12575. "\r\n";
  12576. ::send(cli,
  12577. #ifdef _WIN32
  12578. static_cast<const char *>(response_header.c_str()),
  12579. static_cast<int>(response_header.size()),
  12580. #else
  12581. response_header.c_str(), response_header.size(),
  12582. #endif
  12583. 0);
  12584. std::string chunk(64 * 1024, 'A');
  12585. size_t total_sent = 0;
  12586. while (total_sent < DATA_SIZE) {
  12587. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12588. auto sent = ::send(cli,
  12589. #ifdef _WIN32
  12590. static_cast<const char *>(chunk.c_str()),
  12591. static_cast<int>(to_send),
  12592. #else
  12593. chunk.c_str(), to_send,
  12594. #endif
  12595. 0);
  12596. if (sent <= 0) break;
  12597. total_sent += static_cast<size_t>(sent);
  12598. }
  12599. detail::close_socket(cli);
  12600. }
  12601. detail::close_socket(srv);
  12602. });
  12603. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12604. size_t total_received = 0;
  12605. {
  12606. Client cli("127.0.0.1", PORT + 2);
  12607. cli.set_read_timeout(10, 0);
  12608. // Do NOT call set_payload_max_length — use the default 100MB limit
  12609. auto res =
  12610. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12611. total_received += data_length;
  12612. return true;
  12613. });
  12614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12615. EXPECT_EQ(StatusCode::OK_200, res->status);
  12616. }
  12617. server_thread.join();
  12618. EXPECT_EQ(total_received, DATA_SIZE)
  12619. << "With content_receiver, the client should read all " << DATA_SIZE
  12620. << " bytes despite the default 100MB payload_max_length, but only read "
  12621. << total_received << " bytes.";
  12622. }
  12623. // Verify that an explicit set_payload_max_length smaller than the response is
  12624. // enforced even when a content_receiver is used.
  12625. TEST(ClientVulnerabilityTest,
  12626. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12627. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12628. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12629. #ifndef _WIN32
  12630. signal(SIGPIPE, SIG_IGN);
  12631. #endif
  12632. auto server_thread = std::thread([] {
  12633. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12634. default_socket_options(srv);
  12635. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12636. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12637. sockaddr_in addr{};
  12638. addr.sin_family = AF_INET;
  12639. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12640. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12641. int opt = 1;
  12642. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12643. #ifdef _WIN32
  12644. reinterpret_cast<const char *>(&opt),
  12645. #else
  12646. &opt,
  12647. #endif
  12648. sizeof(opt));
  12649. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12650. ::listen(srv, 1);
  12651. sockaddr_in cli_addr{};
  12652. socklen_t cli_len = sizeof(cli_addr);
  12653. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12654. if (cli != INVALID_SOCKET) {
  12655. char buf[4096];
  12656. ::recv(cli, buf, sizeof(buf), 0);
  12657. auto content_length = std::to_string(DATA_SIZE);
  12658. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12659. "Content-Length: " +
  12660. content_length +
  12661. "\r\n"
  12662. "Connection: close\r\n"
  12663. "\r\n";
  12664. ::send(cli,
  12665. #ifdef _WIN32
  12666. static_cast<const char *>(response_header.c_str()),
  12667. static_cast<int>(response_header.size()),
  12668. #else
  12669. response_header.c_str(), response_header.size(),
  12670. #endif
  12671. 0);
  12672. std::string chunk(64 * 1024, 'A');
  12673. size_t total_sent = 0;
  12674. while (total_sent < DATA_SIZE) {
  12675. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12676. auto sent = ::send(cli,
  12677. #ifdef _WIN32
  12678. static_cast<const char *>(chunk.c_str()),
  12679. static_cast<int>(to_send),
  12680. #else
  12681. chunk.c_str(), to_send,
  12682. #endif
  12683. 0);
  12684. if (sent <= 0) break;
  12685. total_sent += static_cast<size_t>(sent);
  12686. }
  12687. detail::close_socket(cli);
  12688. }
  12689. detail::close_socket(srv);
  12690. });
  12691. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12692. size_t total_received = 0;
  12693. {
  12694. Client cli("127.0.0.1", PORT + 2);
  12695. cli.set_read_timeout(10, 0);
  12696. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12697. auto res =
  12698. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12699. total_received += data_length;
  12700. return true;
  12701. });
  12702. // Should fail because 200MB exceeds the explicit 150MB limit
  12703. EXPECT_FALSE(res);
  12704. }
  12705. server_thread.join();
  12706. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12707. << "Client with content_receiver should respect the explicit "
  12708. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12709. << total_received << " bytes.";
  12710. }
  12711. // Verify that an explicit set_payload_max_length larger than the response
  12712. // allows the content_receiver to read all data successfully.
  12713. TEST(ClientVulnerabilityTest,
  12714. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12715. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12716. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12717. #ifndef _WIN32
  12718. signal(SIGPIPE, SIG_IGN);
  12719. #endif
  12720. auto server_thread = std::thread([] {
  12721. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12722. default_socket_options(srv);
  12723. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12724. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12725. sockaddr_in addr{};
  12726. addr.sin_family = AF_INET;
  12727. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12728. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12729. int opt = 1;
  12730. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12731. #ifdef _WIN32
  12732. reinterpret_cast<const char *>(&opt),
  12733. #else
  12734. &opt,
  12735. #endif
  12736. sizeof(opt));
  12737. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12738. ::listen(srv, 1);
  12739. sockaddr_in cli_addr{};
  12740. socklen_t cli_len = sizeof(cli_addr);
  12741. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12742. if (cli != INVALID_SOCKET) {
  12743. char buf[4096];
  12744. ::recv(cli, buf, sizeof(buf), 0);
  12745. auto content_length = std::to_string(DATA_SIZE);
  12746. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12747. "Content-Length: " +
  12748. content_length +
  12749. "\r\n"
  12750. "Connection: close\r\n"
  12751. "\r\n";
  12752. ::send(cli,
  12753. #ifdef _WIN32
  12754. static_cast<const char *>(response_header.c_str()),
  12755. static_cast<int>(response_header.size()),
  12756. #else
  12757. response_header.c_str(), response_header.size(),
  12758. #endif
  12759. 0);
  12760. std::string chunk(64 * 1024, 'A');
  12761. size_t total_sent = 0;
  12762. while (total_sent < DATA_SIZE) {
  12763. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12764. auto sent = ::send(cli,
  12765. #ifdef _WIN32
  12766. static_cast<const char *>(chunk.c_str()),
  12767. static_cast<int>(to_send),
  12768. #else
  12769. chunk.c_str(), to_send,
  12770. #endif
  12771. 0);
  12772. if (sent <= 0) break;
  12773. total_sent += static_cast<size_t>(sent);
  12774. }
  12775. #ifdef _WIN32
  12776. ::shutdown(cli, SD_SEND);
  12777. #else
  12778. ::shutdown(cli, SHUT_WR);
  12779. #endif
  12780. char drain[1024];
  12781. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12782. detail::close_socket(cli);
  12783. }
  12784. detail::close_socket(srv);
  12785. });
  12786. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12787. size_t total_received = 0;
  12788. {
  12789. Client cli("127.0.0.1", PORT + 2);
  12790. cli.set_read_timeout(10, 0);
  12791. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12792. auto res =
  12793. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12794. total_received += data_length;
  12795. return true;
  12796. });
  12797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12798. EXPECT_EQ(StatusCode::OK_200, res->status);
  12799. }
  12800. server_thread.join();
  12801. EXPECT_EQ(total_received, DATA_SIZE)
  12802. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12803. << " bytes (larger than " << DATA_SIZE
  12804. << " bytes response), content_receiver should read all data, but only "
  12805. "read "
  12806. << total_received << " bytes.";
  12807. }
  12808. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12809. // Regression test for "zip bomb" attack on the client side: a malicious server
  12810. // sends a small gzip-compressed response that decompresses to a huge payload.
  12811. // The client must enforce payload_max_length on the decompressed size.
  12812. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12813. constexpr size_t DECOMPRESSED_SIZE =
  12814. 10 * 1024 * 1024; // 10MB after decompression
  12815. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12816. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12817. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12818. std::string compressed;
  12819. {
  12820. httplib::detail::gzip_compressor compressor;
  12821. bool ok =
  12822. compressor.compress(uncompressed.data(), uncompressed.size(),
  12823. /*last=*/true, [&](const char *buf, size_t len) {
  12824. compressed.append(buf, len);
  12825. return true;
  12826. });
  12827. ASSERT_TRUE(ok);
  12828. }
  12829. // Sanity: compressed data should be much smaller than the decompressed size
  12830. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12831. #ifndef _WIN32
  12832. signal(SIGPIPE, SIG_IGN);
  12833. #endif
  12834. // Set up the listening socket in the main thread so the server is guaranteed
  12835. // to be ready before the client connects (eliminates race condition).
  12836. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12837. default_socket_options(srv);
  12838. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12839. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12840. sockaddr_in addr{};
  12841. addr.sin_family = AF_INET;
  12842. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12843. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12844. int opt = 1;
  12845. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12846. #ifdef _WIN32
  12847. reinterpret_cast<const char *>(&opt),
  12848. #else
  12849. &opt,
  12850. #endif
  12851. sizeof(opt));
  12852. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12853. ASSERT_EQ(0, ::listen(srv, 1));
  12854. auto server_thread = std::thread([&compressed, srv] {
  12855. sockaddr_in cli_addr{};
  12856. socklen_t cli_len = sizeof(cli_addr);
  12857. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12858. if (cli != INVALID_SOCKET) {
  12859. // Read the full HTTP request (until \r\n\r\n)
  12860. char buf[4096];
  12861. size_t total = 0;
  12862. while (total < sizeof(buf)) {
  12863. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12864. if (n <= 0) break;
  12865. total += static_cast<size_t>(n);
  12866. // Check for end of headers
  12867. if (total >= 4) {
  12868. std::string req(buf, total);
  12869. if (req.find("\r\n\r\n") != std::string::npos) break;
  12870. }
  12871. }
  12872. // Malicious response: gzip-compressed body, no Content-Length
  12873. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12874. "Content-Encoding: gzip\r\n"
  12875. "Connection: close\r\n"
  12876. "\r\n";
  12877. ::send(cli,
  12878. #ifdef _WIN32
  12879. static_cast<const char *>(response_header.c_str()),
  12880. static_cast<int>(response_header.size()),
  12881. #else
  12882. response_header.c_str(), response_header.size(),
  12883. #endif
  12884. 0);
  12885. // Send the compressed payload (small on the wire, huge when decompressed)
  12886. size_t total_sent = 0;
  12887. while (total_sent < compressed.size()) {
  12888. auto to_send = std::min(compressed.size() - total_sent,
  12889. static_cast<size_t>(64 * 1024));
  12890. auto sent =
  12891. ::send(cli,
  12892. #ifdef _WIN32
  12893. static_cast<const char *>(compressed.c_str() + total_sent),
  12894. static_cast<int>(to_send),
  12895. #else
  12896. compressed.c_str() + total_sent, to_send,
  12897. #endif
  12898. 0);
  12899. if (sent <= 0) break;
  12900. total_sent += static_cast<size_t>(sent);
  12901. }
  12902. detail::close_socket(cli);
  12903. }
  12904. });
  12905. auto se = detail::scope_exit([&] {
  12906. detail::close_socket(srv);
  12907. server_thread.join();
  12908. });
  12909. size_t total_decompressed = 0;
  12910. {
  12911. Client cli("127.0.0.1", PORT + 3);
  12912. cli.set_read_timeout(5, 0);
  12913. cli.set_decompress(true);
  12914. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12915. auto stream = cli.open_stream("GET", "/zipbomb");
  12916. ASSERT_TRUE(stream.is_valid());
  12917. char buffer[64 * 1024];
  12918. ssize_t n;
  12919. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12920. total_decompressed += static_cast<size_t>(n);
  12921. }
  12922. }
  12923. // The decompressed size must be capped by payload_max_length. Without
  12924. // protection, the client would decompress the full 10MB from a tiny
  12925. // compressed payload, enabling a zip bomb DoS attack.
  12926. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12927. << "Client decompressed " << total_decompressed
  12928. << " bytes from a gzip response. The decompressed size should be "
  12929. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12930. }
  12931. #endif
  12932. TEST(HostAndPortPropertiesTest, NoSSL) {
  12933. httplib::Client cli("www.google.com", 1234);
  12934. ASSERT_EQ("www.google.com", cli.host());
  12935. ASSERT_EQ(1234, cli.port());
  12936. }
  12937. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12938. httplib::Client cli("www.google.com:1234");
  12939. ASSERT_EQ("www.google.com", cli.host());
  12940. ASSERT_EQ(1234, cli.port());
  12941. }
  12942. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12943. // Port number that overflows int — should not crash, client becomes invalid
  12944. httplib::Client cli("http://www.google.com:99999999999999999999");
  12945. ASSERT_FALSE(cli.is_valid());
  12946. }
  12947. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12948. // Port 99999 exceeds valid range (1-65535) — should not crash
  12949. httplib::Client cli("http://www.google.com:99999");
  12950. ASSERT_FALSE(cli.is_valid());
  12951. auto res = cli.Get("/");
  12952. EXPECT_FALSE(res);
  12953. EXPECT_EQ(Error::Connection, res.error());
  12954. }
  12955. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  12956. httplib::Client cli("http://user:pass@localhost:1234");
  12957. ASSERT_FALSE(cli.is_valid());
  12958. EXPECT_FALSE(cli.Get("/"));
  12959. }
  12960. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12961. httplib::Client cli("http://www.google.com:80abc");
  12962. ASSERT_FALSE(cli.is_valid());
  12963. }
  12964. #ifdef CPPHTTPLIB_SSL_ENABLED
  12965. TEST(HostAndPortPropertiesTest, SSL) {
  12966. httplib::SSLClient cli("www.google.com");
  12967. ASSERT_EQ("www.google.com", cli.host());
  12968. ASSERT_EQ(443, cli.port());
  12969. }
  12970. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12971. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12972. std::string cert;
  12973. read_file(CA_CERT_FILE, cert);
  12974. httplib::SSLClient httplib_client("www.google.com");
  12975. // Load CA store first time
  12976. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12977. // Load CA store second time (update)
  12978. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12979. // Verify client is still valid and can make connections
  12980. httplib_client.enable_server_certificate_verification(true);
  12981. auto res = httplib_client.Get("/");
  12982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12983. // Google may return 200 or 301 depending on various factors
  12984. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12985. res->status == StatusCode::MovedPermanently_301);
  12986. }
  12987. TEST(SSLClientTest, ServerNameIndication_Online) {
  12988. auto host = "httpbingo.org";
  12989. auto path = std::string{"/get"};
  12990. SSLClient cli(host, 443);
  12991. auto res = cli.Get(path);
  12992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12993. ASSERT_EQ(StatusCode::OK_200, res->status);
  12994. }
  12995. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12996. // Use a site that will cause SSL verification failure due to self-signed cert
  12997. SSLClient cli("self-signed.badssl.com", 443);
  12998. cli.enable_server_certificate_verification(true);
  12999. auto res = cli.Get("/");
  13000. ASSERT_TRUE(!res);
  13001. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13002. // Verify backend error is captured for SSLServerVerification
  13003. // This occurs when certificate verification fails
  13004. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13005. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13006. EXPECT_NE(0UL, res.ssl_backend_error());
  13007. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13008. // For OpenSSL, ssl_error is 0 for verification errors
  13009. EXPECT_EQ(0, res.ssl_error());
  13010. #if !defined(_WIN32) || \
  13011. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13012. // On non-Windows or when Windows Schannel is disabled, the error comes
  13013. // from OpenSSL's verification
  13014. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13015. res.ssl_backend_error());
  13016. #endif
  13017. #endif
  13018. }
  13019. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13020. // Use a site where hostname doesn't match the certificate
  13021. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13022. SSLClient cli("wrong.host.badssl.com", 443);
  13023. cli.enable_server_certificate_verification(true);
  13024. cli.enable_server_hostname_verification(true);
  13025. auto res = cli.Get("/");
  13026. ASSERT_TRUE(!res);
  13027. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13028. // Verify backend error is captured for hostname verification failure
  13029. EXPECT_NE(0UL, res.ssl_backend_error());
  13030. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13031. // For OpenSSL, ssl_error is 0 for verification errors
  13032. EXPECT_EQ(0, res.ssl_error());
  13033. #if !defined(_WIN32) || \
  13034. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13035. // On non-Windows or when Windows Schannel is disabled, the error comes
  13036. // from OpenSSL's hostname verification
  13037. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13038. res.ssl_backend_error());
  13039. #endif
  13040. #endif
  13041. }
  13042. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13043. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13044. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13045. SSLClient cli("www.google.com", 443);
  13046. cli.enable_server_certificate_verification(true);
  13047. auto res = cli.Get("/");
  13048. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13049. }
  13050. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13051. SSLClient cli("www.google.com", 443);
  13052. cli.enable_server_certificate_verification(true);
  13053. cli.enable_windows_certificate_verification(false);
  13054. auto res = cli.Get("/");
  13055. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13056. }
  13057. // The server sends an intermediate cross-signed by a root Windows trusts,
  13058. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13059. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13060. SSLClient cli("accounts.spotify.com", 443);
  13061. auto res = cli.Get("/");
  13062. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13063. << " ssl_backend_error=" << res.ssl_backend_error();
  13064. }
  13065. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13066. // policy status, which no backend reports for a self-signed certificate.
  13067. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13068. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13069. ASSERT_TRUE(svr.is_valid());
  13070. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13071. auto se = detail::scope_exit([&] {
  13072. svr.stop();
  13073. t.join();
  13074. ASSERT_FALSE(svr.is_running());
  13075. });
  13076. svr.wait_until_ready();
  13077. SSLClient cli("127.0.0.1", PORT);
  13078. cli.set_connection_timeout(30);
  13079. auto res = cli.Get("/");
  13080. ASSERT_FALSE(res);
  13081. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13082. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13083. }
  13084. #endif
  13085. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13086. Client cli("https://google.com");
  13087. auto res = cli.Get("/");
  13088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13089. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13090. }
  13091. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13092. SSLClient cli("google.com");
  13093. cli.set_ca_cert_path(CA_CERT_FILE);
  13094. auto res = cli.Get("/");
  13095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13096. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13097. }
  13098. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13099. SSLClient cli("google.com");
  13100. cli.enable_server_certificate_verification(true);
  13101. cli.set_ca_cert_path("hello");
  13102. auto res = cli.Get("/");
  13103. ASSERT_TRUE(!res);
  13104. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13105. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13106. // should be set
  13107. EXPECT_EQ(0, res.ssl_error());
  13108. // Verify backend error is captured for SSLLoadingCerts
  13109. // This error occurs when loading CA certificates fails
  13110. EXPECT_NE(0UL, res.ssl_backend_error());
  13111. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13112. // OpenSSL specific error codes:
  13113. // > openssl errstr 0x80000002
  13114. // error:80000002:system library::No such file or directory
  13115. // > openssl errstr 0xA000126
  13116. // error:0A000126:SSL routines::unexpected eof while reading
  13117. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13118. res.ssl_backend_error() == 0xA000126);
  13119. #endif
  13120. }
  13121. TEST(SSLClientTest, ServerCertificateVerification4) {
  13122. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13123. ASSERT_TRUE(svr.is_valid());
  13124. svr.Get("/test", [&](const Request &, Response &res) {
  13125. res.set_content("test", "text/plain");
  13126. svr.stop();
  13127. ASSERT_TRUE(true);
  13128. });
  13129. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13130. auto se = detail::scope_exit([&] {
  13131. t.join();
  13132. ASSERT_FALSE(svr.is_running());
  13133. });
  13134. svr.wait_until_ready();
  13135. SSLClient cli("127.0.0.1", PORT);
  13136. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13137. cli.enable_server_certificate_verification(true);
  13138. cli.set_connection_timeout(30);
  13139. auto res = cli.Get("/test");
  13140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13141. ASSERT_EQ(StatusCode::OK_200, res->status);
  13142. }
  13143. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13144. std::string cert;
  13145. read_file(CA_CERT_FILE, cert);
  13146. SSLClient cli("google.com");
  13147. cli.load_ca_cert_store(cert.data(), cert.size());
  13148. const auto res = cli.Get("/");
  13149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13150. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13151. }
  13152. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13153. // clang-format off
  13154. static constexpr char cert[] =
  13155. "GlobalSign Root CA\n"
  13156. "==================\n"
  13157. "-----BEGIN CERTIFICATE-----\n"
  13158. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13159. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13160. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13161. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13162. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13163. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13164. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13165. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13166. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13167. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13168. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13169. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13170. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13171. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13172. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13173. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13174. "-----END CERTIFICATE-----\n";
  13175. // clang-format on
  13176. SSLClient cli("google.com");
  13177. cli.load_ca_cert_store(cert, sizeof(cert));
  13178. const auto res = cli.Get("/");
  13179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13180. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13181. }
  13182. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13183. SSLClient cli("www.youtube.com");
  13184. cli.set_ca_cert_path(CA_CERT_FILE);
  13185. cli.enable_server_certificate_verification(true);
  13186. cli.set_follow_location(true);
  13187. auto res = cli.Get("/");
  13188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13189. ASSERT_EQ(StatusCode::OK_200, res->status);
  13190. }
  13191. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13192. SSLClient cli("wWw.YouTube.Com");
  13193. cli.set_ca_cert_path(CA_CERT_FILE);
  13194. cli.enable_server_certificate_verification(true);
  13195. cli.enable_server_hostname_verification(true);
  13196. cli.set_follow_location(true);
  13197. auto res = cli.Get("/");
  13198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13199. ASSERT_EQ(StatusCode::OK_200, res->status);
  13200. }
  13201. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13202. SSLClient cli("gOoGlE.COm");
  13203. cli.enable_server_certificate_verification(true);
  13204. cli.enable_server_hostname_verification(true);
  13205. cli.set_follow_location(true);
  13206. auto res = cli.Get("/");
  13207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13208. ASSERT_EQ(StatusCode::OK_200, res->status);
  13209. }
  13210. TEST(SSLClientTest, Issue2004_Online) {
  13211. Client client("https://google.com");
  13212. client.set_follow_location(true);
  13213. auto res = client.Get("/");
  13214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13215. ASSERT_EQ(StatusCode::OK_200, res->status);
  13216. auto body = res->body;
  13217. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13218. }
  13219. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13220. // Create SSLClient with invalid cert/key to make is_valid() return false
  13221. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13222. "nonexistent_key.pem");
  13223. // is_valid() should be false due to cert loading failure
  13224. ASSERT_FALSE(cli.is_valid());
  13225. auto res = cli.Get("/");
  13226. ASSERT_FALSE(res);
  13227. EXPECT_EQ(Error::SSLConnection, res.error());
  13228. }
  13229. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13230. // Test for Issue #2251: SSL error not properly reported when client cert
  13231. // and key paths are swapped or mismatched
  13232. // This simulates the scenario where user accidentally swaps the cert and key
  13233. // files
  13234. // Using client cert file as private key and vice versa (completely wrong)
  13235. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13236. // Should fail validation due to cert/key mismatch
  13237. ASSERT_FALSE(cli.is_valid());
  13238. // Attempt to make a request should fail with proper error
  13239. auto res = cli.Get("/");
  13240. ASSERT_FALSE(res);
  13241. EXPECT_EQ(Error::SSLConnection, res.error());
  13242. // SSL error should be recorded in the Result object (this is the key fix for
  13243. // Issue #2251)
  13244. auto backend_error = res.ssl_backend_error();
  13245. EXPECT_NE(0u, backend_error);
  13246. }
  13247. // Tests cert/key mismatch detection at the TLS context level
  13248. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13249. // Test that using mismatched cert/key causes connection failure.
  13250. // We verify this at the SSLClient level rather than through internal
  13251. // TLS API functions.
  13252. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13253. cli.enable_server_certificate_verification(false);
  13254. cli.set_connection_timeout(2);
  13255. // The mismatch should cause a connection or handshake error
  13256. auto res = cli.Get("/test");
  13257. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13258. // Either way, the request should fail
  13259. EXPECT_FALSE(res);
  13260. }
  13261. #endif
  13262. #if 0
  13263. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13264. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13265. ASSERT_TRUE(cli != nullptr);
  13266. cli->set_address_family(AF_INET6);
  13267. cli->set_interface("en0");
  13268. auto res = cli->Get("/get");
  13269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13270. ASSERT_EQ(StatusCode::OK_200, res->status);
  13271. }
  13272. #endif
  13273. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  13274. #ifdef CPPHTTPLIB_SSL_ENABLED
  13275. void ClientCertPresent(
  13276. const std::string &client_cert_file,
  13277. const std::string &client_private_key_file,
  13278. const std::string &client_encrypted_private_key_pass = std::string()) {
  13279. using namespace httplib::tls;
  13280. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13281. CLIENT_CA_CERT_DIR);
  13282. ASSERT_TRUE(svr.is_valid());
  13283. svr.Get("/test", [&](const Request &req, Response &res) {
  13284. res.set_content("test", "text/plain");
  13285. auto cert = req.peer_cert();
  13286. ASSERT_TRUE(static_cast<bool>(cert));
  13287. std::string common_name = cert.subject_cn();
  13288. EXPECT_EQ("Common Name", common_name);
  13289. });
  13290. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13291. auto se = detail::scope_exit([&] {
  13292. svr.stop();
  13293. t.join();
  13294. ASSERT_FALSE(svr.is_running());
  13295. });
  13296. svr.wait_until_ready();
  13297. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13298. client_encrypted_private_key_pass);
  13299. cli.enable_server_certificate_verification(false);
  13300. cli.set_connection_timeout(30);
  13301. auto res = cli.Get("/test");
  13302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13303. ASSERT_EQ(StatusCode::OK_200, res->status);
  13304. }
  13305. TEST(SSLClientServerTest, ClientCertPresent) {
  13306. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13307. }
  13308. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13309. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13310. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13311. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13312. }
  13313. // PEM memory-based constructor tests (works with all TLS backends)
  13314. void PemMemoryClientCertPresent(
  13315. const std::string &client_cert_file,
  13316. const std::string &client_private_key_file,
  13317. const std::string &client_encrypted_private_key_pass = std::string()) {
  13318. // Read PEM files into memory
  13319. std::string server_cert_pem, server_key_pem;
  13320. std::string client_ca_pem;
  13321. std::string client_cert_pem, client_key_pem;
  13322. read_file(SERVER_CERT_FILE, server_cert_pem);
  13323. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13324. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13325. read_file(client_cert_file, client_cert_pem);
  13326. read_file(client_private_key_file, client_key_pem);
  13327. // Create server with PEM memory
  13328. SSLServer::PemMemory server_pem = {
  13329. server_cert_pem.c_str(),
  13330. server_cert_pem.size(),
  13331. server_key_pem.c_str(),
  13332. server_key_pem.size(),
  13333. client_ca_pem.c_str(),
  13334. client_ca_pem.size(),
  13335. nullptr // no password for server key
  13336. };
  13337. SSLServer svr(server_pem);
  13338. ASSERT_TRUE(svr.is_valid());
  13339. svr.Get("/test", [&](const Request &, Response &res) {
  13340. res.set_content("test", "text/plain");
  13341. });
  13342. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13343. auto se = detail::scope_exit([&] {
  13344. svr.stop();
  13345. t.join();
  13346. ASSERT_FALSE(svr.is_running());
  13347. });
  13348. svr.wait_until_ready();
  13349. // Create client with PEM memory
  13350. const char *password = client_encrypted_private_key_pass.empty()
  13351. ? nullptr
  13352. : client_encrypted_private_key_pass.c_str();
  13353. SSLClient::PemMemory client_pem = {
  13354. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13355. client_key_pem.size(), password};
  13356. SSLClient cli(HOST, PORT, client_pem);
  13357. cli.enable_server_certificate_verification(false);
  13358. cli.set_connection_timeout(30);
  13359. auto res = cli.Get("/test");
  13360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13361. ASSERT_EQ(StatusCode::OK_200, res->status);
  13362. }
  13363. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13364. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13365. }
  13366. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13367. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13368. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13369. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13370. }
  13371. TEST(SSLClientServerTest, ClientCertMissing) {
  13372. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13373. CLIENT_CA_CERT_DIR);
  13374. ASSERT_TRUE(svr.is_valid());
  13375. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13376. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13377. auto se = detail::scope_exit([&] {
  13378. svr.stop();
  13379. t.join();
  13380. ASSERT_FALSE(svr.is_running());
  13381. });
  13382. svr.wait_until_ready();
  13383. SSLClient cli(HOST, PORT);
  13384. cli.set_connection_timeout(30);
  13385. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13386. // the chain check on Windows, so the result does not depend on the order.
  13387. cli.enable_server_hostname_verification(false);
  13388. auto res = cli.Get("/test");
  13389. ASSERT_TRUE(!res);
  13390. // When client cert is missing and server requires it, connection fails
  13391. // Error type depends on backend implementation
  13392. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13393. res.error() == Error::SSLConnection);
  13394. // Verify backend error is captured
  13395. // Note: This test may have different error codes depending on the exact
  13396. // verification failure
  13397. EXPECT_NE(0UL, res.ssl_backend_error());
  13398. }
  13399. TEST(SSLClientServerTest, TrustDirOptional) {
  13400. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13401. ASSERT_TRUE(svr.is_valid());
  13402. svr.Get("/test", [&](const Request &, Response &res) {
  13403. res.set_content("test", "text/plain");
  13404. });
  13405. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13406. auto se = detail::scope_exit([&] {
  13407. svr.stop();
  13408. t.join();
  13409. ASSERT_FALSE(svr.is_running());
  13410. });
  13411. svr.wait_until_ready();
  13412. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13413. cli.enable_server_certificate_verification(false);
  13414. cli.set_connection_timeout(30);
  13415. auto res = cli.Get("/test");
  13416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13417. ASSERT_EQ(StatusCode::OK_200, res->status);
  13418. }
  13419. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13420. class NoListenSSLServer : public SSLServer {
  13421. public:
  13422. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13423. const char *client_ca_cert_file_path,
  13424. const char *client_ca_cert_dir_path = nullptr)
  13425. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13426. client_ca_cert_dir_path),
  13427. stop_(false) {}
  13428. std::atomic_bool stop_;
  13429. private:
  13430. bool process_and_close_socket(socket_t /*sock*/) override {
  13431. // Don't create SSL context
  13432. while (!stop_.load()) {
  13433. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13434. }
  13435. return true;
  13436. }
  13437. };
  13438. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13439. CLIENT_CA_CERT_FILE);
  13440. ASSERT_TRUE(svr.is_valid());
  13441. svr.Get("/test", [&](const Request &, Response &res) {
  13442. res.set_content("test", "text/plain");
  13443. });
  13444. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13445. auto se = detail::scope_exit([&] {
  13446. svr.stop_ = true;
  13447. svr.stop();
  13448. t.join();
  13449. ASSERT_FALSE(svr.is_running());
  13450. });
  13451. svr.wait_until_ready();
  13452. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13453. cli.enable_server_certificate_verification(false);
  13454. cli.set_connection_timeout(1);
  13455. auto res = cli.Get("/test");
  13456. ASSERT_TRUE(!res);
  13457. EXPECT_EQ(Error::SSLConnection, res.error());
  13458. // Timeout results in WantRead error code (maps to backend-specific value)
  13459. EXPECT_NE(0, res.ssl_error());
  13460. }
  13461. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13462. // Test SSLServer with client certificate verification using the standard
  13463. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13464. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13465. CLIENT_CA_CERT_DIR);
  13466. ASSERT_TRUE(svr.is_valid());
  13467. svr.Get("/test", [&](const Request &req, Response &res) {
  13468. res.set_content("test", "text/plain");
  13469. auto cert = req.peer_cert();
  13470. ASSERT_TRUE(static_cast<bool>(cert));
  13471. auto common_name = cert.subject_cn();
  13472. EXPECT_EQ("Common Name", common_name);
  13473. });
  13474. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13475. auto se = detail::scope_exit([&] {
  13476. svr.stop();
  13477. t.join();
  13478. ASSERT_FALSE(svr.is_running());
  13479. });
  13480. svr.wait_until_ready();
  13481. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13482. cli.enable_server_certificate_verification(false);
  13483. cli.set_connection_timeout(30);
  13484. auto res = cli.Get("/test");
  13485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13486. ASSERT_EQ(StatusCode::OK_200, res->status);
  13487. }
  13488. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13489. // Verifies that wildcard matching and exact matching work consistently
  13490. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13491. using namespace httplib::tls;
  13492. // We need a running server to test against
  13493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13494. ASSERT_TRUE(svr.is_valid());
  13495. svr.Get("/test", [](const Request &, Response &res) {
  13496. res.set_content("ok", "text/plain");
  13497. });
  13498. thread t([&]() { svr.listen(HOST, PORT); });
  13499. auto se = detail::scope_exit([&] {
  13500. svr.stop();
  13501. t.join();
  13502. });
  13503. svr.wait_until_ready();
  13504. bool verify_callback_called = false;
  13505. bool verify_result_wrong = false;
  13506. SSLClient cli(HOST, PORT);
  13507. cli.enable_server_certificate_verification(true);
  13508. cli.set_ca_cert_path(CA_CERT_FILE);
  13509. cli.set_connection_timeout(5);
  13510. // Note: Test certificate has CN="Common Name", not "localhost"
  13511. bool verify_result_cn = false;
  13512. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13513. verify_callback_called = true;
  13514. if (!ctx.cert) return false;
  13515. // Test 1: "Common Name" should match (our test server cert CN)
  13516. verify_result_cn = ctx.check_hostname("Common Name");
  13517. // Test 2: wrong hostname should not match
  13518. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13519. return true; // Accept for the purpose of this test
  13520. });
  13521. auto res = cli.Get("/test");
  13522. // The request may succeed or fail depending on cert configuration
  13523. // but the callback should have been called
  13524. ASSERT_TRUE(verify_callback_called)
  13525. << "Verify callback should have been called";
  13526. // CN="Common Name" should match our test certificate
  13527. //
  13528. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13529. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13530. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13531. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13532. // <openssl/base.h>, which is included transitively when
  13533. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13534. #if defined(OPENSSL_IS_BORINGSSL)
  13535. EXPECT_FALSE(verify_result_cn)
  13536. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13537. #else
  13538. EXPECT_TRUE(verify_result_cn)
  13539. << "verify_hostname should match 'Common Name' (certificate CN)";
  13540. #endif
  13541. // Wrong hostname should not match
  13542. EXPECT_FALSE(verify_result_wrong)
  13543. << "verify_hostname should not match 'wronghost.example.com'";
  13544. }
  13545. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13546. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13547. // X509_check_ip behavior and must hold for every backend.
  13548. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13549. using namespace httplib::tls;
  13550. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13551. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13552. ASSERT_TRUE(svr.is_valid());
  13553. svr.Get("/test", [](const Request &, Response &res) {
  13554. res.set_content("ok", "text/plain");
  13555. });
  13556. thread t([&]() { svr.listen(HOST, PORT); });
  13557. auto se = detail::scope_exit([&] {
  13558. svr.stop();
  13559. t.join();
  13560. });
  13561. svr.wait_until_ready();
  13562. bool verify_callback_called = false;
  13563. bool ip_matched_via_cn = true;
  13564. SSLClient cli(HOST, PORT);
  13565. cli.enable_server_certificate_verification(true);
  13566. cli.set_ca_cert_path(CA_CERT_FILE);
  13567. cli.set_connection_timeout(5);
  13568. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13569. verify_callback_called = true;
  13570. if (!ctx.cert) return false;
  13571. // The IP appears only in the CN, so it must NOT be accepted.
  13572. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13573. return true; // Accept for the purpose of this test
  13574. });
  13575. cli.Get("/test");
  13576. ASSERT_TRUE(verify_callback_called)
  13577. << "Verify callback should have been called";
  13578. EXPECT_FALSE(ip_matched_via_cn)
  13579. << "An IP host must not be authenticated via the certificate CN";
  13580. }
  13581. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13582. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13583. using namespace httplib::tls;
  13584. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13585. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13586. ASSERT_TRUE(svr.is_valid());
  13587. svr.Get("/test", [](const Request &, Response &res) {
  13588. res.set_content("ok", "text/plain");
  13589. });
  13590. thread t([&]() { svr.listen(HOST, PORT); });
  13591. auto se = detail::scope_exit([&] {
  13592. svr.stop();
  13593. t.join();
  13594. });
  13595. svr.wait_until_ready();
  13596. bool verify_callback_called = false;
  13597. bool san_matched = false;
  13598. bool wrong_ipv6_matched = true;
  13599. bool cn_ipv6_matched = true;
  13600. SSLClient cli(HOST, PORT);
  13601. cli.enable_server_certificate_verification(true);
  13602. cli.set_ca_cert_path(CA_CERT_FILE);
  13603. cli.set_connection_timeout(5);
  13604. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13605. verify_callback_called = true;
  13606. if (!ctx.cert) return false;
  13607. // Matches the IPv6 iPAddress SAN.
  13608. san_matched = ctx.check_hostname("2001:db8::1");
  13609. // A different IPv6 address must not match.
  13610. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13611. // "::1" lives only in the CN, so it must not be accepted.
  13612. cn_ipv6_matched = ctx.check_hostname("::1");
  13613. return true; // Accept for the purpose of this test
  13614. });
  13615. cli.Get("/test");
  13616. ASSERT_TRUE(verify_callback_called)
  13617. << "Verify callback should have been called";
  13618. EXPECT_TRUE(san_matched)
  13619. << "verify_hostname should match an IPv6 iPAddress SAN";
  13620. EXPECT_FALSE(wrong_ipv6_matched)
  13621. << "verify_hostname should not match a non-matching IPv6 address";
  13622. EXPECT_FALSE(cn_ipv6_matched)
  13623. << "An IPv6 host must not be authenticated via the certificate CN";
  13624. }
  13625. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13626. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13627. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13628. using namespace httplib::tls;
  13629. // SANs: DNS:a.zz, IP:42.46.122.122
  13630. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13631. ASSERT_TRUE(svr.is_valid());
  13632. svr.Get("/test", [](const Request &, Response &res) {
  13633. res.set_content("ok", "text/plain");
  13634. });
  13635. auto port = svr.bind_to_any_port(HOST);
  13636. thread t([&]() { svr.listen_after_bind(); });
  13637. auto se = detail::scope_exit([&] {
  13638. svr.stop();
  13639. t.join();
  13640. });
  13641. svr.wait_until_ready();
  13642. bool verify_callback_called = false;
  13643. bool dns_san_matched = false;
  13644. bool ip_san_matched = false;
  13645. bool ip_matched_via_dns_san = true;
  13646. bool dns_matched_via_ip_san = true;
  13647. bool cn_matched_next_to_dns_san = true;
  13648. SSLClient cli(HOST, port);
  13649. cli.enable_server_certificate_verification(true);
  13650. cli.set_ca_cert_path(CA_CERT_FILE);
  13651. cli.set_connection_timeout(5);
  13652. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13653. verify_callback_called = true;
  13654. if (!ctx.cert) return false;
  13655. dns_san_matched = ctx.check_hostname("a.zz");
  13656. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13657. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13658. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13659. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  13660. return true; // Accept for the purpose of this test
  13661. });
  13662. cli.Get("/test");
  13663. ASSERT_TRUE(verify_callback_called)
  13664. << "Verify callback should have been called";
  13665. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13666. EXPECT_TRUE(ip_san_matched)
  13667. << "verify_hostname should match an iPAddress SAN";
  13668. EXPECT_FALSE(ip_matched_via_dns_san)
  13669. << "An IP host must not be authenticated via a dNSName SAN";
  13670. EXPECT_FALSE(dns_matched_via_ip_san)
  13671. << "A DNS host must not be authenticated via an iPAddress SAN";
  13672. EXPECT_FALSE(cn_matched_next_to_dns_san)
  13673. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  13674. }
  13675. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13676. // "www.*.example.test" names one host and not every host under example.test.
  13677. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13678. using namespace httplib::tls;
  13679. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13680. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13681. ASSERT_TRUE(svr.is_valid());
  13682. svr.Get("/test", [](const Request &, Response &res) {
  13683. res.set_content("ok", "text/plain");
  13684. });
  13685. auto port = svr.bind_to_any_port(HOST);
  13686. thread t([&]() { svr.listen_after_bind(); });
  13687. auto se = detail::scope_exit([&] {
  13688. svr.stop();
  13689. t.join();
  13690. });
  13691. svr.wait_until_ready();
  13692. bool verify_callback_called = false;
  13693. bool leftmost_wildcard_matched = false;
  13694. bool wildcard_spanned_labels = true;
  13695. bool inner_wildcard_matched = true;
  13696. SSLClient cli(HOST, port);
  13697. cli.enable_server_certificate_verification(true);
  13698. cli.set_ca_cert_path(CA_CERT_FILE);
  13699. cli.set_connection_timeout(5);
  13700. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13701. verify_callback_called = true;
  13702. if (!ctx.cert) return false;
  13703. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13704. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13705. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13706. return true; // Accept for the purpose of this test
  13707. });
  13708. cli.Get("/test");
  13709. ASSERT_TRUE(verify_callback_called)
  13710. << "Verify callback should have been called";
  13711. EXPECT_TRUE(leftmost_wildcard_matched)
  13712. << "A leftmost wildcard should match a single label";
  13713. EXPECT_FALSE(wildcard_spanned_labels)
  13714. << "A wildcard label must not match more than one label";
  13715. EXPECT_FALSE(inner_wildcard_matched)
  13716. << "A wildcard outside the leftmost label must not be honoured";
  13717. }
  13718. // sans() must report each SAN entry under its own type.
  13719. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13720. using namespace httplib::tls;
  13721. // SANs: DNS:a.zz, IP:42.46.122.122
  13722. SSLServer svr(SERVER_CERT_SAN_TYPES_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. auto port = svr.bind_to_any_port(HOST);
  13728. thread t([&]() { svr.listen_after_bind(); });
  13729. auto se = detail::scope_exit([&] {
  13730. svr.stop();
  13731. t.join();
  13732. });
  13733. svr.wait_until_ready();
  13734. bool verify_callback_called = false;
  13735. std::vector<SanEntry> sans;
  13736. SSLClient cli(HOST, port);
  13737. cli.enable_server_certificate_verification(true);
  13738. cli.set_ca_cert_path(CA_CERT_FILE);
  13739. cli.set_connection_timeout(5);
  13740. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13741. verify_callback_called = true;
  13742. if (!ctx.cert) return false;
  13743. sans = ctx.sans();
  13744. return true; // Accept for the purpose of this test
  13745. });
  13746. cli.Get("/test");
  13747. ASSERT_TRUE(verify_callback_called)
  13748. << "Verify callback should have been called";
  13749. auto has_san = [&](SanType type, const std::string &value) {
  13750. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13751. return san.type == type && san.value == value;
  13752. });
  13753. };
  13754. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13755. << "sans() should report the dNSName SAN";
  13756. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13757. << "sans() should report the iPAddress SAN";
  13758. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13759. << "sans() must not report the dNSName SAN as an address";
  13760. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13761. << "sans() must not report the iPAddress SAN as a DNS name";
  13762. }
  13763. #endif
  13764. // mbedTLS-specific callback constructor test
  13765. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13766. #ifdef CPPHTTPLIB_SSL_ENABLED
  13767. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13768. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13769. ASSERT_TRUE(svr.is_valid());
  13770. // Set up a handler to verify client certificate is present
  13771. bool client_cert_verified = false;
  13772. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13773. // Verify that client certificate was provided
  13774. client_cert_verified = true;
  13775. res.set_content("success", "text/plain");
  13776. });
  13777. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13778. auto se = detail::scope_exit([&] {
  13779. svr.stop();
  13780. t.join();
  13781. ASSERT_FALSE(svr.is_running());
  13782. });
  13783. svr.wait_until_ready();
  13784. // Client with certificate
  13785. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13786. cli.enable_server_certificate_verification(false);
  13787. cli.set_connection_timeout(30);
  13788. auto res = cli.Get("/test");
  13789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13790. ASSERT_EQ(StatusCode::OK_200, res->status);
  13791. ASSERT_TRUE(client_cert_verified);
  13792. EXPECT_EQ("success", res->body);
  13793. }
  13794. #endif
  13795. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13796. // backends
  13797. #ifdef CPPHTTPLIB_SSL_ENABLED
  13798. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13799. using namespace httplib::tls;
  13800. // Test that when client CA cert file is provided,
  13801. // the server properly requests and validates client certificates
  13802. // Create a server with client authentication
  13803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13804. ASSERT_TRUE(svr.is_valid());
  13805. bool handler_called = false;
  13806. svr.Get("/test", [&](const Request &req, Response &res) {
  13807. handler_called = true;
  13808. // Verify that a client certificate was provided
  13809. auto cert = req.peer_cert();
  13810. ASSERT_TRUE(static_cast<bool>(cert));
  13811. // Get the issuer name
  13812. std::string issuer_str = cert.issuer_name();
  13813. ASSERT_FALSE(issuer_str.empty());
  13814. // The client certificate should be issued by our test CA
  13815. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13816. res.set_content("authenticated", "text/plain");
  13817. });
  13818. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13819. auto se = detail::scope_exit([&] {
  13820. svr.stop();
  13821. t.join();
  13822. ASSERT_FALSE(svr.is_running());
  13823. });
  13824. svr.wait_until_ready();
  13825. // Connect with a client certificate issued by the CA
  13826. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13827. cli.enable_server_certificate_verification(false);
  13828. cli.set_connection_timeout(30);
  13829. auto res = cli.Get("/test");
  13830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13831. ASSERT_EQ(StatusCode::OK_200, res->status);
  13832. ASSERT_TRUE(handler_called);
  13833. EXPECT_EQ("authenticated", res->body);
  13834. }
  13835. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13836. using namespace httplib::tls;
  13837. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13838. ASSERT_TRUE(svr.is_valid());
  13839. svr.Get("/test", [](const Request &, Response &res) {
  13840. res.set_content("ok", "text/plain");
  13841. });
  13842. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13843. auto se = detail::scope_exit([&] {
  13844. svr.stop();
  13845. t.join();
  13846. });
  13847. svr.wait_until_ready();
  13848. SSLClient cli(HOST, PORT);
  13849. cli.enable_server_certificate_verification(false);
  13850. cli.set_connection_timeout(30);
  13851. bool cert_checked = false;
  13852. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13853. if (ctx.cert) {
  13854. auto sans = ctx.sans();
  13855. // Test certificate may or may not have SANs - just verify the API
  13856. // works If SANs exist, verify the types are valid
  13857. for (const auto &san : sans) {
  13858. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13859. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13860. san.type == SanType::OTHER);
  13861. EXPECT_FALSE(san.value.empty());
  13862. }
  13863. cert_checked = true;
  13864. }
  13865. return true;
  13866. });
  13867. auto res = cli.Get("/test");
  13868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13869. EXPECT_TRUE(cert_checked);
  13870. }
  13871. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13872. using namespace httplib::tls;
  13873. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13874. ASSERT_TRUE(svr.is_valid());
  13875. svr.Get("/test", [](const Request &, Response &res) {
  13876. res.set_content("ok", "text/plain");
  13877. });
  13878. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13879. auto se = detail::scope_exit([&] {
  13880. svr.stop();
  13881. t.join();
  13882. });
  13883. svr.wait_until_ready();
  13884. SSLClient cli(HOST, PORT);
  13885. cli.enable_server_certificate_verification(false);
  13886. cli.set_connection_timeout(30);
  13887. bool validity_checked = false;
  13888. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13889. if (ctx.cert) {
  13890. time_t not_before = 0, not_after = 0;
  13891. bool result = ctx.validity(not_before, not_after);
  13892. EXPECT_TRUE(result);
  13893. // Verify that not_before < now < not_after for a valid cert
  13894. time_t now = time(nullptr);
  13895. EXPECT_LT(not_before, now);
  13896. EXPECT_GT(not_after, now);
  13897. validity_checked = true;
  13898. }
  13899. return true;
  13900. });
  13901. auto res = cli.Get("/test");
  13902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13903. EXPECT_TRUE(validity_checked);
  13904. }
  13905. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13906. using namespace httplib::tls;
  13907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13908. ASSERT_TRUE(svr.is_valid());
  13909. svr.Get("/test", [](const Request &, Response &res) {
  13910. res.set_content("ok", "text/plain");
  13911. });
  13912. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13913. auto se = detail::scope_exit([&] {
  13914. svr.stop();
  13915. t.join();
  13916. });
  13917. svr.wait_until_ready();
  13918. SSLClient cli(HOST, PORT);
  13919. cli.enable_server_certificate_verification(false);
  13920. cli.set_connection_timeout(30);
  13921. bool serial_checked = false;
  13922. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13923. if (ctx.cert) {
  13924. std::string serial = ctx.serial();
  13925. EXPECT_FALSE(serial.empty());
  13926. // Serial should be a hex string
  13927. for (char c : serial) {
  13928. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13929. (c >= 'a' && c <= 'f'));
  13930. }
  13931. serial_checked = true;
  13932. }
  13933. return true;
  13934. });
  13935. auto res = cli.Get("/test");
  13936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13937. EXPECT_TRUE(serial_checked);
  13938. }
  13939. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13940. // Test 1: Valid CA file - no error should be recorded
  13941. {
  13942. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13943. CLIENT_CA_CERT_FILE);
  13944. ASSERT_TRUE(svr.is_valid());
  13945. // With valid setup, last_ssl_error should be 0
  13946. EXPECT_EQ(0, svr.ssl_last_error());
  13947. }
  13948. // Test 2: Invalid CA file content
  13949. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13950. {
  13951. // Create a temporary file with completely invalid content
  13952. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13953. {
  13954. std::ofstream ofs(temp_invalid_ca);
  13955. ofs << "This is not a certificate file at all\n";
  13956. ofs << "Just plain text content\n";
  13957. }
  13958. // Create server with invalid CA file
  13959. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13960. // Clean up temporary file
  13961. std::remove(temp_invalid_ca);
  13962. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13963. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13964. // Note: SSL_CTX_load_verify_locations typically fails first,
  13965. // but our error handling code path is still exercised
  13966. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13967. }
  13968. }
  13969. TEST(VerifyCallbackTest, VerifyContextFields) {
  13970. using namespace httplib::tls;
  13971. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13972. ASSERT_TRUE(svr.is_valid());
  13973. svr.Get("/test", [](const Request &, Response &res) {
  13974. res.set_content("ok", "text/plain");
  13975. });
  13976. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13977. auto se = detail::scope_exit([&] {
  13978. svr.stop();
  13979. t.join();
  13980. });
  13981. svr.wait_until_ready();
  13982. SSLClient cli(HOST, PORT);
  13983. cli.enable_server_certificate_verification(false);
  13984. cli.set_connection_timeout(30);
  13985. int callback_count = 0;
  13986. bool saw_leaf_cert = false;
  13987. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13988. if (ctx.cert) {
  13989. callback_count++;
  13990. // We should see at least one certificate (the leaf)
  13991. std::string cn = ctx.subject_cn();
  13992. if (!cn.empty()) { saw_leaf_cert = true; }
  13993. // Verify context fields are populated
  13994. EXPECT_NE(ctx.session, nullptr);
  13995. EXPECT_GE(ctx.depth, 0);
  13996. }
  13997. return true;
  13998. });
  13999. auto res = cli.Get("/test");
  14000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14001. EXPECT_GT(callback_count, 0);
  14002. EXPECT_TRUE(saw_leaf_cert);
  14003. }
  14004. // A verifier belongs to the client that set it, not to the thread that set it.
  14005. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14006. using namespace httplib::tls;
  14007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14008. ASSERT_TRUE(svr.is_valid());
  14009. svr.Get("/test", [](const Request &, Response &res) {
  14010. res.set_content("ok", "text/plain");
  14011. });
  14012. auto port = svr.bind_to_any_port(HOST);
  14013. thread t([&]() { svr.listen_after_bind(); });
  14014. auto se = detail::scope_exit([&] {
  14015. svr.stop();
  14016. t.join();
  14017. });
  14018. svr.wait_until_ready();
  14019. auto rejecting_calls = 0;
  14020. SSLClient rejecting(HOST, port);
  14021. rejecting.enable_server_certificate_verification(false);
  14022. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14023. rejecting_calls++;
  14024. return false;
  14025. });
  14026. auto accepting_calls = 0;
  14027. SSLClient accepting(HOST, port);
  14028. accepting.enable_server_certificate_verification(false);
  14029. // Set on another thread than the requests below.
  14030. thread([&]() {
  14031. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14032. accepting_calls++;
  14033. return true;
  14034. });
  14035. }).join();
  14036. // Requested on another thread than the verifier was set on.
  14037. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14038. EXPECT_GT(rejecting_calls, 0);
  14039. auto res = accepting.Get("/test");
  14040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14041. EXPECT_GT(accepting_calls, 0);
  14042. }
  14043. // VerifyContext::session is the same handle the other tls:: functions take.
  14044. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14045. using namespace httplib::tls;
  14046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14047. ASSERT_TRUE(svr.is_valid());
  14048. svr.Get("/test", [](const Request &, Response &res) {
  14049. res.set_content("ok", "text/plain");
  14050. });
  14051. auto port = svr.bind_to_any_port(HOST);
  14052. thread t([&]() { svr.listen_after_bind(); });
  14053. auto se = detail::scope_exit([&] {
  14054. svr.stop();
  14055. t.join();
  14056. });
  14057. svr.wait_until_ready();
  14058. SSLClient cli(HOST, port);
  14059. cli.enable_server_certificate_verification(false);
  14060. session_t verifier_session = nullptr;
  14061. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14062. verifier_session = ctx.session;
  14063. return true;
  14064. });
  14065. session_t session_verifier_session = nullptr;
  14066. cli.set_session_verifier([&](session_t session) {
  14067. session_verifier_session = session;
  14068. return SSLVerifierResponse::NoDecisionMade;
  14069. });
  14070. auto res = cli.Get("/test");
  14071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14072. EXPECT_NE(nullptr, verifier_session);
  14073. EXPECT_EQ(session_verifier_session, verifier_session);
  14074. }
  14075. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14076. using httplib::tls::TlsError;
  14077. // Test that verify_error_to_string returns empty for success
  14078. std::string success_str = TlsError::verify_error_to_string(0);
  14079. EXPECT_TRUE(success_str.empty());
  14080. // Test that verify_error_to_string returns non-empty for error codes
  14081. // Using a common error code (certificate expired)
  14082. std::string error_str =
  14083. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14084. EXPECT_FALSE(error_str.empty());
  14085. }
  14086. TEST(SessionVerifierTest, CertificateAccepted) {
  14087. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14088. ASSERT_TRUE(svr.is_valid());
  14089. svr.Get("/test", [](const Request &, Response &res) {
  14090. res.set_content("ok", "text/plain");
  14091. });
  14092. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14093. auto se = detail::scope_exit([&] {
  14094. svr.stop();
  14095. t.join();
  14096. });
  14097. svr.wait_until_ready();
  14098. SSLClient cli(HOST, PORT);
  14099. cli.enable_server_certificate_verification(false);
  14100. cli.set_connection_timeout(30);
  14101. bool callback_called = false;
  14102. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14103. EXPECT_NE(session, nullptr);
  14104. callback_called = true;
  14105. return SSLVerifierResponse::CertificateAccepted;
  14106. });
  14107. auto res = cli.Get("/test");
  14108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14109. EXPECT_EQ(200, res->status);
  14110. EXPECT_TRUE(callback_called);
  14111. }
  14112. TEST(SessionVerifierTest, CertificateRejected) {
  14113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14114. ASSERT_TRUE(svr.is_valid());
  14115. svr.Get("/test", [](const Request &, Response &res) {
  14116. res.set_content("ok", "text/plain");
  14117. });
  14118. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14119. auto se = detail::scope_exit([&] {
  14120. svr.stop();
  14121. t.join();
  14122. });
  14123. svr.wait_until_ready();
  14124. SSLClient cli(HOST, PORT);
  14125. cli.enable_server_certificate_verification(false);
  14126. cli.set_connection_timeout(30);
  14127. bool callback_called = false;
  14128. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14129. EXPECT_NE(session, nullptr);
  14130. callback_called = true;
  14131. return SSLVerifierResponse::CertificateRejected;
  14132. });
  14133. auto res = cli.Get("/test");
  14134. EXPECT_FALSE(res);
  14135. EXPECT_TRUE(callback_called);
  14136. }
  14137. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14138. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14139. ASSERT_TRUE(svr.is_valid());
  14140. svr.Get("/test", [](const Request &, Response &res) {
  14141. res.set_content("ok", "text/plain");
  14142. });
  14143. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14144. auto se = detail::scope_exit([&] {
  14145. svr.stop();
  14146. t.join();
  14147. });
  14148. svr.wait_until_ready();
  14149. // NoDecisionMade with verification disabled should succeed (no default check)
  14150. SSLClient cli(HOST, PORT);
  14151. cli.enable_server_certificate_verification(false);
  14152. cli.set_connection_timeout(30);
  14153. bool callback_called = false;
  14154. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14155. EXPECT_NE(session, nullptr);
  14156. callback_called = true;
  14157. return SSLVerifierResponse::NoDecisionMade;
  14158. });
  14159. auto res = cli.Get("/test");
  14160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14161. EXPECT_EQ(200, res->status);
  14162. EXPECT_TRUE(callback_called);
  14163. }
  14164. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14165. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14166. ASSERT_TRUE(svr.is_valid());
  14167. svr.Get("/test", [](const Request &, Response &res) {
  14168. res.set_content("ok", "text/plain");
  14169. });
  14170. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14171. auto se = detail::scope_exit([&] {
  14172. svr.stop();
  14173. t.join();
  14174. });
  14175. svr.wait_until_ready();
  14176. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14177. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14178. // so we only check that the request fails, not whether the callback was
  14179. // called.
  14180. SSLClient cli(HOST, PORT);
  14181. cli.enable_server_certificate_verification(true);
  14182. cli.set_connection_timeout(30);
  14183. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14184. EXPECT_NE(session, nullptr);
  14185. return SSLVerifierResponse::NoDecisionMade;
  14186. });
  14187. auto res = cli.Get("/test");
  14188. EXPECT_FALSE(res);
  14189. }
  14190. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14191. // Test SSL server using PemMemory constructor with client CA certificates
  14192. // Read PEM files
  14193. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14194. read_file(SERVER_CERT_FILE, server_cert_pem);
  14195. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14196. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14197. // Create SSLServer with PemMemory constructor including client CA
  14198. SSLServer::PemMemory server_pem = {
  14199. server_cert_pem.c_str(),
  14200. server_cert_pem.size(),
  14201. server_key_pem.c_str(),
  14202. server_key_pem.size(),
  14203. client_ca_pem.c_str(),
  14204. client_ca_pem.size(),
  14205. nullptr // no password for server key
  14206. };
  14207. SSLServer svr(server_pem);
  14208. ASSERT_TRUE(svr.is_valid());
  14209. // No SSL error should be recorded for valid setup
  14210. EXPECT_EQ(0, svr.ssl_last_error());
  14211. // Set up server endpoints
  14212. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14213. res.set_content("ok", "text/plain");
  14214. });
  14215. // Start server in a thread
  14216. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14217. svr.wait_until_ready();
  14218. // Connect with client certificate (using constructor with paths)
  14219. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14220. cli.enable_server_certificate_verification(false);
  14221. auto res = cli.Get("/test-pem-ca");
  14222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14223. EXPECT_EQ(200, res->status);
  14224. EXPECT_EQ("ok", res->body);
  14225. svr.stop();
  14226. server_thread.join();
  14227. }
  14228. #endif
  14229. #ifdef _WIN32
  14230. TEST(CleanupTest, WSACleanup) {
  14231. int ret = WSACleanup();
  14232. ASSERT_EQ(0, ret);
  14233. }
  14234. #endif
  14235. #ifndef CPPHTTPLIB_SSL_ENABLED
  14236. TEST(NoSSLSupport, SimpleInterface) {
  14237. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14238. }
  14239. #endif
  14240. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14241. TEST(InvalidScheme, SimpleInterface) {
  14242. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14243. }
  14244. #endif
  14245. TEST(NoScheme, SimpleInterface) {
  14246. Client cli("yahoo.com:80");
  14247. ASSERT_TRUE(cli.is_valid());
  14248. }
  14249. TEST(SendAPI, SimpleInterface_Online) {
  14250. Client cli("http://yahoo.com");
  14251. Request req;
  14252. req.method = "GET";
  14253. req.path = "/";
  14254. auto res = cli.send(req);
  14255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14256. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14257. }
  14258. TEST(SendAPI, WithParamsInRequest) {
  14259. Server svr;
  14260. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14261. EXPECT_TRUE(req.has_param("test"));
  14262. EXPECT_EQ("test_value", req.get_param_value("test"));
  14263. });
  14264. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14265. auto se = detail::scope_exit([&] {
  14266. svr.stop();
  14267. t.join();
  14268. ASSERT_FALSE(svr.is_running());
  14269. });
  14270. svr.wait_until_ready();
  14271. Client cli(HOST, PORT);
  14272. {
  14273. Request req;
  14274. req.method = "GET";
  14275. req.path = "/";
  14276. req.params.emplace("test", "test_value");
  14277. auto res = cli.send(req);
  14278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14279. }
  14280. {
  14281. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14283. }
  14284. }
  14285. TEST(ClientImplMethods, GetSocketTest) {
  14286. httplib::Server svr;
  14287. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14288. res.status = StatusCode::OK_200;
  14289. });
  14290. auto port = svr.bind_to_any_port("127.0.0.1");
  14291. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14292. auto se = detail::scope_exit([&] {
  14293. svr.stop();
  14294. thread.join();
  14295. ASSERT_FALSE(svr.is_running());
  14296. });
  14297. svr.wait_until_ready();
  14298. {
  14299. httplib::Client cli("127.0.0.1", port);
  14300. cli.set_keep_alive(true);
  14301. // Use the behavior of cpp-httplib of opening the connection
  14302. // only when the first request happens. If that changes,
  14303. // this test would be obsolete.
  14304. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14305. // This also implicitly tests the server. But other tests would fail much
  14306. // earlier than this one to be considered.
  14307. auto res = cli.Get("/");
  14308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14309. EXPECT_EQ(StatusCode::OK_200, res->status);
  14310. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14311. }
  14312. }
  14313. #ifdef CPPHTTPLIB_SSL_ENABLED
  14314. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14315. Client cli("http://yahoo.com");
  14316. auto res = cli.Get("/");
  14317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14318. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14319. cli.set_follow_location(true);
  14320. res = cli.Get("/");
  14321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14322. EXPECT_EQ(StatusCode::OK_200, res->status);
  14323. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14324. }
  14325. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14326. Client cli("https://yahoo.com");
  14327. auto res = cli.Get("/");
  14328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14329. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14330. cli.set_follow_location(true);
  14331. res = cli.Get("/");
  14332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14333. EXPECT_EQ(StatusCode::OK_200, res->status);
  14334. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14335. }
  14336. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14337. Client cli("https://yahoo.com");
  14338. auto res = cli.Get("/");
  14339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14340. ASSERT_FALSE(!res);
  14341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14342. ASSERT_FALSE(res == nullptr);
  14343. ASSERT_TRUE(res != nullptr);
  14344. EXPECT_EQ(Error::Success, res.error());
  14345. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14346. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14347. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14348. cli.set_follow_location(true);
  14349. res = cli.Get("/");
  14350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14351. EXPECT_EQ(Error::Success, res.error());
  14352. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14353. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14354. EXPECT_EQ(StatusCode::OK_200, res->status);
  14355. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14356. }
  14357. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14358. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14359. Client cli("https://cdnjs.cloudflare.com");
  14360. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14361. Headers{{"Accept-Encoding", "br"}});
  14362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14363. EXPECT_EQ(StatusCode::OK_200, res->status);
  14364. EXPECT_EQ(287630U, res->body.size());
  14365. EXPECT_EQ("application/javascript; charset=utf-8",
  14366. res->get_header_value("Content-Type"));
  14367. }
  14368. #endif
  14369. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14370. #undef REDIR_HOST // Silence compiler warning
  14371. #define REDIR_HOST "https://httpbingo.org"
  14372. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14373. Client cli(REDIR_HOST);
  14374. cli.set_follow_location(true);
  14375. auto res =
  14376. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14378. EXPECT_EQ(StatusCode::OK_200, res->status);
  14379. }
  14380. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14381. Client cli(REDIR_HOST);
  14382. cli.set_follow_location(true);
  14383. Params params;
  14384. params.emplace("url", "http://example.com");
  14385. params.emplace("status_code", "302");
  14386. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14388. EXPECT_EQ(StatusCode::OK_200, res->status);
  14389. }
  14390. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14391. Client cli(REDIR_HOST);
  14392. cli.set_follow_location(true);
  14393. Params params;
  14394. params.emplace("url", "http://example.com");
  14395. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14397. EXPECT_EQ(StatusCode::OK_200, res->status);
  14398. }
  14399. TEST(HttpToHttpsRedirectTest, CertFile) {
  14400. auto ssl_port = PORT + 1;
  14401. Server svr;
  14402. ASSERT_TRUE(svr.is_valid());
  14403. svr.Get("/index", [&](const Request &, Response &res) {
  14404. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14405. "/index");
  14406. svr.stop();
  14407. });
  14408. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14409. ASSERT_TRUE(ssl_svr.is_valid());
  14410. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14411. res.set_content("test", "text/plain");
  14412. ssl_svr.stop();
  14413. });
  14414. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14415. thread t2 =
  14416. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14417. auto se = detail::scope_exit([&] {
  14418. t2.join();
  14419. t.join();
  14420. ASSERT_FALSE(svr.is_running());
  14421. });
  14422. svr.wait_until_ready();
  14423. ssl_svr.wait_until_ready();
  14424. Client cli("127.0.0.1", PORT);
  14425. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14426. cli.enable_server_certificate_verification(true);
  14427. cli.set_follow_location(true);
  14428. cli.set_connection_timeout(30);
  14429. auto res = cli.Get("/index");
  14430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14431. ASSERT_EQ(StatusCode::OK_200, res->status);
  14432. }
  14433. TEST(SSLClientRedirectTest, CertFile) {
  14434. auto ssl_port = PORT + 1;
  14435. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14436. ASSERT_TRUE(ssl_svr1.is_valid());
  14437. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14438. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14439. "/index");
  14440. ssl_svr1.stop();
  14441. });
  14442. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14443. ASSERT_TRUE(ssl_svr2.is_valid());
  14444. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14445. res.set_content("test", "text/plain");
  14446. ssl_svr2.stop();
  14447. });
  14448. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14449. thread t2 =
  14450. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14451. auto se = detail::scope_exit([&] {
  14452. t2.join();
  14453. t.join();
  14454. ASSERT_FALSE(ssl_svr1.is_running());
  14455. });
  14456. ssl_svr1.wait_until_ready();
  14457. ssl_svr2.wait_until_ready();
  14458. SSLClient cli("127.0.0.1", PORT);
  14459. std::string cert;
  14460. read_file(SERVER_CERT2_FILE, cert);
  14461. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14462. cli.enable_server_certificate_verification(true);
  14463. cli.set_follow_location(true);
  14464. cli.set_connection_timeout(30);
  14465. auto res = cli.Get("/index");
  14466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14467. ASSERT_EQ(StatusCode::OK_200, res->status);
  14468. }
  14469. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14470. // another port, so the client follows it with a new client.
  14471. static Result GetThroughTlsRedirectToDifferentPort(
  14472. const std::function<void(SSLClient &)> &setup,
  14473. const char *target_cert = SERVER_CERT2_FILE,
  14474. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  14475. auto ssl_port = PORT + 1;
  14476. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14477. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14478. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14479. "/index");
  14480. });
  14481. SSLServer ssl_svr2(target_cert, target_key);
  14482. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14483. res.set_content("test", "text/plain");
  14484. });
  14485. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14486. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14487. auto se = detail::scope_exit([&] {
  14488. ssl_svr2.stop();
  14489. ssl_svr1.stop();
  14490. t2.join();
  14491. t.join();
  14492. });
  14493. ssl_svr1.wait_until_ready();
  14494. ssl_svr2.wait_until_ready();
  14495. SSLClient cli("127.0.0.1", PORT);
  14496. cli.set_follow_location(true);
  14497. cli.set_connection_timeout(30);
  14498. setup(cli);
  14499. return cli.Get("/index");
  14500. }
  14501. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14502. auto calls = 0;
  14503. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14504. cli.enable_server_certificate_verification(false);
  14505. // Accept the first server only.
  14506. cli.set_session_verifier([&](tls::session_t) {
  14507. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14508. : SSLVerifierResponse::CertificateRejected;
  14509. });
  14510. });
  14511. EXPECT_FALSE(res);
  14512. EXPECT_EQ(2, calls);
  14513. }
  14514. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14515. std::string pinned;
  14516. auto res = GetThroughTlsRedirectToDifferentPort(
  14517. [&](SSLClient &cli) {
  14518. cli.enable_server_certificate_verification(false);
  14519. // Pin the first certificate seen.
  14520. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14521. if (pinned.empty()) { pinned = ctx.serial(); }
  14522. return ctx.serial() == pinned;
  14523. });
  14524. },
  14525. // A certificate other than the first server's.
  14526. SERVER_CERT_FILE);
  14527. EXPECT_FALSE(res);
  14528. EXPECT_FALSE(pinned.empty());
  14529. }
  14530. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14531. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14532. std::string cert;
  14533. read_file(SERVER_CERT2_FILE, cert);
  14534. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14535. });
  14536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14537. EXPECT_EQ(StatusCode::OK_200, res->status);
  14538. }
  14539. // The target's certificate is signed by the root CA, which the first server's
  14540. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  14541. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  14542. auto res = GetThroughTlsRedirectToDifferentPort(
  14543. [](SSLClient &cli) {
  14544. std::string root_ca, cert;
  14545. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14546. read_file(SERVER_CERT2_FILE, cert);
  14547. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14548. cli.load_ca_cert_store(cert.data(), cert.size());
  14549. cli.enable_server_hostname_verification(false);
  14550. },
  14551. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14553. EXPECT_EQ(StatusCode::OK_200, res->status);
  14554. }
  14555. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  14556. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  14557. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  14558. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  14559. auto res = GetThroughTlsRedirectToDifferentPort(
  14560. [](SSLClient &cli) {
  14561. std::string root_ca, cert;
  14562. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14563. read_file(SERVER_CERT2_FILE, cert);
  14564. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14565. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14566. cli.enable_server_hostname_verification(false);
  14567. },
  14568. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14569. ASSERT_FALSE(res);
  14570. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14571. }
  14572. #endif
  14573. #endif
  14574. #ifdef CPPHTTPLIB_SSL_ENABLED
  14575. // Test that set_ca_cert_store() skips system certs (consistent with
  14576. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14577. // should be trusted - system certs should NOT be loaded.
  14578. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14579. // Load a specific cert that is NOT a system CA cert
  14580. std::string cert;
  14581. read_file(SERVER_CERT2_FILE, cert);
  14582. SSLClient cli("google.com");
  14583. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14584. cli.enable_server_certificate_verification(true);
  14585. // This should FAIL because:
  14586. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14587. // 2. System certs should NOT be loaded when custom store is set
  14588. // If system certs WERE loaded, this would succeed
  14589. auto res = cli.Get("/");
  14590. ASSERT_FALSE(res);
  14591. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14592. }
  14593. // Same as above, but through the native store handle path. Regression test:
  14594. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14595. // merged system certs into the user-provided store.
  14596. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14597. std::string cert;
  14598. read_file(SERVER_CERT2_FILE, cert);
  14599. SSLClient cli("google.com");
  14600. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14601. cli.enable_server_certificate_verification(true);
  14602. auto res = cli.Get("/");
  14603. ASSERT_FALSE(res);
  14604. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14605. }
  14606. // A custom store set via the native handle must still verify a server whose
  14607. // cert it does contain.
  14608. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14609. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14610. ASSERT_TRUE(svr.is_valid());
  14611. svr.Get("/test", [&](const Request &, Response &res) {
  14612. res.set_content("test", "text/plain");
  14613. });
  14614. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14615. auto se = detail::scope_exit([&] {
  14616. svr.stop();
  14617. t.join();
  14618. ASSERT_FALSE(svr.is_running());
  14619. });
  14620. svr.wait_until_ready();
  14621. SSLClient cli("127.0.0.1", PORT);
  14622. std::string cert;
  14623. read_file(SERVER_CERT2_FILE, cert);
  14624. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14625. cli.enable_server_certificate_verification(true);
  14626. cli.set_connection_timeout(30);
  14627. auto res = cli.Get("/test");
  14628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14629. ASSERT_EQ(StatusCode::OK_200, res->status);
  14630. }
  14631. // CA certs loaded through the universal Client must be transferred to the
  14632. // client created internally for following an HTTPS redirect. Regression test:
  14633. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14634. // the CA data for redirect transfer.
  14635. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14636. auto ssl_port = PORT + 1;
  14637. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14638. ASSERT_TRUE(ssl_svr1.is_valid());
  14639. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14640. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14641. "/index");
  14642. });
  14643. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14644. ASSERT_TRUE(ssl_svr2.is_valid());
  14645. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14646. res.set_content("test", "text/plain");
  14647. });
  14648. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14649. thread t2 =
  14650. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14651. auto se = detail::scope_exit([&] {
  14652. ssl_svr2.stop();
  14653. ssl_svr1.stop();
  14654. t2.join();
  14655. t.join();
  14656. ASSERT_FALSE(ssl_svr1.is_running());
  14657. });
  14658. ssl_svr1.wait_until_ready();
  14659. ssl_svr2.wait_until_ready();
  14660. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14661. std::string cert;
  14662. read_file(SERVER_CERT2_FILE, cert);
  14663. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14664. cli.enable_server_certificate_verification(true);
  14665. cli.set_follow_location(true);
  14666. cli.set_connection_timeout(30);
  14667. auto res = cli.Get("/index");
  14668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14669. ASSERT_EQ(StatusCode::OK_200, res->status);
  14670. }
  14671. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14672. // so a host signed by a system CA verifies even though a custom CA is set
  14673. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14674. std::string cert;
  14675. read_file(SERVER_CERT2_FILE, cert);
  14676. SSLClient cli("google.com");
  14677. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14678. cli.enable_system_ca(true);
  14679. cli.enable_server_certificate_verification(true);
  14680. auto res = cli.Get("/");
  14681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14682. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14683. }
  14684. // The custom CA remains effective when combined with the system CA
  14685. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14686. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14687. ASSERT_TRUE(svr.is_valid());
  14688. svr.Get("/test", [&](const Request &, Response &res) {
  14689. res.set_content("test", "text/plain");
  14690. });
  14691. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14692. auto se = detail::scope_exit([&] {
  14693. svr.stop();
  14694. t.join();
  14695. ASSERT_FALSE(svr.is_running());
  14696. });
  14697. svr.wait_until_ready();
  14698. SSLClient cli("127.0.0.1", PORT);
  14699. std::string cert;
  14700. read_file(SERVER_CERT2_FILE, cert);
  14701. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14702. cli.enable_system_ca(true);
  14703. cli.enable_server_certificate_verification(true);
  14704. cli.set_connection_timeout(30);
  14705. auto res = cli.Get("/test");
  14706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14707. ASSERT_EQ(StatusCode::OK_200, res->status);
  14708. }
  14709. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14710. // skip chain verification entirely (only the certificate identity was
  14711. // checked), so a server presenting an untrusted certificate with a matching
  14712. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14713. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14714. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14715. ASSERT_TRUE(svr.is_valid());
  14716. svr.Get("/test", [&](const Request &, Response &res) {
  14717. res.set_content("test", "text/plain");
  14718. });
  14719. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14720. auto se = detail::scope_exit([&] {
  14721. svr.stop();
  14722. t.join();
  14723. ASSERT_FALSE(svr.is_running());
  14724. });
  14725. svr.wait_until_ready();
  14726. SSLClient cli("127.0.0.1", PORT);
  14727. std::string cert;
  14728. // A trusted CA that did not sign the server certificate. The server cert
  14729. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14730. // this connection.
  14731. read_file(CLIENT_CA_CERT_FILE, cert);
  14732. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14733. cli.enable_server_certificate_verification(true);
  14734. cli.set_connection_timeout(30);
  14735. auto res = cli.Get("/test");
  14736. ASSERT_FALSE(res);
  14737. }
  14738. // enable_system_ca(false) prevents system CA loading entirely
  14739. TEST(SSLClientTest, DisableSystemCa_Online) {
  14740. SSLClient cli("google.com");
  14741. cli.enable_system_ca(false);
  14742. cli.enable_server_certificate_verification(true);
  14743. auto res = cli.Get("/");
  14744. ASSERT_FALSE(res);
  14745. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14746. // itself when the CA chain is empty
  14747. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14748. res.error() == Error::SSLConnection);
  14749. }
  14750. // The universal Client forwards enable_system_ca()
  14751. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14752. std::string cert;
  14753. read_file(SERVER_CERT2_FILE, cert);
  14754. Client cli("https://google.com");
  14755. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14756. cli.enable_system_ca(true);
  14757. cli.enable_server_certificate_verification(true);
  14758. auto res = cli.Get("/");
  14759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14760. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14761. }
  14762. // The system CA policy must carry over to the client created internally for
  14763. // following a cross-host HTTPS redirect
  14764. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14765. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14766. ASSERT_TRUE(svr.is_valid());
  14767. svr.Get("/index", [&](const Request &, Response &res) {
  14768. res.set_redirect("https://www.google.com/");
  14769. });
  14770. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14771. auto se = detail::scope_exit([&] {
  14772. svr.stop();
  14773. t.join();
  14774. ASSERT_FALSE(svr.is_running());
  14775. });
  14776. svr.wait_until_ready();
  14777. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14778. std::string cert;
  14779. read_file(SERVER_CERT2_FILE, cert);
  14780. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14781. cli.enable_system_ca(true);
  14782. cli.enable_server_certificate_verification(true);
  14783. cli.set_follow_location(true);
  14784. cli.set_connection_timeout(30);
  14785. // Receiving any response proves the redirect client completed the TLS
  14786. // handshake with a system-CA-signed host
  14787. auto res = cli.Get("/index");
  14788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14789. }
  14790. TEST(MultipartFormDataTest, LargeData) {
  14791. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14792. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14793. const ContentReader &content_reader) {
  14794. if (req.is_multipart_form_data()) {
  14795. std::vector<FormData> items;
  14796. content_reader(
  14797. [&](const FormData &file) {
  14798. items.push_back(file);
  14799. return true;
  14800. },
  14801. [&](const char *data, size_t data_length) {
  14802. items.back().content.append(data, data_length);
  14803. return true;
  14804. });
  14805. EXPECT_TRUE(std::string(items[0].name) == "document");
  14806. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14807. EXPECT_TRUE(items[0].filename == "2MB_data");
  14808. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14809. EXPECT_TRUE(items[1].name == "hello");
  14810. EXPECT_TRUE(items[1].content == "world");
  14811. EXPECT_TRUE(items[1].filename == "");
  14812. EXPECT_TRUE(items[1].content_type == "");
  14813. } else {
  14814. std::string body;
  14815. content_reader([&](const char *data, size_t data_length) {
  14816. body.append(data, data_length);
  14817. return true;
  14818. });
  14819. }
  14820. });
  14821. auto port = svr.bind_to_any_port(HOST);
  14822. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14823. auto se = detail::scope_exit([&] {
  14824. svr.stop();
  14825. t.join();
  14826. ASSERT_FALSE(svr.is_running());
  14827. });
  14828. svr.wait_until_ready();
  14829. {
  14830. std::string data(1024 * 1024 * 2, '.');
  14831. std::stringstream buffer;
  14832. buffer << data;
  14833. SSLClient cli(HOST, port);
  14834. cli.enable_server_certificate_verification(false);
  14835. UploadFormDataItems items{
  14836. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14837. {"hello", "world", "", ""},
  14838. };
  14839. auto res = cli.Post("/post", items);
  14840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14841. ASSERT_EQ(StatusCode::OK_200, res->status);
  14842. }
  14843. }
  14844. TEST(MultipartFormDataTest, DataProviderItems) {
  14845. std::random_device seed_gen;
  14846. std::mt19937 random(seed_gen());
  14847. std::string rand1;
  14848. rand1.resize(1000);
  14849. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14850. std::string rand2;
  14851. rand2.resize(3000);
  14852. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14854. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14855. const ContentReader &content_reader) {
  14856. ASSERT_FALSE(req.is_multipart_form_data());
  14857. std::string body;
  14858. content_reader([&](const char *data, size_t data_length) {
  14859. body.append(data, data_length);
  14860. return true;
  14861. });
  14862. EXPECT_EQ(body, "");
  14863. });
  14864. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14865. const ContentReader &content_reader) {
  14866. ASSERT_TRUE(req.is_multipart_form_data());
  14867. std::vector<FormData> items;
  14868. content_reader(
  14869. [&](const FormData &file) {
  14870. items.push_back(file);
  14871. return true;
  14872. },
  14873. [&](const char *data, size_t data_length) {
  14874. items.back().content.append(data, data_length);
  14875. return true;
  14876. });
  14877. ASSERT_TRUE(items.size() == 2);
  14878. EXPECT_EQ(std::string(items[0].name), "name1");
  14879. EXPECT_EQ(items[0].content, "Testing123");
  14880. EXPECT_EQ(items[0].filename, "filename1");
  14881. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14882. EXPECT_EQ(items[1].name, "name2");
  14883. EXPECT_EQ(items[1].content, "Testing456");
  14884. EXPECT_EQ(items[1].filename, "");
  14885. EXPECT_EQ(items[1].content_type, "");
  14886. });
  14887. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14888. const ContentReader &content_reader) {
  14889. ASSERT_TRUE(req.is_multipart_form_data());
  14890. std::vector<FormData> items;
  14891. content_reader(
  14892. [&](const FormData &file) {
  14893. items.push_back(file);
  14894. return true;
  14895. },
  14896. [&](const char *data, size_t data_length) {
  14897. items.back().content.append(data, data_length);
  14898. return true;
  14899. });
  14900. ASSERT_TRUE(items.size() == 2);
  14901. EXPECT_EQ(items[0].name, "name3");
  14902. EXPECT_EQ(items[0].content, rand1);
  14903. EXPECT_EQ(items[0].filename, "filename3");
  14904. EXPECT_EQ(items[0].content_type, "");
  14905. EXPECT_EQ(items[1].name, "name4");
  14906. EXPECT_EQ(items[1].content, rand2);
  14907. EXPECT_EQ(items[1].filename, "filename4");
  14908. EXPECT_EQ(items[1].content_type, "");
  14909. });
  14910. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14911. const ContentReader &content_reader) {
  14912. ASSERT_TRUE(req.is_multipart_form_data());
  14913. std::vector<FormData> items;
  14914. content_reader(
  14915. [&](const FormData &file) {
  14916. items.push_back(file);
  14917. return true;
  14918. },
  14919. [&](const char *data, size_t data_length) {
  14920. items.back().content.append(data, data_length);
  14921. return true;
  14922. });
  14923. ASSERT_TRUE(items.size() == 4);
  14924. EXPECT_EQ(std::string(items[0].name), "name1");
  14925. EXPECT_EQ(items[0].content, "Testing123");
  14926. EXPECT_EQ(items[0].filename, "filename1");
  14927. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14928. EXPECT_EQ(items[1].name, "name2");
  14929. EXPECT_EQ(items[1].content, "Testing456");
  14930. EXPECT_EQ(items[1].filename, "");
  14931. EXPECT_EQ(items[1].content_type, "");
  14932. EXPECT_EQ(items[2].name, "name3");
  14933. EXPECT_EQ(items[2].content, rand1);
  14934. EXPECT_EQ(items[2].filename, "filename3");
  14935. EXPECT_EQ(items[2].content_type, "");
  14936. EXPECT_EQ(items[3].name, "name4");
  14937. EXPECT_EQ(items[3].content, rand2);
  14938. EXPECT_EQ(items[3].filename, "filename4");
  14939. EXPECT_EQ(items[3].content_type, "");
  14940. });
  14941. auto port = svr.bind_to_any_port("localhost");
  14942. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14943. auto se = detail::scope_exit([&] {
  14944. svr.stop();
  14945. t.join();
  14946. ASSERT_FALSE(svr.is_running());
  14947. });
  14948. svr.wait_until_ready();
  14949. {
  14950. SSLClient cli("localhost", port);
  14951. cli.enable_server_certificate_verification(false);
  14952. UploadFormDataItems items{
  14953. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14954. {"name2", "Testing456", "", ""}, // not a file
  14955. };
  14956. {
  14957. auto res = cli.Post("/post-none", {}, {}, {});
  14958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14959. ASSERT_EQ(StatusCode::OK_200, res->status);
  14960. }
  14961. FormDataProviderItems providers;
  14962. {
  14963. auto res =
  14964. cli.Post("/post-items", {}, items, providers); // empty providers
  14965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14966. ASSERT_EQ(StatusCode::OK_200, res->status);
  14967. }
  14968. providers.push_back({"name3",
  14969. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14970. // test the offset is given correctly at each step
  14971. if (!offset)
  14972. sink.os.write(rand1.data(), 30);
  14973. else if (offset == 30)
  14974. sink.os.write(rand1.data() + 30, 300);
  14975. else if (offset == 330)
  14976. sink.os.write(rand1.data() + 330, 670);
  14977. else if (offset == rand1.size())
  14978. sink.done();
  14979. return true;
  14980. },
  14981. "filename3",
  14982. {}});
  14983. providers.push_back({"name4",
  14984. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14985. // test the offset is given correctly at each step
  14986. if (!offset)
  14987. sink.os.write(rand2.data(), 2000);
  14988. else if (offset == 2000)
  14989. sink.os.write(rand2.data() + 2000, 1);
  14990. else if (offset == 2001)
  14991. sink.os.write(rand2.data() + 2001, 999);
  14992. else if (offset == rand2.size())
  14993. sink.done();
  14994. return true;
  14995. },
  14996. "filename4",
  14997. {}});
  14998. {
  14999. auto res = cli.Post("/post-providers", {}, {}, providers);
  15000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15001. ASSERT_EQ(StatusCode::OK_200, res->status);
  15002. }
  15003. {
  15004. auto res = cli.Post("/post-both", {}, items, providers);
  15005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15006. ASSERT_EQ(StatusCode::OK_200, res->status);
  15007. }
  15008. }
  15009. }
  15010. TEST(MultipartFormDataTest, BadHeader) {
  15011. Server svr;
  15012. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15013. res.set_content("ok", "text/plain");
  15014. });
  15015. thread t = thread([&] { svr.listen(HOST, PORT); });
  15016. auto se = detail::scope_exit([&] {
  15017. svr.stop();
  15018. t.join();
  15019. ASSERT_FALSE(svr.is_running());
  15020. });
  15021. svr.wait_until_ready();
  15022. const std::string body =
  15023. "This is the preamble. It is to be ignored, though it\r\n"
  15024. "is a handy place for composition agents to include an\r\n"
  15025. "explanatory note to non-MIME conformant readers.\r\n"
  15026. "\r\n"
  15027. "\r\n"
  15028. "--simple boundary\r\n"
  15029. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15030. ": BAD...\r\n"
  15031. "\r\n"
  15032. "value1\r\n"
  15033. "--simple boundary\r\n"
  15034. "Content-Disposition: form-data; name=\"field2\"; "
  15035. "filename=\"example.txt\"\r\n"
  15036. "\r\n"
  15037. "value2\r\n"
  15038. "--simple boundary--\r\n"
  15039. "This is the epilogue. It is also to be ignored.\r\n";
  15040. std::string content_type =
  15041. R"(multipart/form-data; boundary="simple boundary")";
  15042. Client cli(HOST, PORT);
  15043. auto res = cli.Post("/post", body, content_type.c_str());
  15044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15045. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15046. }
  15047. TEST(MultipartFormDataTest, WithPreamble) {
  15048. Server svr;
  15049. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15050. res.set_content("ok", "text/plain");
  15051. });
  15052. thread t = thread([&] { svr.listen(HOST, PORT); });
  15053. auto se = detail::scope_exit([&] {
  15054. svr.stop();
  15055. t.join();
  15056. ASSERT_FALSE(svr.is_running());
  15057. });
  15058. svr.wait_until_ready();
  15059. const std::string body =
  15060. "This is the preamble. It is to be ignored, though it\r\n"
  15061. "is a handy place for composition agents to include an\r\n"
  15062. "explanatory note to non-MIME conformant readers.\r\n"
  15063. "\r\n"
  15064. "\r\n"
  15065. "--simple boundary\r\n"
  15066. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15067. "\r\n"
  15068. "value1\r\n"
  15069. "--simple boundary\r\n"
  15070. "Content-Disposition: form-data; name=\"field2\"; "
  15071. "filename=\"example.txt\"\r\n"
  15072. "\r\n"
  15073. "value2\r\n"
  15074. "--simple boundary--\r\n"
  15075. "This is the epilogue. It is also to be ignored.\r\n";
  15076. std::string content_type =
  15077. R"(multipart/form-data; boundary="simple boundary")";
  15078. Client cli(HOST, PORT);
  15079. auto res = cli.Post("/post", body, content_type.c_str());
  15080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15081. EXPECT_EQ(StatusCode::OK_200, res->status);
  15082. }
  15083. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15084. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15085. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15086. const ContentReader &content_reader) {
  15087. if (req.is_multipart_form_data()) {
  15088. std::vector<FormData> items;
  15089. content_reader(
  15090. [&](const FormData &file) {
  15091. items.push_back(file);
  15092. return true;
  15093. },
  15094. [&](const char *data, size_t data_length) {
  15095. items.back().content.append(data, data_length);
  15096. return true;
  15097. });
  15098. EXPECT_TRUE(std::string(items[0].name) == "document");
  15099. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15100. EXPECT_TRUE(items[0].filename == "2MB_data");
  15101. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15102. EXPECT_TRUE(items[1].name == "hello");
  15103. EXPECT_TRUE(items[1].content == "world");
  15104. EXPECT_TRUE(items[1].filename == "");
  15105. EXPECT_TRUE(items[1].content_type == "");
  15106. } else {
  15107. std::string body;
  15108. content_reader([&](const char *data, size_t data_length) {
  15109. body.append(data, data_length);
  15110. return true;
  15111. });
  15112. }
  15113. });
  15114. auto port = svr.bind_to_any_port("localhost");
  15115. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15116. auto se = detail::scope_exit([&] {
  15117. svr.stop();
  15118. t.join();
  15119. ASSERT_FALSE(svr.is_running());
  15120. });
  15121. svr.wait_until_ready();
  15122. {
  15123. std::string data(1024 * 1024 * 2, '.');
  15124. std::stringstream buffer;
  15125. buffer << data;
  15126. SSLClient cli("localhost", port);
  15127. cli.enable_server_certificate_verification(false);
  15128. UploadFormDataItems items{
  15129. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15130. {"hello", "world", "", ""},
  15131. };
  15132. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15134. ASSERT_EQ(StatusCode::OK_200, res->status);
  15135. }
  15136. }
  15137. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15138. std::string data(1024 * 1024 * 2, '&');
  15139. std::stringstream buffer;
  15140. buffer << data;
  15141. Client cli("https://localhost:8080");
  15142. UploadFormDataItems items{
  15143. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15144. {"hello", "world", "", ""},
  15145. };
  15146. for (const char &c : " \t\r\n") {
  15147. auto res =
  15148. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15149. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15150. ASSERT_FALSE(res);
  15151. }
  15152. }
  15153. TEST(MultipartFormDataTest, PutFormData) {
  15154. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15155. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15156. const ContentReader &content_reader) {
  15157. if (req.is_multipart_form_data()) {
  15158. std::vector<FormData> items;
  15159. content_reader(
  15160. [&](const FormData &file) {
  15161. items.push_back(file);
  15162. return true;
  15163. },
  15164. [&](const char *data, size_t data_length) {
  15165. items.back().content.append(data, data_length);
  15166. return true;
  15167. });
  15168. EXPECT_TRUE(std::string(items[0].name) == "document");
  15169. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15170. EXPECT_TRUE(items[0].filename == "2MB_data");
  15171. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15172. EXPECT_TRUE(items[1].name == "hello");
  15173. EXPECT_TRUE(items[1].content == "world");
  15174. EXPECT_TRUE(items[1].filename == "");
  15175. EXPECT_TRUE(items[1].content_type == "");
  15176. } else {
  15177. std::string body;
  15178. content_reader([&](const char *data, size_t data_length) {
  15179. body.append(data, data_length);
  15180. return true;
  15181. });
  15182. }
  15183. });
  15184. auto port = svr.bind_to_any_port("localhost");
  15185. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15186. auto se = detail::scope_exit([&] {
  15187. svr.stop();
  15188. t.join();
  15189. ASSERT_FALSE(svr.is_running());
  15190. });
  15191. svr.wait_until_ready();
  15192. {
  15193. std::string data(1024 * 1024 * 2, '&');
  15194. std::stringstream buffer;
  15195. buffer << data;
  15196. SSLClient cli("localhost", port);
  15197. cli.enable_server_certificate_verification(false);
  15198. UploadFormDataItems items{
  15199. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15200. {"hello", "world", "", ""},
  15201. };
  15202. auto res = cli.Put("/put", items);
  15203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15204. ASSERT_EQ(StatusCode::OK_200, res->status);
  15205. }
  15206. }
  15207. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15208. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15209. svr.Put("/put_customboundary",
  15210. [&](const Request &req, const Response & /*res*/,
  15211. const ContentReader &content_reader) {
  15212. if (req.is_multipart_form_data()) {
  15213. std::vector<FormData> items;
  15214. content_reader(
  15215. [&](const FormData &file) {
  15216. items.push_back(file);
  15217. return true;
  15218. },
  15219. [&](const char *data, size_t data_length) {
  15220. items.back().content.append(data, data_length);
  15221. return true;
  15222. });
  15223. EXPECT_TRUE(std::string(items[0].name) == "document");
  15224. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15225. EXPECT_TRUE(items[0].filename == "2MB_data");
  15226. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15227. EXPECT_TRUE(items[1].name == "hello");
  15228. EXPECT_TRUE(items[1].content == "world");
  15229. EXPECT_TRUE(items[1].filename == "");
  15230. EXPECT_TRUE(items[1].content_type == "");
  15231. } else {
  15232. std::string body;
  15233. content_reader([&](const char *data, size_t data_length) {
  15234. body.append(data, data_length);
  15235. return true;
  15236. });
  15237. }
  15238. });
  15239. auto port = svr.bind_to_any_port("localhost");
  15240. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15241. auto se = detail::scope_exit([&] {
  15242. svr.stop();
  15243. t.join();
  15244. ASSERT_FALSE(svr.is_running());
  15245. });
  15246. svr.wait_until_ready();
  15247. {
  15248. std::string data(1024 * 1024 * 2, '&');
  15249. std::stringstream buffer;
  15250. buffer << data;
  15251. SSLClient cli("localhost", port);
  15252. cli.enable_server_certificate_verification(false);
  15253. UploadFormDataItems items{
  15254. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15255. {"hello", "world", "", ""},
  15256. };
  15257. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15259. ASSERT_EQ(StatusCode::OK_200, res->status);
  15260. }
  15261. }
  15262. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15263. std::string data(1024 * 1024 * 2, '&');
  15264. std::stringstream buffer;
  15265. buffer << data;
  15266. Client cli("https://localhost:8080");
  15267. cli.enable_server_certificate_verification(false);
  15268. UploadFormDataItems items{
  15269. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15270. {"hello", "world", "", ""},
  15271. };
  15272. for (const char &c : " \t\r\n") {
  15273. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15274. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15275. ASSERT_FALSE(res);
  15276. }
  15277. }
  15278. TEST(MultipartFormDataTest, AlternateFilename) {
  15279. auto handled = false;
  15280. Server svr;
  15281. svr.Post("/test", [&](const Request &req, Response &res) {
  15282. ASSERT_EQ(2u, req.form.files.size());
  15283. ASSERT_EQ(1u, req.form.fields.size());
  15284. // Test files
  15285. const auto &file1 = req.form.get_file("file1");
  15286. ASSERT_EQ("file1", file1.name);
  15287. ASSERT_EQ("A.txt", file1.filename);
  15288. ASSERT_EQ("text/plain", file1.content_type);
  15289. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15290. const auto &file2 = req.form.get_file("file2");
  15291. ASSERT_EQ("file2", file2.name);
  15292. ASSERT_EQ("a.html", file2.filename);
  15293. ASSERT_EQ("text/html", file2.content_type);
  15294. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15295. file2.content);
  15296. // Test text field
  15297. const auto &text = req.form.get_field("text");
  15298. ASSERT_EQ("text default", text);
  15299. res.set_content("ok", "text/plain");
  15300. handled = true;
  15301. });
  15302. thread t = thread([&] { svr.listen(HOST, PORT); });
  15303. auto se = detail::scope_exit([&] {
  15304. svr.stop();
  15305. t.join();
  15306. ASSERT_FALSE(svr.is_running());
  15307. ASSERT_TRUE(handled);
  15308. });
  15309. svr.wait_until_ready();
  15310. auto req = "POST /test HTTP/1.1\r\n"
  15311. "Host: localhost\r\n"
  15312. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15313. "Content-Length: 399\r\n"
  15314. "\r\n"
  15315. "----------\r\n"
  15316. "Content-Disposition: form-data; name=\"text\"\r\n"
  15317. "\r\n"
  15318. "text default\r\n"
  15319. "----------\r\n"
  15320. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15321. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15322. "Content-Type: text/plain\r\n"
  15323. "\r\n"
  15324. "Content of a.txt.\r\n"
  15325. "\r\n"
  15326. "----------\r\n"
  15327. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15328. "\"a.html\"\r\n"
  15329. "Content-Type: text/html\r\n"
  15330. "\r\n"
  15331. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15332. "\r\n"
  15333. "------------\r\n";
  15334. ASSERT_TRUE(send_request(1, req));
  15335. }
  15336. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15337. auto handled = false;
  15338. Server svr;
  15339. svr.Post("/test", [&](const Request &req, Response &res) {
  15340. // Case-insensitive "utf-8''" prefix with a long value
  15341. const auto &file = req.form.get_file("file1");
  15342. ASSERT_EQ("file1", file.name);
  15343. // 8000 chars exercises both the Content-Disposition parser and the
  15344. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15345. // Prior to the fix, std::regex_match on this header would cause O(N)
  15346. // stack recursion in libstdc++, leading to SIGSEGV.
  15347. std::string expected_filename(8000, 'A');
  15348. ASSERT_EQ(expected_filename, file.filename);
  15349. res.set_content("ok", "text/plain");
  15350. handled = true;
  15351. });
  15352. thread t = thread([&] { svr.listen(HOST, PORT); });
  15353. auto se = detail::scope_exit([&] {
  15354. svr.stop();
  15355. t.join();
  15356. ASSERT_FALSE(svr.is_running());
  15357. ASSERT_TRUE(handled);
  15358. });
  15359. svr.wait_until_ready();
  15360. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15361. // Regression test for GHSA-qq6v-r583-3h69
  15362. std::string long_filename(8000, 'A');
  15363. std::string body = "----------\r\n"
  15364. "Content-Disposition: form-data; name=\"file1\"; "
  15365. "filename*=\"Utf-8''" +
  15366. long_filename +
  15367. "\"\r\n"
  15368. "\r\n"
  15369. "hello\r\n"
  15370. "------------\r\n";
  15371. auto req = "POST /test HTTP/1.1\r\n"
  15372. "Host: localhost\r\n"
  15373. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15374. "Content-Length: " +
  15375. std::to_string(body.size()) + "\r\n\r\n" + body;
  15376. ASSERT_TRUE(send_request(1, req));
  15377. }
  15378. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15379. auto handled = false;
  15380. Server svr;
  15381. svr.Post("/test", [&](const Request &req, Response &) {
  15382. ASSERT_EQ(2u, req.form.fields.size());
  15383. const auto &text1 = req.form.get_field("text1");
  15384. ASSERT_EQ("text1", text1);
  15385. const auto &text2 = req.form.get_field("text2");
  15386. ASSERT_EQ("text2", text2);
  15387. handled = true;
  15388. });
  15389. thread t = thread([&] { svr.listen(HOST, PORT); });
  15390. auto se = detail::scope_exit([&] {
  15391. svr.stop();
  15392. t.join();
  15393. ASSERT_FALSE(svr.is_running());
  15394. ASSERT_TRUE(handled);
  15395. });
  15396. svr.wait_until_ready();
  15397. auto req = "POST /test HTTP/1.1\r\n"
  15398. "Host: localhost\r\n"
  15399. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15400. "Content-Length: 146\r\n"
  15401. "\r\n----------\r\n"
  15402. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15403. "\r\n"
  15404. "text1"
  15405. "\r\n----------\r\n"
  15406. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15407. "\r\n"
  15408. "text2"
  15409. "\r\n------------";
  15410. std::string response;
  15411. ASSERT_TRUE(send_request(1, req, &response));
  15412. ASSERT_EQ("200", response.substr(9, 3));
  15413. }
  15414. TEST(MultipartFormDataTest, ContentLength) {
  15415. auto handled = false;
  15416. Server svr;
  15417. svr.Post("/test", [&](const Request &req, Response &) {
  15418. ASSERT_EQ(2u, req.form.fields.size());
  15419. const auto &text1 = req.form.get_field("text1");
  15420. ASSERT_EQ("text1", text1);
  15421. const auto &text2 = req.form.get_field("text2");
  15422. ASSERT_EQ("text2", text2);
  15423. handled = true;
  15424. });
  15425. thread t = thread([&] { svr.listen(HOST, PORT); });
  15426. auto se = detail::scope_exit([&] {
  15427. svr.stop();
  15428. t.join();
  15429. ASSERT_FALSE(svr.is_running());
  15430. ASSERT_TRUE(handled);
  15431. });
  15432. svr.wait_until_ready();
  15433. auto req = "POST /test HTTP/1.1\r\n"
  15434. "Host: localhost\r\n"
  15435. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15436. "Content-Length: 167\r\n"
  15437. "\r\n----------\r\n"
  15438. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15439. "Content-Length: 5\r\n"
  15440. "\r\n"
  15441. "text1"
  15442. "\r\n----------\r\n"
  15443. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15444. "\r\n"
  15445. "text2"
  15446. "\r\n------------\r\n";
  15447. std::string response;
  15448. ASSERT_TRUE(send_request(1, req, &response));
  15449. ASSERT_EQ("200", response.substr(9, 3));
  15450. }
  15451. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15452. auto handled = false;
  15453. Server svr;
  15454. svr.Post("/test", [&](const Request &req, Response &) {
  15455. ASSERT_EQ(2u, req.form.fields.size());
  15456. const auto &text1 = req.form.get_field("text1");
  15457. ASSERT_EQ("text1", text1);
  15458. // TODO: Add header access for text fields if needed
  15459. const auto &text2 = req.form.get_field("text2");
  15460. ASSERT_EQ("text2", text2);
  15461. // TODO: Header access for text fields needs to be implemented
  15462. // auto &headers = it->second.headers;
  15463. // ASSERT_EQ(3U, headers.size());
  15464. // auto custom_header = headers.find("x-whatever");
  15465. // ASSERT_TRUE(custom_header != headers.end());
  15466. // ASSERT_NE("customvalue", custom_header->second);
  15467. // ASSERT_EQ("CustomValue", custom_header->second);
  15468. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15469. handled = true;
  15470. });
  15471. thread t = thread([&] { svr.listen(HOST, PORT); });
  15472. auto se = detail::scope_exit([&] {
  15473. svr.stop();
  15474. t.join();
  15475. ASSERT_FALSE(svr.is_running());
  15476. ASSERT_TRUE(handled);
  15477. });
  15478. svr.wait_until_ready();
  15479. auto req = "POST /test HTTP/1.1\r\n"
  15480. "Host: localhost\r\n"
  15481. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15482. "Content-Length: 232\r\n"
  15483. "\r\n----------\r\n"
  15484. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15485. "Content-Length: 5\r\n"
  15486. "X-Test: 1\r\n"
  15487. "\r\n"
  15488. "text1"
  15489. "\r\n----------\r\n"
  15490. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15491. "Content-Type: text/plain\r\n"
  15492. "X-Whatever: CustomValue\r\n"
  15493. "\r\n"
  15494. "text2"
  15495. "\r\n------------\r\n"
  15496. "That should be disregarded. Not even read";
  15497. std::string response;
  15498. ASSERT_TRUE(send_request(1, req, &response));
  15499. ASSERT_EQ("200", response.substr(9, 3));
  15500. }
  15501. TEST(MultipartFormDataTest, LargeHeader) {
  15502. auto handled = false;
  15503. Server svr;
  15504. svr.Post("/test", [&](const Request &req, Response &) {
  15505. ASSERT_EQ(1u, req.form.fields.size());
  15506. const auto &text = req.form.get_field("name1");
  15507. ASSERT_EQ("text1", text);
  15508. handled = true;
  15509. });
  15510. thread t = thread([&] { svr.listen(HOST, PORT); });
  15511. auto se = detail::scope_exit([&] {
  15512. svr.stop();
  15513. t.join();
  15514. ASSERT_FALSE(svr.is_running());
  15515. ASSERT_TRUE(handled);
  15516. });
  15517. svr.wait_until_ready();
  15518. auto boundary = std::string("cpp-httplib-multipart-data");
  15519. std::string content = "--" + boundary +
  15520. "\r\n"
  15521. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15522. "\r\n"
  15523. "text1\r\n"
  15524. "--" +
  15525. boundary + "--\r\n";
  15526. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15527. "Host: localhost\r\n"
  15528. "Content-Type: multipart/form-data;boundary=" +
  15529. boundary +
  15530. "\r\n"
  15531. "Content-Length: " +
  15532. std::to_string(content.size()) +
  15533. "\r\n"
  15534. "Dummy-Header: ";
  15535. std::string header_suffix = "\r\n"
  15536. "\r\n";
  15537. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15538. size_t header_dummy_size =
  15539. read_buff_size -
  15540. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15541. auto header_dummy = std::string(header_dummy_size, '@');
  15542. auto req = header_prefix + header_dummy + header_suffix + content;
  15543. std::string response;
  15544. ASSERT_TRUE(send_request(1, req, &response));
  15545. ASSERT_EQ("200", response.substr(9, 3));
  15546. }
  15547. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15548. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15549. // (not chunked Transfer-Encoding) after the streaming refactor.
  15550. auto handled = false;
  15551. Server svr;
  15552. svr.Post("/upload", [&](const Request &req, Response &res) {
  15553. auto cl_it = req.headers.find("Content-Length");
  15554. EXPECT_TRUE(cl_it != req.headers.end());
  15555. auto te_it = req.headers.find("Transfer-Encoding");
  15556. EXPECT_TRUE(te_it == req.headers.end());
  15557. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15558. res.set_content("ok", "text/plain");
  15559. handled = true;
  15560. });
  15561. auto port = svr.bind_to_any_port(HOST);
  15562. auto t = thread([&] { svr.listen_after_bind(); });
  15563. auto se = detail::scope_exit([&] {
  15564. svr.stop();
  15565. t.join();
  15566. ASSERT_FALSE(svr.is_running());
  15567. ASSERT_TRUE(handled);
  15568. });
  15569. svr.wait_until_ready();
  15570. UploadFormDataItems items = {
  15571. {"field1", "hello", "", "text/plain"},
  15572. {"file1", "world", "test.txt", "application/octet-stream"},
  15573. };
  15574. Client cli(HOST, port);
  15575. auto res = cli.Post("/upload", {}, items);
  15576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15577. EXPECT_EQ(StatusCode::OK_200, res->status);
  15578. }
  15579. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15580. // Verify that make_multipart_content_provider coalesces many small segments
  15581. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15582. constexpr size_t kItemCount = 1000;
  15583. UploadFormDataItems items;
  15584. items.reserve(kItemCount);
  15585. for (size_t i = 0; i < kItemCount; i++) {
  15586. items.push_back(
  15587. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15588. }
  15589. const std::string boundary = "----test-boundary";
  15590. auto content_length = detail::get_multipart_content_length(items, boundary);
  15591. auto provider = detail::make_multipart_content_provider(items, boundary);
  15592. // Drive the provider the same way write_content_with_progress does
  15593. size_t write_count = 0;
  15594. size_t total_bytes = 0;
  15595. DataSink sink;
  15596. size_t offset = 0;
  15597. sink.write = [&](const char *d, size_t l) -> bool {
  15598. (void)d;
  15599. write_count++;
  15600. total_bytes += l;
  15601. offset += l;
  15602. return true;
  15603. };
  15604. sink.is_writable = []() -> bool { return true; };
  15605. while (offset < content_length) {
  15606. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15607. }
  15608. EXPECT_EQ(content_length, total_bytes);
  15609. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15610. // With buffering into 64KB blocks, write_count should be much smaller.
  15611. auto segment_count = 3 * kItemCount + 1;
  15612. EXPECT_LT(write_count, segment_count / 10);
  15613. }
  15614. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15615. // Integration test: send many UploadFormDataItems and verify the server
  15616. // receives all of them correctly (#2410).
  15617. constexpr size_t kItemCount = 500;
  15618. auto handled = false;
  15619. Server svr;
  15620. svr.Post("/upload", [&](const Request &req, Response &res) {
  15621. EXPECT_EQ(kItemCount, req.form.fields.size());
  15622. for (size_t i = 0; i < kItemCount; i++) {
  15623. auto key = "field" + std::to_string(i);
  15624. auto val = "value" + std::to_string(i);
  15625. auto it = req.form.fields.find(key);
  15626. if (it != req.form.fields.end()) {
  15627. EXPECT_EQ(val, it->second.content);
  15628. } else {
  15629. ADD_FAILURE() << "Missing field: " << key;
  15630. }
  15631. }
  15632. res.set_content("ok", "text/plain");
  15633. handled = true;
  15634. });
  15635. auto port = svr.bind_to_any_port(HOST);
  15636. auto t = thread([&] { svr.listen_after_bind(); });
  15637. auto se = detail::scope_exit([&] {
  15638. svr.stop();
  15639. t.join();
  15640. ASSERT_FALSE(svr.is_running());
  15641. ASSERT_TRUE(handled);
  15642. });
  15643. svr.wait_until_ready();
  15644. UploadFormDataItems items;
  15645. items.reserve(kItemCount);
  15646. for (size_t i = 0; i < kItemCount; i++) {
  15647. items.push_back(
  15648. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15649. }
  15650. Client cli(HOST, port);
  15651. auto res = cli.Post("/upload", items);
  15652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15653. EXPECT_EQ(StatusCode::OK_200, res->status);
  15654. }
  15655. TEST(MultipartFormDataTest, MakeFileProvider) {
  15656. // Verify make_file_provider sends a file's contents correctly.
  15657. const std::string file_content(4096, 'Z');
  15658. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15659. {
  15660. std::ofstream ofs(tmp_path, std::ios::binary);
  15661. ofs.write(file_content.data(),
  15662. static_cast<std::streamsize>(file_content.size()));
  15663. }
  15664. auto handled = false;
  15665. Server svr;
  15666. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15667. const ContentReader &content_reader) {
  15668. ASSERT_TRUE(req.is_multipart_form_data());
  15669. std::vector<FormData> items;
  15670. content_reader(
  15671. [&](const FormData &file) {
  15672. items.push_back(file);
  15673. return true;
  15674. },
  15675. [&](const char *data, size_t data_length) {
  15676. items.back().content.append(data, data_length);
  15677. return true;
  15678. });
  15679. ASSERT_EQ(1u, items.size());
  15680. EXPECT_EQ("myfile", items[0].name);
  15681. EXPECT_EQ("data.bin", items[0].filename);
  15682. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15683. EXPECT_EQ(file_content, items[0].content);
  15684. handled = true;
  15685. });
  15686. auto port = svr.bind_to_any_port(HOST);
  15687. auto t = thread([&] { svr.listen_after_bind(); });
  15688. auto se = detail::scope_exit([&] {
  15689. svr.stop();
  15690. t.join();
  15691. ASSERT_FALSE(svr.is_running());
  15692. ASSERT_TRUE(handled);
  15693. std::remove(tmp_path.c_str());
  15694. });
  15695. svr.wait_until_ready();
  15696. FormDataProviderItems providers;
  15697. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15698. "application/octet-stream"));
  15699. Client cli(HOST, port);
  15700. auto res = cli.Post("/upload", {}, {}, providers);
  15701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15702. EXPECT_EQ(StatusCode::OK_200, res->status);
  15703. }
  15704. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15705. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15706. // (100) headers is rejected with a 400 Bad Request response.
  15707. Server svr;
  15708. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15709. res.set_content("ok", "text/plain");
  15710. });
  15711. thread t = thread([&] { svr.listen(HOST, PORT); });
  15712. auto se = detail::scope_exit([&] {
  15713. svr.stop();
  15714. t.join();
  15715. ASSERT_FALSE(svr.is_running());
  15716. });
  15717. svr.wait_until_ready();
  15718. // Build a multipart part with 101 custom headers (exceeding
  15719. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15720. std::stringstream body;
  15721. body << "--simpleboundary\r\n"
  15722. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15723. for (int i = 0; i < 101; i++) {
  15724. body << "X-Custom-Header-" << i << ": value\r\n";
  15725. }
  15726. body << "\r\n"
  15727. << "value1\r\n"
  15728. << "--simpleboundary--\r\n";
  15729. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15730. Client cli(HOST, PORT);
  15731. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15733. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15734. }
  15735. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15736. // A body that never contains the declared boundary must not be accumulated
  15737. // while the parser waits for it. Buffering it would also make every read
  15738. // rescan everything seen so far, which is quadratic in the body size.
  15739. Server svr;
  15740. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15741. res.set_content("ok", "text/plain");
  15742. });
  15743. auto port = svr.bind_to_any_port(HOST);
  15744. thread t = thread([&] { svr.listen_after_bind(); });
  15745. auto se = detail::scope_exit([&] {
  15746. svr.stop();
  15747. t.join();
  15748. ASSERT_FALSE(svr.is_running());
  15749. });
  15750. svr.wait_until_ready();
  15751. Client cli(HOST, port);
  15752. cli.set_read_timeout(60, 0);
  15753. cli.set_write_timeout(60, 0);
  15754. // '-' is the worst case: it matches the first character of the boundary, so
  15755. // every position has to be checked against it.
  15756. auto post_dashes = [&](size_t size) {
  15757. const std::string body(size, '-');
  15758. auto start = std::chrono::steady_clock::now();
  15759. auto res =
  15760. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15761. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15762. std::chrono::steady_clock::now() - start)
  15763. .count();
  15764. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15765. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15766. return ms;
  15767. };
  15768. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15769. // Windows.
  15770. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15771. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15772. // Comparing the two sizes rather than checking an absolute duration keeps
  15773. // this meaningful across build types and CI load, both of which move the
  15774. // absolute numbers by more than an order of magnitude. Four times the bytes
  15775. // costs about four times the time when parsing is linear, and about sixteen
  15776. // times when the body is buffered and rescanned.
  15777. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15778. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15779. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15780. << "ms, which suggests the body is being buffered and rescanned";
  15781. }
  15782. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15783. // A boundary can only be followed by CRLF or by "--", so anything else is
  15784. // malformed no matter what comes next. The parser must say so right away
  15785. // instead of buffering the rest of the declared body.
  15786. Server svr;
  15787. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15788. res.set_content("ok", "text/plain");
  15789. });
  15790. auto port = svr.bind_to_any_port(HOST);
  15791. thread t = thread([&] { svr.listen_after_bind(); });
  15792. auto se = detail::scope_exit([&] {
  15793. svr.stop();
  15794. t.join();
  15795. ASSERT_FALSE(svr.is_running());
  15796. });
  15797. svr.wait_until_ready();
  15798. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15799. // buffers instead of failing would still be waiting for the remaining bytes.
  15800. const std::string body = "--zzzz\r\n"
  15801. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15802. "\r\n"
  15803. "text1"
  15804. "\r\n--zzzzXX";
  15805. const std::string req = "POST /post HTTP/1.1\r\n"
  15806. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15807. "Content-Length: 1048576\r\n"
  15808. "\r\n" +
  15809. body;
  15810. std::string response;
  15811. ASSERT_TRUE(send_request(3, req, &response, port));
  15812. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15813. EXPECT_EQ("400", response.substr(9, 3));
  15814. }
  15815. // Posts a multipart body split into two writes, so that the server sees the
  15816. // split at whatever offset the caller chose, and expects the single "text1"
  15817. // field to come through.
  15818. static void expect_split_multipart_ok(const std::string &body1,
  15819. const std::string &body2) {
  15820. auto handled = false;
  15821. Server svr;
  15822. svr.Post("/post", [&](const Request &req, Response &) {
  15823. EXPECT_EQ(1u, req.form.fields.size());
  15824. EXPECT_EQ("text1", req.form.get_field("text1"));
  15825. handled = true;
  15826. });
  15827. auto port = svr.bind_to_any_port(HOST);
  15828. thread t = thread([&] { svr.listen_after_bind(); });
  15829. auto se = detail::scope_exit([&] {
  15830. svr.stop();
  15831. t.join();
  15832. ASSERT_FALSE(svr.is_running());
  15833. ASSERT_TRUE(handled);
  15834. });
  15835. svr.wait_until_ready();
  15836. // "Connection: close" makes the server close once it has answered, so the
  15837. // response drain ends immediately instead of idling until the read timeout.
  15838. const std::string head =
  15839. "POST /post HTTP/1.1\r\n"
  15840. "Host: localhost\r\n"
  15841. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15842. "Connection: close\r\n"
  15843. "Content-Length: " +
  15844. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15845. std::string response;
  15846. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15847. ASSERT_GE(response.size(), 12u) << "no response";
  15848. EXPECT_EQ("200", response.substr(9, 3));
  15849. }
  15850. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15851. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15852. // ignored, including when it does not arrive in the same read as the
  15853. // close-delimiter itself.
  15854. expect_split_multipart_ok("--zzzz\r\n"
  15855. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15856. "\r\n"
  15857. "text1"
  15858. "\r\n--zzzz--",
  15859. "\r\nthis epilogue must be ignored\r\n");
  15860. }
  15861. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15862. // The initial boundary may be preceded by a preamble of any length and may
  15863. // straddle a read boundary. Discarding data while waiting for it must not
  15864. // throw away a partial boundary sitting at the end of the buffer.
  15865. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15866. "zz\r\n"
  15867. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15868. "\r\n"
  15869. "text1"
  15870. "\r\n--zzzz--\r\n");
  15871. }
  15872. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15873. // The received boundary was only checked for being non-empty, so it could be
  15874. // as long as a header is allowed to be. The parser scans the body for
  15875. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15876. // costs a nearly full comparison at nearly every position, making the
  15877. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15878. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15879. Server svr;
  15880. svr.Post("/post", [](const Request &req, Response &res) {
  15881. EXPECT_EQ(1u, req.form.fields.size());
  15882. EXPECT_EQ("text1", req.form.get_field("text1"));
  15883. res.set_content("ok", "text/plain");
  15884. });
  15885. auto port = svr.bind_to_any_port(HOST);
  15886. thread t = thread([&] { svr.listen_after_bind(); });
  15887. auto se = detail::scope_exit([&] {
  15888. svr.stop();
  15889. t.join();
  15890. ASSERT_FALSE(svr.is_running());
  15891. });
  15892. svr.wait_until_ready();
  15893. Client cli(HOST, port);
  15894. auto post_with_boundary_of_length = [&](size_t len) {
  15895. const std::string boundary(len, 'a');
  15896. const std::string body =
  15897. "--" + boundary +
  15898. "\r\n"
  15899. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15900. "\r\n"
  15901. "text1"
  15902. "\r\n--" +
  15903. boundary + "--\r\n";
  15904. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15905. };
  15906. auto res = post_with_boundary_of_length(70);
  15907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15908. EXPECT_EQ(StatusCode::OK_200, res->status);
  15909. res = post_with_boundary_of_length(71);
  15910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15911. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15912. }
  15913. TEST(MakeFileBodyTest, Basic) {
  15914. const std::string file_content(4096, 'Z');
  15915. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15916. {
  15917. std::ofstream ofs(tmp_path, std::ios::binary);
  15918. ofs.write(file_content.data(),
  15919. static_cast<std::streamsize>(file_content.size()));
  15920. }
  15921. auto handled = false;
  15922. Server svr;
  15923. svr.Post("/upload", [&](const Request &req, Response &res) {
  15924. EXPECT_EQ(file_content, req.body);
  15925. handled = true;
  15926. res.status = StatusCode::OK_200;
  15927. });
  15928. auto port = svr.bind_to_any_port(HOST);
  15929. auto t = thread([&] { svr.listen_after_bind(); });
  15930. auto se = detail::scope_exit([&] {
  15931. svr.stop();
  15932. t.join();
  15933. ASSERT_FALSE(svr.is_running());
  15934. ASSERT_TRUE(handled);
  15935. std::remove(tmp_path.c_str());
  15936. });
  15937. svr.wait_until_ready();
  15938. auto fb = make_file_body(tmp_path);
  15939. ASSERT_GT(fb.first, 0u);
  15940. Client cli(HOST, port);
  15941. auto res =
  15942. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15944. EXPECT_EQ(StatusCode::OK_200, res->status);
  15945. }
  15946. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15947. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15948. {
  15949. std::ofstream ofs(path, std::ios::binary);
  15950. const std::string content(100, 'A');
  15951. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15952. }
  15953. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15954. auto body = make_file_body(path);
  15955. ASSERT_EQ(100u, body.first);
  15956. ASSERT_TRUE(static_cast<bool>(body.second));
  15957. // Rewritten shorter after its length was measured - and, on a server, after
  15958. // that length has already gone out as Content-Length.
  15959. {
  15960. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15961. const std::string content(10, 'A');
  15962. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15963. }
  15964. std::string written;
  15965. DataSink sink;
  15966. sink.write = [&](const char *d, size_t l) {
  15967. written.append(d, l);
  15968. return true;
  15969. };
  15970. // The provider has to report failure. write_content_with_progress() advances
  15971. // its offset only by what was written, so a provider that returns true
  15972. // without completing the length it promised is called again straight away,
  15973. // and again.
  15974. EXPECT_FALSE(body.second(0, body.first, sink));
  15975. EXPECT_EQ(std::string(10, 'A'), written);
  15976. }
  15977. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15978. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15979. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15980. {
  15981. std::ofstream ofs(path, std::ios::binary);
  15982. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15983. }
  15984. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15985. auto body = make_file_body(path);
  15986. ASSERT_EQ(content.size(), body.first);
  15987. ASSERT_TRUE(static_cast<bool>(body.second));
  15988. std::string written;
  15989. DataSink sink;
  15990. sink.write = [&](const char *d, size_t l) {
  15991. written.append(d, l);
  15992. return true;
  15993. };
  15994. EXPECT_TRUE(body.second(0, body.first, sink));
  15995. EXPECT_EQ(content, written);
  15996. }
  15997. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15998. static constexpr unsigned int number_of_tasks{1000000};
  15999. std::atomic_uint count{0};
  16000. std::unique_ptr<TaskQueue> task_queue{
  16001. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16002. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16003. auto queued = task_queue->enqueue(
  16004. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16005. EXPECT_TRUE(queued);
  16006. }
  16007. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16008. task_queue->shutdown();
  16009. #else
  16010. EXPECT_NO_THROW(task_queue->shutdown());
  16011. #endif
  16012. EXPECT_EQ(number_of_tasks, count.load());
  16013. }
  16014. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16015. static constexpr unsigned int number_of_tasks{1000000};
  16016. static constexpr unsigned int qlimit{2};
  16017. unsigned int queued_count{0};
  16018. std::atomic_uint count{0};
  16019. std::unique_ptr<TaskQueue> task_queue{
  16020. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16021. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16022. if (task_queue->enqueue(
  16023. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16024. queued_count++;
  16025. }
  16026. }
  16027. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16028. task_queue->shutdown();
  16029. #else
  16030. EXPECT_NO_THROW(task_queue->shutdown());
  16031. #endif
  16032. EXPECT_EQ(queued_count, count.load());
  16033. EXPECT_TRUE(queued_count <= number_of_tasks);
  16034. EXPECT_TRUE(queued_count >= qlimit);
  16035. }
  16036. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16037. // Use a short idle timeout so a dynamic thread spawns, times out and
  16038. // exits during the test, and the pool keeps working afterwards.
  16039. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16040. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16041. /*idle_timeout_sec=*/1}};
  16042. std::atomic_uint count{0};
  16043. std::condition_variable cv;
  16044. std::mutex mtx;
  16045. bool release = false;
  16046. // Block the base thread so the second task spawns a dynamic thread.
  16047. EXPECT_TRUE(task_queue->enqueue([&] {
  16048. std::unique_lock<std::mutex> lock(mtx);
  16049. while (!release) {
  16050. cv.wait(lock);
  16051. }
  16052. count++;
  16053. }));
  16054. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16055. // Let the dynamic thread finish its task and exceed the idle timeout.
  16056. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16057. {
  16058. std::unique_lock<std::mutex> lock(mtx);
  16059. release = true;
  16060. }
  16061. cv.notify_all();
  16062. // The pool must still accept and run tasks after the dynamic thread exited.
  16063. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16064. task_queue->shutdown();
  16065. EXPECT_EQ(3u, count.load());
  16066. }
  16067. TEST(TaskQueueTest, MaxQueuedRequests) {
  16068. static constexpr unsigned int qlimit{3};
  16069. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16070. std::condition_variable sem_cv;
  16071. std::mutex sem_mtx;
  16072. int credits = 0;
  16073. bool queued;
  16074. /* Fill up the queue with tasks that will block until we give them credits to
  16075. * complete. */
  16076. for (unsigned int n = 0; n <= qlimit;) {
  16077. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16078. std::unique_lock<std::mutex> lock(sem_mtx);
  16079. while (credits <= 0) {
  16080. sem_cv.wait(lock);
  16081. }
  16082. /* Consume the credit and signal the test code if they are all gone. */
  16083. if (--credits == 0) { sem_cv.notify_one(); }
  16084. });
  16085. if (n < qlimit) {
  16086. /* The first qlimit enqueues must succeed. */
  16087. EXPECT_TRUE(queued);
  16088. } else {
  16089. /* The last one will succeed only when the worker thread
  16090. * starts and dequeues the first blocking task. Although
  16091. * not necessary for the correctness of this test, we sleep for
  16092. * a short while to avoid busy waiting. */
  16093. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16094. }
  16095. if (queued) { n++; }
  16096. }
  16097. /* Further enqueues must fail since the queue is full. */
  16098. for (auto i = 0; i < 4; i++) {
  16099. queued = task_queue->enqueue([] {});
  16100. EXPECT_FALSE(queued);
  16101. }
  16102. /* Give the credits to allow the previous tasks to complete. */
  16103. {
  16104. std::unique_lock<std::mutex> lock(sem_mtx);
  16105. credits += qlimit + 1;
  16106. }
  16107. sem_cv.notify_all();
  16108. /* Wait for all the credits to be consumed. */
  16109. {
  16110. std::unique_lock<std::mutex> lock(sem_mtx);
  16111. while (credits > 0) {
  16112. sem_cv.wait(lock);
  16113. }
  16114. }
  16115. /* Check that we are able again to enqueue at least qlimit tasks. */
  16116. for (unsigned int i = 0; i < qlimit; i++) {
  16117. queued = task_queue->enqueue([] {});
  16118. EXPECT_TRUE(queued);
  16119. }
  16120. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16121. task_queue->shutdown();
  16122. #else
  16123. EXPECT_NO_THROW(task_queue->shutdown());
  16124. #endif
  16125. }
  16126. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16127. Server svr;
  16128. std::string method;
  16129. std::string body;
  16130. auto has_content_length = false;
  16131. auto has_transfer_encoding = false;
  16132. std::atomic<int> bad_requests{0};
  16133. // Leftover body bytes get parsed as a malformed request and answered with
  16134. // 400
  16135. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16136. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16137. });
  16138. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16139. res.set_redirect("/down", StatusCode::SeeOther_303);
  16140. });
  16141. svr.Get("/down", [&](const Request &req, Response &res) {
  16142. method = req.method;
  16143. body = req.body;
  16144. has_content_length = req.has_header("Content-Length");
  16145. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16146. res.set_content("ok", "text/plain");
  16147. });
  16148. auto port = svr.bind_to_any_port(HOST);
  16149. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16150. auto se = detail::scope_exit([&] {
  16151. svr.stop();
  16152. thread.join();
  16153. ASSERT_FALSE(svr.is_running());
  16154. });
  16155. svr.wait_until_ready();
  16156. const std::string payload = "SECRET-BODY";
  16157. auto check = [&](Client &cli, const Result &res) {
  16158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16159. EXPECT_EQ(StatusCode::OK_200, res->status);
  16160. EXPECT_EQ("ok", res->body);
  16161. EXPECT_EQ("GET", method);
  16162. EXPECT_TRUE(body.empty());
  16163. EXPECT_FALSE(has_content_length);
  16164. EXPECT_FALSE(has_transfer_encoding);
  16165. // Nothing of the original body may be left on the connection
  16166. auto res2 = cli.Get("/down");
  16167. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16168. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16169. EXPECT_EQ("ok", res2->body);
  16170. EXPECT_EQ(0, bad_requests);
  16171. };
  16172. // With content length
  16173. {
  16174. Client cli(HOST, port);
  16175. cli.set_keep_alive(true);
  16176. cli.set_follow_location(true);
  16177. auto res = cli.Post(
  16178. "/up", payload.size(),
  16179. [&](size_t offset, size_t length, DataSink &sink) {
  16180. return sink.write(payload.data() + offset, length);
  16181. },
  16182. "text/plain");
  16183. check(cli, res);
  16184. }
  16185. // Without content length (chunked)
  16186. {
  16187. Client cli(HOST, port);
  16188. cli.set_keep_alive(true);
  16189. cli.set_follow_location(true);
  16190. auto res = cli.Post(
  16191. "/up",
  16192. [&](size_t /*offset*/, DataSink &sink) {
  16193. sink.write(payload.data(), payload.size());
  16194. sink.done();
  16195. return true;
  16196. },
  16197. "text/plain");
  16198. check(cli, res);
  16199. }
  16200. }
  16201. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16202. Server svr;
  16203. std::string target;
  16204. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16205. // Echo the still-encoded name back in the Location
  16206. const std::string prefix = "/start/";
  16207. res.status = StatusCode::Found_302;
  16208. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16209. });
  16210. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16211. target = req.target;
  16212. res.set_content("ok", "text/plain");
  16213. });
  16214. auto port = svr.bind_to_any_port(HOST);
  16215. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16216. auto se = detail::scope_exit([&] {
  16217. svr.stop();
  16218. thread.join();
  16219. ASSERT_FALSE(svr.is_running());
  16220. });
  16221. svr.wait_until_ready();
  16222. // Decoding the Location path would turn the first four into a path
  16223. // separator, a query delimiter, a fragment delimiter and a different
  16224. // percent-encoded octet. The rest must keep reaching the server as they are.
  16225. const std::vector<std::string> names = {
  16226. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16227. };
  16228. for (auto path_encode : {true, false}) {
  16229. Client cli(HOST, port);
  16230. cli.set_follow_location(true);
  16231. cli.set_path_encode(path_encode);
  16232. for (const auto &name : names) {
  16233. target.clear();
  16234. auto res = cli.Get("/start/" + name);
  16235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16236. EXPECT_EQ(StatusCode::OK_200, res->status);
  16237. EXPECT_EQ("/dest/" + name, target);
  16238. }
  16239. }
  16240. }
  16241. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16242. Server svr;
  16243. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16244. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16245. });
  16246. svr.Get("/hello", [](const Request &req, Response &res) {
  16247. res.set_content(req.get_param_value("key"), "text/plain");
  16248. });
  16249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16250. auto se = detail::scope_exit([&] {
  16251. svr.stop();
  16252. thread.join();
  16253. ASSERT_FALSE(svr.is_running());
  16254. });
  16255. svr.wait_until_ready();
  16256. {
  16257. Client cli(HOST, PORT);
  16258. cli.set_follow_location(true);
  16259. auto res = cli.Get("/");
  16260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16261. EXPECT_EQ(StatusCode::OK_200, res->status);
  16262. EXPECT_EQ("val&key2=val2", res->body);
  16263. }
  16264. }
  16265. #endif
  16266. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16267. Server svr;
  16268. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16269. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16270. });
  16271. svr.Get("/hello", [](const Request &req, Response &res) {
  16272. res.set_content(req.get_param_value("key"), "text/plain");
  16273. });
  16274. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16275. auto se = detail::scope_exit([&] {
  16276. svr.stop();
  16277. thread.join();
  16278. ASSERT_FALSE(svr.is_running());
  16279. });
  16280. svr.wait_until_ready();
  16281. {
  16282. Client cli(HOST, PORT);
  16283. cli.set_follow_location(true);
  16284. auto res = cli.Get("/");
  16285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16286. EXPECT_EQ(StatusCode::OK_200, res->status);
  16287. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16288. }
  16289. }
  16290. TEST(RedirectTest, RedirectWithPlusInPath) {
  16291. Server svr;
  16292. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16293. res.set_redirect("/a+b");
  16294. });
  16295. // Route pattern uses regex; escape + as \\+
  16296. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16297. res.set_content(req.path, "text/plain");
  16298. });
  16299. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16300. auto se = detail::scope_exit([&] {
  16301. svr.stop();
  16302. thread.join();
  16303. ASSERT_FALSE(svr.is_running());
  16304. });
  16305. svr.wait_until_ready();
  16306. {
  16307. Client cli(HOST, PORT);
  16308. cli.set_follow_location(true);
  16309. auto res = cli.Get("/");
  16310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16311. EXPECT_EQ(StatusCode::OK_200, res->status);
  16312. EXPECT_EQ("/a+b", res->body);
  16313. }
  16314. }
  16315. TEST(RedirectTest, ResolveRelativeLocation) {
  16316. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16317. const std::vector<std::pair<std::string, std::string>> cases = {
  16318. {"g", "/b/c/g"},
  16319. {"./g", "/b/c/g"},
  16320. {"g/", "/b/c/g/"},
  16321. {"?y", "/b/c/d;p?y"},
  16322. {"g?y", "/b/c/g?y"},
  16323. {"#s", "/b/c/d;p?q#s"},
  16324. {"g#s", "/b/c/g#s"},
  16325. {"g?y#s", "/b/c/g?y#s"},
  16326. {";x", "/b/c/;x"},
  16327. {"g;x", "/b/c/g;x"},
  16328. {".", "/b/c/"},
  16329. {"./", "/b/c/"},
  16330. {"..", "/b/"},
  16331. {"../", "/b/"},
  16332. {"../g", "/b/g"},
  16333. {"../..", "/"},
  16334. {"../../", "/"},
  16335. {"../../g", "/g"},
  16336. {"../../../g", "/g"},
  16337. {"g.", "/b/c/g."},
  16338. {".g", "/b/c/.g"},
  16339. {"g..", "/b/c/g.."},
  16340. {"..g", "/b/c/..g"},
  16341. {"./../g", "/b/g"},
  16342. {"./g/.", "/b/c/g/"},
  16343. {"g/./h", "/b/c/g/h"},
  16344. {"g/../h", "/b/c/h"},
  16345. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16346. {"g;x=1/../y", "/b/c/y"},
  16347. {"g?y/./x", "/b/c/g?y/./x"},
  16348. {"g#s/../x", "/b/c/g#s/../x"},
  16349. // Not relative-path references, so left for parse_url.
  16350. {"/g", "/g"},
  16351. {"//g", "//g"},
  16352. {"http://g/x", "http://g/x"},
  16353. {"g:h", "g:h"},
  16354. };
  16355. for (const auto &c : cases) {
  16356. EXPECT_EQ(c.second,
  16357. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16358. << c.first;
  16359. }
  16360. }
  16361. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16362. Server svr;
  16363. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16364. res.set_redirect(req.get_param_value("to"));
  16365. });
  16366. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16367. res.set_content(req.target, "text/plain");
  16368. });
  16369. svr.Get("/other", [](const Request &req, Response &res) {
  16370. res.set_content(req.target, "text/plain");
  16371. });
  16372. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16373. auto se = detail::scope_exit([&] {
  16374. svr.stop();
  16375. thread.join();
  16376. ASSERT_FALSE(svr.is_running());
  16377. });
  16378. svr.wait_until_ready();
  16379. const std::vector<std::pair<std::string, std::string>> cases = {
  16380. {"next", "/dir/next"},
  16381. {"./next?x=1", "/dir/next?x=1"},
  16382. {"../other", "/other"},
  16383. };
  16384. for (const auto &c : cases) {
  16385. Client cli(HOST, PORT);
  16386. cli.set_follow_location(true);
  16387. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16388. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16389. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16390. EXPECT_EQ(c.second, res->body) << c.first;
  16391. }
  16392. }
  16393. #ifdef CPPHTTPLIB_SSL_ENABLED
  16394. TEST(RedirectTest, Issue2185_Online) {
  16395. SSLClient client("github.com");
  16396. client.set_follow_location(true);
  16397. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16398. "Coollab-Windows.zip");
  16399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16400. EXPECT_EQ(StatusCode::OK_200, res->status);
  16401. EXPECT_EQ(9920427U, res->body.size());
  16402. }
  16403. #endif
  16404. TEST(VulnerabilityTest, CRLFInjection) {
  16405. Server svr;
  16406. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16407. res.set_content("Hello 1", "text/plain");
  16408. });
  16409. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16410. res.set_content("Hello 2", "text/plain");
  16411. });
  16412. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16413. res.set_content("Hello 3", "text/plain");
  16414. });
  16415. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16416. res.set_content("Hello 4", "text/plain");
  16417. });
  16418. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16419. for (const auto &x : req.headers) {
  16420. auto key = x.first;
  16421. EXPECT_STRNE("evil", key.c_str());
  16422. }
  16423. });
  16424. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16425. auto se = detail::scope_exit([&] {
  16426. svr.stop();
  16427. thread.join();
  16428. ASSERT_FALSE(svr.is_running());
  16429. });
  16430. svr.wait_until_ready();
  16431. {
  16432. Client cli(HOST, PORT);
  16433. cli.Post("/test1", "A=B",
  16434. "application/x-www-form-urlencoded\r\nevil: hello1");
  16435. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16436. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16437. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16438. }
  16439. }
  16440. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16441. auto server_thread = std::thread([] {
  16442. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16443. default_socket_options(srv);
  16444. sockaddr_in addr{};
  16445. addr.sin_family = AF_INET;
  16446. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16447. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16448. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16449. ::listen(srv, 1);
  16450. sockaddr_in cli_addr{};
  16451. socklen_t cli_len = sizeof(cli_addr);
  16452. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16453. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16454. std::string buf_all;
  16455. char buf[2048];
  16456. ssize_t n;
  16457. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16458. buf_all.append(buf, static_cast<size_t>(n));
  16459. size_t pos;
  16460. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16461. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16462. auto e = request_block.find("\r\n");
  16463. if (e != std::string::npos) {
  16464. auto request_line = request_block.substr(0, e);
  16465. std::string msg =
  16466. "CRLF injection detected in request line: '" + request_line + "'";
  16467. EXPECT_FALSE(true) << msg;
  16468. }
  16469. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16470. ::send(cli,
  16471. #ifdef _WIN32
  16472. static_cast<const char *>(resp.c_str()),
  16473. static_cast<int>(resp.size()),
  16474. #else
  16475. resp.c_str(), resp.size(),
  16476. #endif
  16477. 0);
  16478. buf_all.erase(0, pos + 4);
  16479. }
  16480. }
  16481. detail::close_socket(cli);
  16482. detail::close_socket(srv);
  16483. });
  16484. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16485. auto cli = Client("127.0.0.1", PORT + 1);
  16486. auto headers = Headers{
  16487. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16488. {"Connection", "keep-alive"}};
  16489. auto res = cli.Get("/hi", headers);
  16490. EXPECT_FALSE(res);
  16491. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16492. server_thread.join();
  16493. }
  16494. // A request rejected before any byte reaches the socket must fail right away
  16495. // instead of waiting for a response the server will never send.
  16496. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16497. // The kernel completes the TCP handshake from the listen backlog, so the
  16498. // client connects, but nothing ever reads, responds or closes.
  16499. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16500. default_socket_options(srv);
  16501. sockaddr_in addr{};
  16502. addr.sin_family = AF_INET;
  16503. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16504. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16505. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16506. ASSERT_EQ(0, ::listen(srv, 8));
  16507. auto cli = Client("127.0.0.1", PORT + 1);
  16508. cli.set_read_timeout(10, 0);
  16509. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16510. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16511. std::chrono::steady_clock::now() - start)
  16512. .count();
  16513. };
  16514. {
  16515. Request req;
  16516. req.method = "GE T";
  16517. req.path = "/";
  16518. auto start = std::chrono::steady_clock::now();
  16519. auto res = cli.send(req);
  16520. EXPECT_FALSE(res);
  16521. EXPECT_EQ(Error::Write, res.error());
  16522. EXPECT_LT(elapsed_ms(start), 1000);
  16523. }
  16524. {
  16525. auto start = std::chrono::steady_clock::now();
  16526. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16527. EXPECT_FALSE(res);
  16528. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16529. EXPECT_LT(elapsed_ms(start), 1000);
  16530. }
  16531. EXPECT_FALSE(cli.is_socket_open());
  16532. detail::close_socket(srv);
  16533. }
  16534. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16535. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16536. default_socket_options(srv);
  16537. sockaddr_in addr{};
  16538. addr.sin_family = AF_INET;
  16539. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16540. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16541. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16542. ASSERT_EQ(0, ::listen(srv, 1));
  16543. std::string received;
  16544. auto server_thread = std::thread([&] {
  16545. auto sock = ::accept(srv, nullptr, nullptr);
  16546. if (sock == INVALID_SOCKET) { return; }
  16547. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16548. char buf[2048];
  16549. ssize_t n;
  16550. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16551. received.append(buf, static_cast<size_t>(n));
  16552. }
  16553. detail::close_socket(sock);
  16554. });
  16555. {
  16556. auto cli = Client("127.0.0.1", PORT + 1);
  16557. // "Z" sorts after the default headers, so writing straight to the socket
  16558. // would have sent the request line and those headers before the rejection.
  16559. auto handle =
  16560. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16561. EXPECT_FALSE(handle.is_valid());
  16562. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16563. }
  16564. server_thread.join();
  16565. detail::close_socket(srv);
  16566. EXPECT_TRUE(received.empty()) << received;
  16567. }
  16568. TEST(PathParamsTest, StaticMatch) {
  16569. const auto pattern = "/users/all";
  16570. detail::PathParamsMatcher matcher(pattern);
  16571. Request request;
  16572. request.path = "/users/all";
  16573. ASSERT_TRUE(matcher.match(request));
  16574. std::unordered_map<std::string, std::string> expected_params = {};
  16575. EXPECT_EQ(request.path_params, expected_params);
  16576. }
  16577. TEST(PathParamsTest, StaticMismatch) {
  16578. const auto pattern = "/users/all";
  16579. detail::PathParamsMatcher matcher(pattern);
  16580. Request request;
  16581. request.path = "/users/1";
  16582. ASSERT_FALSE(matcher.match(request));
  16583. }
  16584. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16585. const auto pattern = "/users/:id/subscriptions";
  16586. detail::PathParamsMatcher matcher(pattern);
  16587. Request request;
  16588. request.path = "/users/42/subscriptions";
  16589. ASSERT_TRUE(matcher.match(request));
  16590. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16591. EXPECT_EQ(request.path_params, expected_params);
  16592. }
  16593. TEST(PathParamsTest, SingleParamInTheEnd) {
  16594. const auto pattern = "/users/:id";
  16595. detail::PathParamsMatcher matcher(pattern);
  16596. Request request;
  16597. request.path = "/users/24";
  16598. ASSERT_TRUE(matcher.match(request));
  16599. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16600. EXPECT_EQ(request.path_params, expected_params);
  16601. }
  16602. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16603. const auto pattern = "/users/:id/";
  16604. detail::PathParamsMatcher matcher(pattern);
  16605. Request request;
  16606. request.path = "/users/42/";
  16607. ASSERT_TRUE(matcher.match(request));
  16608. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16609. EXPECT_EQ(request.path_params, expected_params);
  16610. }
  16611. TEST(PathParamsTest, EmptyParam) {
  16612. const auto pattern = "/users/:id/";
  16613. detail::PathParamsMatcher matcher(pattern);
  16614. Request request;
  16615. request.path = "/users//";
  16616. ASSERT_TRUE(matcher.match(request));
  16617. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16618. EXPECT_EQ(request.path_params, expected_params);
  16619. }
  16620. TEST(PathParamsTest, FragmentMismatch) {
  16621. const auto pattern = "/users/:id/";
  16622. detail::PathParamsMatcher matcher(pattern);
  16623. Request request;
  16624. request.path = "/admins/24/";
  16625. ASSERT_FALSE(matcher.match(request));
  16626. }
  16627. TEST(PathParamsTest, ExtraFragments) {
  16628. const auto pattern = "/users/:id";
  16629. detail::PathParamsMatcher matcher(pattern);
  16630. Request request;
  16631. request.path = "/users/42/subscriptions";
  16632. ASSERT_FALSE(matcher.match(request));
  16633. }
  16634. TEST(PathParamsTest, MissingTrailingParam) {
  16635. const auto pattern = "/users/:id";
  16636. detail::PathParamsMatcher matcher(pattern);
  16637. Request request;
  16638. request.path = "/users";
  16639. ASSERT_FALSE(matcher.match(request));
  16640. }
  16641. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16642. const auto pattern = "/users/:id/subscriptions";
  16643. detail::PathParamsMatcher matcher(pattern);
  16644. Request request;
  16645. request.path = "/users/subscriptions";
  16646. ASSERT_FALSE(matcher.match(request));
  16647. }
  16648. TEST(PathParamsTest, MultipleParams) {
  16649. const auto pattern = "/users/:userid/subscriptions/:subid";
  16650. detail::PathParamsMatcher matcher(pattern);
  16651. Request request;
  16652. request.path = "/users/42/subscriptions/2";
  16653. ASSERT_TRUE(matcher.match(request));
  16654. std::unordered_map<std::string, std::string> expected_params = {
  16655. {"userid", "42"}, {"subid", "2"}};
  16656. EXPECT_EQ(request.path_params, expected_params);
  16657. }
  16658. TEST(PathParamsTest, SequenceOfParams) {
  16659. const auto pattern = "/values/:x/:y/:z";
  16660. detail::PathParamsMatcher matcher(pattern);
  16661. Request request;
  16662. request.path = "/values/1/2/3";
  16663. ASSERT_TRUE(matcher.match(request));
  16664. std::unordered_map<std::string, std::string> expected_params = {
  16665. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16666. EXPECT_EQ(request.path_params, expected_params);
  16667. }
  16668. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16669. const auto pattern = "/prefix:suffix";
  16670. detail::PathParamsMatcher matcher(pattern);
  16671. Request request;
  16672. request.path = "/prefix:suffix";
  16673. ASSERT_TRUE(matcher.match(request));
  16674. const std::unordered_map<std::string, std::string> expected_params = {};
  16675. EXPECT_EQ(request.path_params, expected_params);
  16676. }
  16677. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16678. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16679. // calling thread's stack on a long enough path for a quantified pattern;
  16680. // RegexMatcher must refuse to run regex matching on paths beyond
  16681. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16682. detail::RegexMatcher matcher("/files/(.*)");
  16683. Request within_limit;
  16684. within_limit.path = "/files/" + std::string(10, 'A');
  16685. EXPECT_TRUE(matcher.match(within_limit));
  16686. Request over_limit;
  16687. over_limit.path =
  16688. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16689. EXPECT_FALSE(matcher.match(over_limit));
  16690. }
  16691. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16692. Server svr;
  16693. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16694. res.set_content("ok", "text/plain");
  16695. });
  16696. auto port = svr.bind_to_any_port(HOST);
  16697. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16698. auto se = detail::scope_exit([&] {
  16699. svr.stop();
  16700. thread.join();
  16701. ASSERT_FALSE(svr.is_running());
  16702. });
  16703. svr.wait_until_ready();
  16704. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16705. // request URI limit; this used to be able to crash the process.
  16706. std::string path =
  16707. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16708. std::string req = "GET " + path +
  16709. " HTTP/1.1\r\n"
  16710. "Host: " +
  16711. std::string(HOST) + ":" + std::to_string(port) +
  16712. "\r\n"
  16713. "Connection: close\r\n"
  16714. "\r\n";
  16715. std::string response;
  16716. ASSERT_TRUE(send_request(5, req, &response, port));
  16717. EXPECT_NE(std::string::npos, response.find("404"));
  16718. }
  16719. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16720. Server svr;
  16721. auto handler = [](const Request & /*req*/, Response &res) {
  16722. res.set_content("hit", "text/plain");
  16723. };
  16724. // No regex metacharacter, so this one is compared literally
  16725. svr.Get("/literal/route", handler);
  16726. // '.' is a regex metacharacter, so this one must keep regex semantics
  16727. svr.Get("/a.c", handler);
  16728. auto port = svr.bind_to_any_port(HOST);
  16729. std::thread t([&]() { svr.listen_after_bind(); });
  16730. auto se = detail::scope_exit([&] {
  16731. svr.stop();
  16732. t.join();
  16733. ASSERT_FALSE(svr.is_running());
  16734. });
  16735. svr.wait_until_ready();
  16736. Client cli(HOST, port);
  16737. struct {
  16738. const char *path;
  16739. int status;
  16740. } cases[] = {
  16741. {"/literal/route", StatusCode::OK_200},
  16742. {"/literal/routes", StatusCode::NotFound_404},
  16743. {"/literal/rout", StatusCode::NotFound_404},
  16744. {"/abc", StatusCode::OK_200},
  16745. {"/a.c", StatusCode::OK_200},
  16746. };
  16747. for (const auto &x : cases) {
  16748. auto res = cli.Get(x.path);
  16749. ASSERT_TRUE(res) << x.path;
  16750. EXPECT_EQ(x.status, res->status) << x.path;
  16751. }
  16752. }
  16753. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16754. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16755. // from exhausting the stack, so it must only constrain routes that actually
  16756. // run a regular expression. A literal route is matched by comparison and
  16757. // stays usable at any length.
  16758. Server svr;
  16759. const std::string pattern =
  16760. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16761. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16762. res.set_content("hit", "text/plain");
  16763. });
  16764. auto port = svr.bind_to_any_port(HOST);
  16765. std::thread t([&]() { svr.listen_after_bind(); });
  16766. auto se = detail::scope_exit([&] {
  16767. svr.stop();
  16768. t.join();
  16769. ASSERT_FALSE(svr.is_running());
  16770. });
  16771. svr.wait_until_ready();
  16772. Client cli(HOST, port);
  16773. auto res = cli.Get(pattern);
  16774. ASSERT_TRUE(res);
  16775. EXPECT_EQ(StatusCode::OK_200, res->status);
  16776. }
  16777. TEST(ParseUrlTest, VariousPatterns) {
  16778. {
  16779. detail::UrlComponents uc;
  16780. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16781. EXPECT_EQ("http", uc.scheme);
  16782. EXPECT_EQ("example.com", uc.host);
  16783. EXPECT_EQ("8080", uc.port);
  16784. EXPECT_EQ("/path", uc.path);
  16785. EXPECT_EQ("?q=1", uc.query);
  16786. }
  16787. {
  16788. detail::UrlComponents uc;
  16789. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16790. EXPECT_EQ("https", uc.scheme);
  16791. EXPECT_EQ("example.com", uc.host);
  16792. EXPECT_TRUE(uc.port.empty());
  16793. EXPECT_EQ("/path", uc.path);
  16794. }
  16795. {
  16796. detail::UrlComponents uc;
  16797. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16798. EXPECT_EQ("::1", uc.host);
  16799. EXPECT_EQ("8080", uc.port);
  16800. EXPECT_EQ("/path", uc.path);
  16801. }
  16802. {
  16803. detail::UrlComponents uc;
  16804. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16805. }
  16806. {
  16807. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16808. // the path while the connection still targets the bracketed host.
  16809. detail::UrlComponents uc;
  16810. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16811. }
  16812. {
  16813. detail::UrlComponents uc;
  16814. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16815. }
  16816. {
  16817. detail::UrlComponents uc;
  16818. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16819. EXPECT_EQ("::1", uc.host);
  16820. EXPECT_TRUE(uc.port.empty());
  16821. EXPECT_EQ("/path", uc.path);
  16822. }
  16823. {
  16824. detail::UrlComponents uc;
  16825. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16826. EXPECT_TRUE(uc.scheme.empty());
  16827. EXPECT_EQ("example.com", uc.host);
  16828. EXPECT_EQ("/path", uc.path);
  16829. EXPECT_EQ("?q=1", uc.query);
  16830. }
  16831. {
  16832. detail::UrlComponents uc;
  16833. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16834. EXPECT_TRUE(uc.host.empty());
  16835. EXPECT_EQ("/path", uc.path);
  16836. EXPECT_EQ("?q=1", uc.query);
  16837. }
  16838. {
  16839. detail::UrlComponents uc;
  16840. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16841. EXPECT_EQ("example.com", uc.host);
  16842. EXPECT_EQ("8080", uc.port);
  16843. }
  16844. {
  16845. // Unix socket path — must not be parsed as host
  16846. detail::UrlComponents uc;
  16847. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16848. EXPECT_TRUE(uc.host.empty());
  16849. }
  16850. {
  16851. detail::UrlComponents uc;
  16852. ASSERT_TRUE(detail::parse_url("", uc));
  16853. EXPECT_TRUE(uc.host.empty());
  16854. EXPECT_TRUE(uc.path.empty());
  16855. }
  16856. {
  16857. detail::UrlComponents uc;
  16858. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16859. }
  16860. {
  16861. detail::UrlComponents uc;
  16862. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16863. }
  16864. {
  16865. // Accepted by parse_url; callers restrict to http/https
  16866. detail::UrlComponents uc;
  16867. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16868. EXPECT_EQ("ftp", uc.scheme);
  16869. }
  16870. {
  16871. detail::UrlComponents uc;
  16872. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16873. }
  16874. {
  16875. detail::UrlComponents uc;
  16876. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16877. }
  16878. }
  16879. TEST(ParseUrlTest, FragmentHandling) {
  16880. {
  16881. detail::UrlComponents uc;
  16882. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16883. EXPECT_EQ("/path", uc.path);
  16884. EXPECT_TRUE(uc.query.empty());
  16885. }
  16886. {
  16887. detail::UrlComponents uc;
  16888. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16889. EXPECT_TRUE(uc.path.empty());
  16890. EXPECT_TRUE(uc.query.empty());
  16891. }
  16892. }
  16893. TEST(ParseUrlTest, UserinfoHandling) {
  16894. // userinfo, and a backslash some parsers take for '/', are rejected: such
  16895. // parsers would see evil.com as the host.
  16896. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16897. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16898. for (auto url : urls) {
  16899. detail::UrlComponents uc;
  16900. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16901. }
  16902. }
  16903. TEST(ParseUrlTest, IPv6EdgeCases) {
  16904. {
  16905. detail::UrlComponents uc;
  16906. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16907. EXPECT_TRUE(uc.scheme.empty());
  16908. EXPECT_EQ("::1", uc.host);
  16909. EXPECT_EQ("8080", uc.port);
  16910. }
  16911. {
  16912. // Zone ID '%25' is not in [a-fA-F0-9:]
  16913. detail::UrlComponents uc;
  16914. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16915. }
  16916. }
  16917. TEST(ParseUrlTest, SchemeEdgeCases) {
  16918. {
  16919. detail::UrlComponents uc;
  16920. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16921. }
  16922. {
  16923. detail::UrlComponents uc;
  16924. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16925. }
  16926. {
  16927. detail::UrlComponents uc;
  16928. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16929. }
  16930. }
  16931. TEST(ParseUrlTest, PortEdgeCases) {
  16932. {
  16933. detail::UrlComponents uc;
  16934. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16935. EXPECT_TRUE(uc.port.empty());
  16936. EXPECT_EQ("/path", uc.path);
  16937. }
  16938. {
  16939. // parse_url accepts any port string; validation is done by parse_port
  16940. detail::UrlComponents uc;
  16941. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16942. EXPECT_EQ("abc", uc.port);
  16943. }
  16944. }
  16945. TEST(ParseUrlTest, WebSocketPatterns) {
  16946. {
  16947. detail::UrlComponents uc;
  16948. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16949. EXPECT_EQ("ws", uc.scheme);
  16950. EXPECT_EQ("echo.example.com", uc.host);
  16951. EXPECT_EQ("8080", uc.port);
  16952. EXPECT_EQ("/ws", uc.path);
  16953. }
  16954. {
  16955. detail::UrlComponents uc;
  16956. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16957. EXPECT_EQ("wss", uc.scheme);
  16958. EXPECT_EQ("echo.example.com", uc.host);
  16959. EXPECT_TRUE(uc.port.empty());
  16960. EXPECT_EQ("/ws", uc.path);
  16961. }
  16962. }
  16963. TEST(ParseUrlTest, QueryOnly) {
  16964. detail::UrlComponents uc;
  16965. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16966. EXPECT_TRUE(uc.host.empty());
  16967. EXPECT_TRUE(uc.path.empty());
  16968. EXPECT_EQ("?q=1&r=2", uc.query);
  16969. }
  16970. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16971. detail::UrlComponents uc;
  16972. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16973. EXPECT_TRUE(uc.scheme.empty());
  16974. EXPECT_EQ("example.com", uc.host);
  16975. EXPECT_EQ("443", uc.port);
  16976. EXPECT_EQ("/path", uc.path);
  16977. }
  16978. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16979. // If ipv6 regex working, regex match codepath is taken.
  16980. // else port will default to 80 in Client impl
  16981. int clientImplMagicPort = 80;
  16982. int port = 4321;
  16983. // above ports must be different to avoid false negative
  16984. EXPECT_NE(clientImplMagicPort, port);
  16985. std::string ipV6TestURL = "http://[ff06::c3]";
  16986. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16987. CLIENT_PRIVATE_KEY_FILE);
  16988. EXPECT_EQ(cli.port(), port);
  16989. }
  16990. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16991. auto file_path = "./www/dir/index.html";
  16992. auto dir_path = "./www/dir";
  16993. detail::FileStat stat_file(file_path);
  16994. EXPECT_TRUE(stat_file.is_file());
  16995. EXPECT_FALSE(stat_file.is_dir());
  16996. detail::FileStat stat_dir(dir_path);
  16997. EXPECT_FALSE(stat_dir.is_file());
  16998. EXPECT_TRUE(stat_dir.is_dir());
  16999. }
  17000. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17001. // IPv4 with default HTTP port (80)
  17002. EXPECT_EQ("example.com",
  17003. detail::make_host_and_port_string("example.com", 80, false));
  17004. // IPv4 with default HTTPS port (443)
  17005. EXPECT_EQ("example.com",
  17006. detail::make_host_and_port_string("example.com", 443, true));
  17007. // IPv4 with non-default HTTP port
  17008. EXPECT_EQ("example.com:8080",
  17009. detail::make_host_and_port_string("example.com", 8080, false));
  17010. // IPv4 with non-default HTTPS port
  17011. EXPECT_EQ("example.com:8443",
  17012. detail::make_host_and_port_string("example.com", 8443, true));
  17013. // IPv6 with default HTTP port (80)
  17014. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17015. // IPv6 with default HTTPS port (443)
  17016. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17017. // IPv6 with non-default HTTP port
  17018. EXPECT_EQ("[::1]:8080",
  17019. detail::make_host_and_port_string("::1", 8080, false));
  17020. // IPv6 with non-default HTTPS port
  17021. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17022. // IPv6 full address with default port
  17023. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17024. detail::make_host_and_port_string(
  17025. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17026. // IPv6 full address with non-default port
  17027. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17028. detail::make_host_and_port_string(
  17029. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17030. // IPv6 localhost with non-default port
  17031. EXPECT_EQ("[::1]:3000",
  17032. detail::make_host_and_port_string("::1", 3000, false));
  17033. // IPv6 with zone ID (link-local address) with default port
  17034. EXPECT_EQ("[fe80::1%eth0]",
  17035. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17036. // IPv6 with zone ID (link-local address) with non-default port
  17037. EXPECT_EQ("[fe80::1%eth0]:8080",
  17038. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17039. // Edge case: Port 443 with is_ssl=false (should add port)
  17040. EXPECT_EQ("example.com:443",
  17041. detail::make_host_and_port_string("example.com", 443, false));
  17042. // Edge case: Port 80 with is_ssl=true (should add port)
  17043. EXPECT_EQ("example.com:80",
  17044. detail::make_host_and_port_string("example.com", 80, true));
  17045. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17046. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17047. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17048. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17049. // Security fix: Already bracketed IPv6 should not get double brackets
  17050. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17051. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17052. EXPECT_EQ("[::1]:8080",
  17053. detail::make_host_and_port_string("[::1]", 8080, false));
  17054. EXPECT_EQ("[2001:db8::1]:8080",
  17055. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17056. EXPECT_EQ("[fe80::1%eth0]",
  17057. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17058. EXPECT_EQ("[fe80::1%eth0]:8080",
  17059. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17060. // Edge case: Empty host (should return as-is)
  17061. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17062. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17063. // This is a known limitation but shouldn't crash
  17064. EXPECT_EQ("[host:name]",
  17065. detail::make_host_and_port_string("host:name", 80, false));
  17066. // Port number edge cases (no validation, but should not crash)
  17067. EXPECT_EQ("example.com:0",
  17068. detail::make_host_and_port_string("example.com", 0, false));
  17069. EXPECT_EQ("example.com:-1",
  17070. detail::make_host_and_port_string("example.com", -1, false));
  17071. EXPECT_EQ("example.com:65535",
  17072. detail::make_host_and_port_string("example.com", 65535, false));
  17073. EXPECT_EQ("example.com:65536",
  17074. detail::make_host_and_port_string("example.com", 65536, false));
  17075. }
  17076. #ifdef CPPHTTPLIB_SSL_ENABLED
  17077. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17078. httplib::SSLClient cli("roblox.com", 443);
  17079. cli.set_follow_location(true);
  17080. auto res = cli.Get("/");
  17081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17082. EXPECT_EQ(StatusCode::OK_200, res->status);
  17083. }
  17084. #endif
  17085. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17086. Server svr;
  17087. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17088. EXPECT_EQ(res.status, 400);
  17089. });
  17090. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17091. auto se = detail::scope_exit([&] {
  17092. svr.stop();
  17093. thread.join();
  17094. ASSERT_FALSE(svr.is_running());
  17095. });
  17096. svr.wait_until_ready();
  17097. Client cli(HOST, PORT);
  17098. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17099. }
  17100. TEST(InvalidHeaderCharsTest, is_field_name) {
  17101. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17102. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17103. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17104. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17105. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17106. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17107. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17108. EXPECT_FALSE(detail::fields::is_field_name(""));
  17109. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17110. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17111. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17112. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17113. }
  17114. TEST(InvalidHeaderCharsTest, is_field_value) {
  17115. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17116. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17117. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17118. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17119. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17120. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17121. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17122. EXPECT_TRUE(detail::fields::is_field_value(""));
  17123. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17124. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17125. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17126. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17127. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17128. }
  17129. TEST(InvalidHeaderCharsTest, OnServer) {
  17130. Server svr;
  17131. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17132. std::string header = "Not Set";
  17133. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17134. res.set_header(header, "value");
  17135. res.set_content("Page Content Page Content", "text/plain");
  17136. });
  17137. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17138. std::string header = "Not Set";
  17139. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17140. res.set_header("X-Test", header);
  17141. res.set_content("Page Content Page Content", "text/plain");
  17142. });
  17143. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17144. auto se = detail::scope_exit([&] {
  17145. svr.stop();
  17146. thread.join();
  17147. ASSERT_FALSE(svr.is_running());
  17148. });
  17149. svr.wait_until_ready();
  17150. Client cli(HOST, PORT);
  17151. {
  17152. auto res = cli.Get(
  17153. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17155. EXPECT_EQ("Page Content Page Content", res->body);
  17156. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17157. }
  17158. {
  17159. auto res = cli.Get(
  17160. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17162. EXPECT_EQ("Page Content Page Content", res->body);
  17163. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17164. }
  17165. }
  17166. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17167. auto handled = false;
  17168. Server svr;
  17169. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17170. thread t = thread([&] { svr.listen(HOST, PORT); });
  17171. auto se = detail::scope_exit([&] {
  17172. svr.stop();
  17173. t.join();
  17174. ASSERT_FALSE(svr.is_running());
  17175. ASSERT_FALSE(handled);
  17176. });
  17177. svr.wait_until_ready();
  17178. auto req = "POST /test HTTP/1.1\r\n"
  17179. "Content-Length: x\r\n"
  17180. "\r\n";
  17181. std::string response;
  17182. ASSERT_TRUE(send_request(1, req, &response));
  17183. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17184. response.substr(0, response.find("\r\n")));
  17185. }
  17186. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17187. // case-insensitive, and a server that receives a 100-continue expectation in
  17188. // an HTTP/1.0 request MUST ignore it.
  17189. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17190. std::string response;
  17191. ASSERT_TRUE(send_request(1, req, &response, port));
  17192. *got_100 = response.find("100 Continue") != std::string::npos;
  17193. }
  17194. class ExpectTokenTest : public ::testing::Test {
  17195. protected:
  17196. void SetUp() override {
  17197. svr_.Post("/p", [](const Request &, Response &res) {
  17198. res.set_content("ok", "text/plain");
  17199. });
  17200. port_ = svr_.bind_to_any_port(HOST);
  17201. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17202. svr_.wait_until_ready();
  17203. }
  17204. void TearDown() override {
  17205. svr_.stop();
  17206. if (thread_.joinable()) { thread_.join(); }
  17207. }
  17208. std::string request(const char *version, const char *expect_value) const {
  17209. return std::string("POST /p ") + version +
  17210. "\r\n"
  17211. "Host: localhost\r\n"
  17212. "Content-Length: 2\r\n"
  17213. "Connection: close\r\n"
  17214. "Expect: " +
  17215. expect_value +
  17216. "\r\n"
  17217. "\r\n"
  17218. "hi";
  17219. }
  17220. Server svr_;
  17221. int port_ = 0;
  17222. thread thread_;
  17223. };
  17224. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17225. bool got_100 = false;
  17226. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17227. EXPECT_TRUE(got_100);
  17228. }
  17229. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17230. bool got_100 = true;
  17231. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17232. EXPECT_FALSE(got_100);
  17233. }
  17234. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17235. bool got_100 = false;
  17236. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17237. EXPECT_TRUE(got_100);
  17238. }
  17239. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17240. bool got_100 = false;
  17241. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17242. EXPECT_TRUE(got_100);
  17243. }
  17244. // `100 Continue` is sent only when the server starts reading the body, so a
  17245. // request rejected before that never invites the client to send it. The
  17246. // requests below carry the expectation but withhold the body, as a client
  17247. // waiting for `100 Continue` would.
  17248. // A POST that expects `100 Continue` and withholds its two-byte body.
  17249. static std::string expect_headers_only(const std::string &path) {
  17250. return "POST " + path +
  17251. " HTTP/1.1\r\n"
  17252. "Host: localhost\r\n"
  17253. "Content-Length: 2\r\n"
  17254. "Expect: 100-continue\r\n"
  17255. "\r\n";
  17256. }
  17257. class ExpectLazyContinueTest : public ::testing::Test {
  17258. protected:
  17259. void SetUp() override {
  17260. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17261. if (req.path == "/pre-routing") {
  17262. res.status = StatusCode::Unauthorized_401;
  17263. return Server::HandlerResponse::Handled;
  17264. }
  17265. return Server::HandlerResponse::Unhandled;
  17266. });
  17267. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17268. if (req.matched_route == "/pre-request") {
  17269. res.status = StatusCode::Forbidden_403;
  17270. return Server::HandlerResponse::Handled;
  17271. }
  17272. return Server::HandlerResponse::Unhandled;
  17273. });
  17274. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17275. res.set_content("ok", "text/plain");
  17276. });
  17277. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17278. res.set_content("ok", "text/plain");
  17279. });
  17280. svr_.Post("/reader-used", [](const Request &, Response &res,
  17281. const ContentReader &content_reader) {
  17282. std::string body;
  17283. content_reader([&](const char *data, size_t len) {
  17284. body.append(data, len);
  17285. return true;
  17286. });
  17287. res.set_content(body, "text/plain");
  17288. });
  17289. svr_.Post("/reader-unused",
  17290. [](const Request &, Response &res, const ContentReader &) {
  17291. res.set_content("ignored", "text/plain");
  17292. });
  17293. port_ = svr_.bind_to_any_port(HOST);
  17294. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17295. svr_.wait_until_ready();
  17296. }
  17297. void TearDown() override {
  17298. svr_.stop();
  17299. if (thread_.joinable()) { thread_.join(); }
  17300. }
  17301. // Sends `req` and reads until the server closes the connection. Returns
  17302. // false if the read had to wait for the client-side timeout instead.
  17303. bool send_until_closed(const std::string &req, std::string *resp) const {
  17304. auto start = std::chrono::steady_clock::now();
  17305. if (!send_request(3, req, resp, port_)) { return false; }
  17306. auto elapsed = std::chrono::steady_clock::now() - start;
  17307. return elapsed < std::chrono::seconds(2);
  17308. }
  17309. // The final response comes without `100 Continue`, and the server closes
  17310. // the connection since the body may or may not follow.
  17311. void expect_final_without_interim(const std::string &path,
  17312. const char *status_line) const {
  17313. std::string resp;
  17314. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17315. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17316. EXPECT_EQ(0u, resp.find(status_line));
  17317. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17318. }
  17319. Server svr_;
  17320. int port_ = 0;
  17321. thread thread_;
  17322. };
  17323. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17324. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17325. }
  17326. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17327. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17328. }
  17329. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17330. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17331. }
  17332. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17333. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17334. }
  17335. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17336. // The body follows once `100 Continue` has had time to arrive.
  17337. auto req = expect_headers_only("/reader-used");
  17338. req.insert(req.size() - 2, "Connection: close\r\n");
  17339. std::string resp;
  17340. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17341. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17342. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17343. EXPECT_NE(std::string::npos, resp.find("hi"));
  17344. }
  17345. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17346. // Large enough for the client to add `Expect: 100-continue` itself.
  17347. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17348. std::atomic<bool> body_sent{false};
  17349. Client cli(HOST, port_);
  17350. auto res = cli.Post(
  17351. "/pre-request", length,
  17352. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17353. body_sent = true;
  17354. std::string chunk(len, 'x');
  17355. sink.write(chunk.data(), chunk.size());
  17356. return true;
  17357. },
  17358. "application/octet-stream");
  17359. ASSERT_TRUE(res);
  17360. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17361. EXPECT_FALSE(body_sent);
  17362. }
  17363. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17364. Server svr;
  17365. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17366. return StatusCode::ExpectationFailed_417;
  17367. });
  17368. svr.Post("/p", [](const Request &, Response &res) {
  17369. res.set_content("ok", "text/plain");
  17370. });
  17371. auto port = svr.bind_to_any_port(HOST);
  17372. thread t = thread([&] { svr.listen_after_bind(); });
  17373. auto se = detail::scope_exit([&] {
  17374. svr.stop();
  17375. t.join();
  17376. });
  17377. svr.wait_until_ready();
  17378. std::string resp;
  17379. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17380. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17381. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17382. // Exactly one response: the route handler must not run after the 417.
  17383. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17384. }
  17385. #ifndef _WIN32
  17386. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17387. static constexpr char reject[] = "Unauthorized";
  17388. static constexpr char accept[] = "Upload accepted";
  17389. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17390. Server svr;
  17391. svr.set_expect_100_continue_handler(
  17392. [](const Request & /*req*/, Response &res) {
  17393. res.status = StatusCode::Unauthorized_401;
  17394. res.set_content(reject, "text/plain");
  17395. return res.status;
  17396. });
  17397. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17398. res.set_content(accept, "text/plain");
  17399. });
  17400. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17401. auto se = detail::scope_exit([&] {
  17402. svr.stop();
  17403. thread.join();
  17404. ASSERT_FALSE(svr.is_running());
  17405. });
  17406. svr.wait_until_ready();
  17407. {
  17408. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17409. curl_easy_init(), &curl_easy_cleanup};
  17410. ASSERT_NE(curl, nullptr);
  17411. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17412. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17413. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17414. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17415. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17416. &curl_slist_free_all};
  17417. ASSERT_NE(list, nullptr);
  17418. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17419. struct read_data {
  17420. size_t read_size;
  17421. size_t total_size;
  17422. } data = {0, total_size};
  17423. using read_callback_t =
  17424. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17425. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17426. void *userdata) -> size_t {
  17427. read_data *d = (read_data *)userdata;
  17428. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17429. std::fill_n(ptr, size * nmemb, 'A');
  17430. d->read_size += size * nmemb;
  17431. return size * nmemb;
  17432. };
  17433. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17434. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17435. std::vector<char> buffer;
  17436. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17437. using write_callback_t =
  17438. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17439. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17440. void *userdata) -> size_t {
  17441. std::vector<char> *buf = (std::vector<char> *)userdata;
  17442. buf->reserve(buf->size() + size * nmemb + 1);
  17443. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17444. return size * nmemb;
  17445. };
  17446. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17447. {
  17448. const auto res = curl_easy_perform(curl.get());
  17449. ASSERT_EQ(res, CURLE_OK);
  17450. }
  17451. {
  17452. auto response_code = long{};
  17453. const auto res =
  17454. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17455. ASSERT_EQ(res, CURLE_OK);
  17456. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17457. }
  17458. {
  17459. auto dl = curl_off_t{};
  17460. const auto res =
  17461. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17462. ASSERT_EQ(res, CURLE_OK);
  17463. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17464. }
  17465. {
  17466. buffer.push_back('\0');
  17467. ASSERT_STRCASEEQ(buffer.data(), reject);
  17468. }
  17469. }
  17470. }
  17471. #endif
  17472. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17473. // Regression test for #2458.
  17474. //
  17475. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17476. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17477. // ticket can make the client socket spuriously readable during the
  17478. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17479. // the client withholds the body and then blocks reading a response that never
  17480. // comes, failing with `Failed to read connection`.
  17481. //
  17482. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17483. // within the timeout. This raw OpenSSL server deliberately never sends
  17484. // `100 Continue`; the client must still deliver the body and receive 200.
  17485. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17486. signal(SIGPIPE, SIG_IGN);
  17487. const auto port = PORT + 4;
  17488. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17489. ASSERT_NE(srv, INVALID_SOCKET);
  17490. int opt = 1;
  17491. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17492. sockaddr_in addr{};
  17493. addr.sin_family = AF_INET;
  17494. addr.sin_port = htons(static_cast<uint16_t>(port));
  17495. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17496. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17497. ASSERT_EQ(0, ::listen(srv, 1));
  17498. std::atomic<size_t> server_body_bytes{0};
  17499. auto server_thread = std::thread([&] {
  17500. sockaddr_in cli_addr{};
  17501. socklen_t cli_len = sizeof(cli_addr);
  17502. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17503. if (cli == INVALID_SOCKET) { return; }
  17504. // Bound the lifetime of the server side so a buggy client (which never
  17505. // sends the body) cannot make this thread block forever on join.
  17506. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17507. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17508. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17509. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17510. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17511. SSL *ssl = SSL_new(ctx);
  17512. SSL_set_fd(ssl, static_cast<int>(cli));
  17513. if (SSL_accept(ssl) > 0) {
  17514. // Read the request headers. Reading here also flushes the TLS 1.3
  17515. // session tickets to the client. Deliberately do NOT send
  17516. // `100 Continue`.
  17517. std::string buf;
  17518. char tmp[1024];
  17519. while (buf.find("\r\n\r\n") == std::string::npos) {
  17520. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17521. if (n <= 0) { break; }
  17522. buf.append(tmp, static_cast<size_t>(n));
  17523. }
  17524. // A correct client sends the body now; count what arrives.
  17525. auto pos = buf.find("\r\n\r\n");
  17526. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17527. while (body < 4096) {
  17528. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17529. if (n <= 0) { break; }
  17530. body += static_cast<size_t>(n);
  17531. }
  17532. server_body_bytes = body;
  17533. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17534. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17535. SSL_shutdown(ssl);
  17536. }
  17537. SSL_free(ssl);
  17538. detail::close_socket(cli);
  17539. SSL_CTX_free(ctx);
  17540. });
  17541. auto se = detail::scope_exit([&] {
  17542. server_thread.join();
  17543. detail::close_socket(srv);
  17544. });
  17545. SSLClient cli("127.0.0.1", port);
  17546. cli.enable_server_certificate_verification(false);
  17547. cli.set_connection_timeout(5, 0);
  17548. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17549. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17550. std::string body(4096, 'A');
  17551. auto res = cli.Put("/api/test", body, "application/json");
  17552. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17553. EXPECT_EQ(StatusCode::OK_200, res->status);
  17554. EXPECT_EQ(body.size(), server_body_bytes.load());
  17555. }
  17556. #endif
  17557. template <typename S, typename C>
  17558. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17559. svr.Get("/stream", [&](const Request &, Response &res) {
  17560. auto data = new std::string("01234567890123456789");
  17561. res.set_content_provider(
  17562. data->size(), "text/plain",
  17563. [&, data](size_t offset, size_t length, DataSink &sink) {
  17564. const size_t DATA_CHUNK_SIZE = 4;
  17565. const auto &d = *data;
  17566. std::this_thread::sleep_for(std::chrono::seconds(1));
  17567. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17568. return true;
  17569. },
  17570. [data](bool success) {
  17571. EXPECT_FALSE(success);
  17572. delete data;
  17573. });
  17574. });
  17575. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17576. auto i = new size_t(0);
  17577. res.set_content_provider(
  17578. "text/plain",
  17579. [i](size_t, DataSink &sink) {
  17580. if (*i < 5) {
  17581. std::this_thread::sleep_for(std::chrono::seconds(1));
  17582. sink.write("abcd", 4);
  17583. (*i)++;
  17584. } else {
  17585. sink.done();
  17586. }
  17587. return true;
  17588. },
  17589. [i](bool success) {
  17590. EXPECT_FALSE(success);
  17591. delete i;
  17592. });
  17593. });
  17594. svr.Get("/chunked", [&](const Request &, Response &res) {
  17595. auto i = new size_t(0);
  17596. res.set_chunked_content_provider(
  17597. "text/plain",
  17598. [i](size_t, DataSink &sink) {
  17599. if (*i < 5) {
  17600. std::this_thread::sleep_for(std::chrono::seconds(1));
  17601. sink.os << "abcd";
  17602. (*i)++;
  17603. } else {
  17604. sink.done();
  17605. }
  17606. return true;
  17607. },
  17608. [i](bool success) {
  17609. EXPECT_FALSE(success);
  17610. delete i;
  17611. });
  17612. });
  17613. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17614. auto se = detail::scope_exit([&] {
  17615. svr.stop();
  17616. listen_thread.join();
  17617. ASSERT_FALSE(svr.is_running());
  17618. });
  17619. svr.wait_until_ready();
  17620. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17621. {
  17622. auto start = std::chrono::steady_clock::now();
  17623. auto res = cli.Get("/stream");
  17624. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17625. std::chrono::steady_clock::now() - start)
  17626. .count();
  17627. ASSERT_FALSE(res);
  17628. EXPECT_EQ(Error::Read, res.error());
  17629. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17630. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17631. }
  17632. {
  17633. auto start = std::chrono::steady_clock::now();
  17634. auto res = cli.Get("/stream_without_length");
  17635. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17636. std::chrono::steady_clock::now() - start)
  17637. .count();
  17638. ASSERT_FALSE(res);
  17639. EXPECT_EQ(Error::Read, res.error());
  17640. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17641. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17642. }
  17643. {
  17644. auto start = std::chrono::steady_clock::now();
  17645. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17646. EXPECT_EQ("abcd", string(data, data_length));
  17647. return true;
  17648. });
  17649. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17650. std::chrono::steady_clock::now() - start)
  17651. .count();
  17652. ASSERT_FALSE(res);
  17653. EXPECT_EQ(Error::Read, res.error());
  17654. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17655. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17656. }
  17657. }
  17658. TEST(MaxTimeoutTest, ContentStream) {
  17659. time_t timeout = 2000;
  17660. time_t threshold = 200;
  17661. Server svr;
  17662. Client cli("localhost", PORT);
  17663. max_timeout_test(svr, cli, timeout, threshold);
  17664. }
  17665. #ifdef CPPHTTPLIB_SSL_ENABLED
  17666. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17667. time_t timeout = 2000;
  17668. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17669. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17670. SSLClient cli("localhost", PORT);
  17671. cli.enable_server_certificate_verification(false);
  17672. max_timeout_test(svr, cli, timeout, threshold);
  17673. }
  17674. #endif
  17675. class EventDispatcher {
  17676. public:
  17677. EventDispatcher() {}
  17678. bool wait_event(DataSink *sink) {
  17679. unique_lock<mutex> lk(m_);
  17680. int id = id_;
  17681. // Wait with timeout to prevent hanging if client disconnects
  17682. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17683. [&] { return cid_ == id; })) {
  17684. return false; // Timeout occurred
  17685. }
  17686. sink->write(message_.data(), message_.size());
  17687. return true;
  17688. }
  17689. void send_event(const string &message) {
  17690. lock_guard<mutex> lk(m_);
  17691. cid_ = id_++;
  17692. message_ = message;
  17693. cv_.notify_all();
  17694. }
  17695. private:
  17696. mutex m_;
  17697. condition_variable cv_;
  17698. atomic_int id_{0};
  17699. atomic_int cid_{-1};
  17700. string message_;
  17701. };
  17702. TEST(ClientInThreadTest, Issue2068) {
  17703. EventDispatcher ed;
  17704. Server svr;
  17705. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17706. res.set_chunked_content_provider("text/event-stream",
  17707. [&](size_t /*offset*/, DataSink &sink) {
  17708. return ed.wait_event(&sink);
  17709. });
  17710. });
  17711. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17712. svr.wait_until_ready();
  17713. thread event_thread([&] {
  17714. int id = 0;
  17715. while (svr.is_running()) {
  17716. this_thread::sleep_for(chrono::milliseconds(500));
  17717. std::stringstream ss;
  17718. ss << "data: " << id << "\n\n";
  17719. ed.send_event(ss.str());
  17720. id++;
  17721. }
  17722. });
  17723. auto se = detail::scope_exit([&] {
  17724. svr.stop();
  17725. listen_thread.join();
  17726. event_thread.join();
  17727. ASSERT_FALSE(svr.is_running());
  17728. });
  17729. {
  17730. auto client = detail::make_unique<Client>(HOST, PORT);
  17731. client->set_read_timeout(std::chrono::minutes(10));
  17732. std::atomic<bool> stop{false};
  17733. std::thread t([&] {
  17734. client->Get("/event1",
  17735. [&](const char *, size_t) -> bool { return !stop; });
  17736. });
  17737. std::this_thread::sleep_for(std::chrono::seconds(2));
  17738. stop = true;
  17739. client->stop();
  17740. t.join();
  17741. // Reset client after thread has finished
  17742. client.reset();
  17743. }
  17744. }
  17745. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17746. auto handled = false;
  17747. Server svr;
  17748. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17749. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17750. auto se = detail::scope_exit([&] {
  17751. svr.stop();
  17752. t.join();
  17753. ASSERT_FALSE(svr.is_running());
  17754. ASSERT_FALSE(handled);
  17755. });
  17756. svr.wait_until_ready();
  17757. // Two Content-Length headers with different values — must be rejected
  17758. auto req = "POST /test HTTP/1.1\r\n"
  17759. "Content-Length: 5\r\n"
  17760. "Content-Length: 10\r\n"
  17761. "\r\n"
  17762. "hello";
  17763. std::string response;
  17764. ASSERT_TRUE(send_request(1, req, &response));
  17765. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17766. response.substr(0, response.find("\r\n")));
  17767. }
  17768. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17769. auto handled = false;
  17770. Server svr;
  17771. svr.Post("/test", [&](const Request &, Response &res) {
  17772. handled = true;
  17773. res.set_content("ok", "text/plain");
  17774. });
  17775. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17776. auto se = detail::scope_exit([&] {
  17777. svr.stop();
  17778. t.join();
  17779. ASSERT_FALSE(svr.is_running());
  17780. ASSERT_TRUE(handled);
  17781. });
  17782. svr.wait_until_ready();
  17783. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17784. auto req = "POST /test HTTP/1.1\r\n"
  17785. "Host: localhost\r\n"
  17786. "Content-Length: 5\r\n"
  17787. "Content-Length: 5\r\n"
  17788. "\r\n"
  17789. "hello";
  17790. std::string response;
  17791. ASSERT_TRUE(send_request(1, req, &response));
  17792. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17793. }
  17794. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17795. Server svr;
  17796. svr.Get("/test", [](const Request &, Response &res) {
  17797. res.set_content("ok", "text/plain");
  17798. });
  17799. auto port = svr.bind_to_any_port(HOST);
  17800. thread t = thread([&] { svr.listen_after_bind(); });
  17801. auto se = detail::scope_exit([&] {
  17802. svr.stop();
  17803. t.join();
  17804. ASSERT_FALSE(svr.is_running());
  17805. });
  17806. svr.wait_until_ready();
  17807. auto status_line = [&](const std::string &host_lines) {
  17808. std::string res;
  17809. send_request(
  17810. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17811. &res, port);
  17812. return res.substr(0, res.find("\r\n"));
  17813. };
  17814. const char *accepted[] = {
  17815. "Host: localhost\r\n",
  17816. "Host: a.example:8080\r\n",
  17817. "Host: my_service\r\n",
  17818. "Host: [::1]:8080\r\n",
  17819. "Host: [fe80::1%25eth0]\r\n",
  17820. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17821. };
  17822. for (auto host_lines : accepted) {
  17823. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17824. }
  17825. const char *rejected[] = {
  17826. "Host: a.example\r\nHost: b.example\r\n",
  17827. "Host: a.example\r\nHost: a.example\r\n",
  17828. "Host: a@b.example\r\n",
  17829. "Host: a.example/b\r\n",
  17830. "Host: a.example\\b\r\n",
  17831. "Host: a.example?b\r\n",
  17832. "Host: a.example#b\r\n",
  17833. "Host: a.example b.example\r\n",
  17834. };
  17835. for (auto host_lines : rejected) {
  17836. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17837. << host_lines;
  17838. }
  17839. }
  17840. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17841. Server svr;
  17842. svr.Get("/", [](const Request &req, Response &res) {
  17843. EXPECT_EQ(2U, req.trailers.size());
  17844. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17845. // Denied
  17846. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17847. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17848. // Accepted
  17849. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17850. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17851. EXPECT_TRUE(req.has_trailer("X-World"));
  17852. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17853. res.set_content("ok", "text/plain");
  17854. });
  17855. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17856. auto se = detail::scope_exit([&] {
  17857. svr.stop();
  17858. t.join();
  17859. ASSERT_FALSE(svr.is_running());
  17860. });
  17861. svr.wait_until_ready();
  17862. const std::string req = "GET / HTTP/1.1\r\n"
  17863. "Transfer-Encoding: chunked\r\n"
  17864. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17865. "\r\n"
  17866. "0\r\n"
  17867. "Content-Length: 10\r\n"
  17868. "Host: internal.local\r\n"
  17869. "Content-Type: malicious/content\r\n"
  17870. "Cookie: any\r\n"
  17871. "Set-Cookie: any\r\n"
  17872. "X-Forwarded-For: attacker.com\r\n"
  17873. "X-Real-Ip: 1.1.1.1\r\n"
  17874. "X-Hello: hello\r\n"
  17875. "X-World: world\r\n"
  17876. "\r\n";
  17877. std::string res;
  17878. ASSERT_TRUE(send_request(1, req, &res));
  17879. }
  17880. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17881. // several field lines, and the combined value is what has to be parsed. A
  17882. // Trailer field split across lines therefore declares every name it lists;
  17883. // reading only the first line silently drops the trailers the later lines
  17884. // declare. The prohibited-trailer filter still applies to every line.
  17885. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17886. Server svr;
  17887. size_t observed_trailer_count = 0;
  17888. std::string observed_hello;
  17889. std::string observed_world;
  17890. bool observed_content_length = true;
  17891. svr.Get("/", [&](const Request &req, Response &res) {
  17892. observed_trailer_count = req.trailers.size();
  17893. observed_hello = req.get_trailer_value("X-Hello");
  17894. observed_world = req.get_trailer_value("X-World");
  17895. observed_content_length = req.has_trailer("Content-Length");
  17896. res.set_content("ok", "text/plain");
  17897. });
  17898. auto port = svr.bind_to_any_port(HOST);
  17899. thread t = thread([&]() { svr.listen_after_bind(); });
  17900. auto se = detail::scope_exit([&] {
  17901. svr.stop();
  17902. t.join();
  17903. ASSERT_FALSE(svr.is_running());
  17904. });
  17905. svr.wait_until_ready();
  17906. const std::string req = "GET / HTTP/1.1\r\n"
  17907. "Host: localhost\r\n"
  17908. "Transfer-Encoding: chunked\r\n"
  17909. "Trailer: X-Hello\r\n"
  17910. "Trailer: X-World, Content-Length\r\n"
  17911. "\r\n"
  17912. "0\r\n"
  17913. "X-Hello: hello\r\n"
  17914. "X-World: world\r\n"
  17915. "Content-Length: 10\r\n"
  17916. "\r\n";
  17917. std::string res;
  17918. ASSERT_TRUE(send_request(1, req, &res, port));
  17919. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17920. // Accepted: both field lines contribute to the declared set
  17921. EXPECT_EQ(2U, observed_trailer_count);
  17922. EXPECT_EQ(observed_hello, "hello");
  17923. EXPECT_EQ(observed_world, "world");
  17924. // Denied: a prohibited name stays prohibited on a later field line
  17925. EXPECT_FALSE(observed_content_length);
  17926. }
  17927. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17928. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17929. // unbounded run of fields that are never declared, because the counter would
  17930. // only advance for declared fields.
  17931. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17932. Server svr;
  17933. bool handler_called = false;
  17934. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17935. handler_called = true;
  17936. res.set_content("ok", "text/plain");
  17937. });
  17938. auto port = svr.bind_to_any_port(HOST);
  17939. thread t = thread([&]() { svr.listen_after_bind(); });
  17940. auto se = detail::scope_exit([&] {
  17941. svr.stop();
  17942. t.join();
  17943. ASSERT_FALSE(svr.is_running());
  17944. });
  17945. svr.wait_until_ready();
  17946. // Declare nothing, then send far more undeclared trailer fields than the
  17947. // header-count limit. Parsing must stop and reject the request rather than
  17948. // read every line.
  17949. std::string req = "GET / HTTP/1.1\r\n"
  17950. "Transfer-Encoding: chunked\r\n"
  17951. "\r\n"
  17952. "0\r\n";
  17953. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17954. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17955. }
  17956. req += "\r\n";
  17957. std::string res;
  17958. ASSERT_TRUE(send_request(1, req, &res, port));
  17959. // The request is rejected before the handler runs.
  17960. EXPECT_FALSE(handler_called);
  17961. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17962. }
  17963. // The set of declared trailer names is capped so a peer cannot grow it without
  17964. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17965. // declared past the cap is not honored, even if the field is actually sent.
  17966. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17967. Server svr;
  17968. // One name inside the cap and one past it, so the test tracks the cap rather
  17969. // than a fixed count.
  17970. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17971. const std::string within_cap_name = "X-T-0";
  17972. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17973. bool observed_within_cap = false;
  17974. bool observed_past_cap = false;
  17975. svr.Get("/", [&](const Request &req, Response &res) {
  17976. observed_within_cap = req.has_trailer(within_cap_name);
  17977. observed_past_cap = req.has_trailer(past_cap_name);
  17978. res.set_content("ok", "text/plain");
  17979. });
  17980. auto port = svr.bind_to_any_port(HOST);
  17981. thread t = thread([&]() { svr.listen_after_bind(); });
  17982. auto se = detail::scope_exit([&] {
  17983. svr.stop();
  17984. t.join();
  17985. ASSERT_FALSE(svr.is_running());
  17986. });
  17987. svr.wait_until_ready();
  17988. // Declare more trailer names than the cap in a single Trailer field, then
  17989. // actually send the first (within the cap) and the last (past it).
  17990. std::string trailer_decl = "Trailer: ";
  17991. for (int i = 0; i < declared_count; i++) {
  17992. if (i != 0) { trailer_decl += ", "; }
  17993. trailer_decl += "X-T-" + std::to_string(i);
  17994. }
  17995. trailer_decl += "\r\n";
  17996. const std::string req = "GET / HTTP/1.1\r\n"
  17997. "Host: localhost\r\n"
  17998. "Transfer-Encoding: chunked\r\n" +
  17999. trailer_decl +
  18000. "\r\n"
  18001. "0\r\n" +
  18002. within_cap_name + ": a\r\n" + past_cap_name +
  18003. ": b\r\n"
  18004. "\r\n";
  18005. std::string res;
  18006. ASSERT_TRUE(send_request(1, req, &res, port));
  18007. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18008. // A name within the cap is honored; one declared past the cap is dropped.
  18009. EXPECT_TRUE(observed_within_cap);
  18010. EXPECT_FALSE(observed_past_cap);
  18011. }
  18012. // A direct client that is not listed in trusted_proxies must not be able to
  18013. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18014. // the peer address on the actual TCP connection determines whether the
  18015. // header is honored.
  18016. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18017. Server svr;
  18018. // Deliberately does NOT include the loopback address the test client
  18019. // actually connects from, so the direct connection is not a trusted proxy.
  18020. svr.set_trusted_proxies({"203.0.113.66"});
  18021. std::string observed_remote_addr;
  18022. svr.Get("/ip", [&](const Request &req, Response &res) {
  18023. observed_remote_addr = req.remote_addr;
  18024. res.set_content("ok", "text/plain");
  18025. });
  18026. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18027. auto se = detail::scope_exit([&] {
  18028. svr.stop();
  18029. t.join();
  18030. ASSERT_FALSE(svr.is_running());
  18031. });
  18032. svr.wait_until_ready();
  18033. Client cli(HOST, PORT);
  18034. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18036. EXPECT_EQ(StatusCode::OK_200, res->status);
  18037. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18038. // ignored entirely and the real connection-level address retained.
  18039. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18040. observed_remote_addr == "127.0.0.1");
  18041. }
  18042. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18043. Server svr;
  18044. std::string observed_remote_addr;
  18045. std::string observed_xff;
  18046. svr.Get("/ip", [&](const Request &req, Response &res) {
  18047. observed_remote_addr = req.remote_addr;
  18048. observed_xff = req.get_header_value("X-Forwarded-For");
  18049. res.set_content("ok", "text/plain");
  18050. });
  18051. thread t = thread([&]() { svr.listen(HOST, PORT); });
  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. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18061. EXPECT_EQ(StatusCode::OK_200, res->status);
  18062. EXPECT_EQ(observed_xff, "203.0.113.66");
  18063. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18064. observed_remote_addr == "127.0.0.1");
  18065. }
  18066. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18067. Server svr;
  18068. svr.set_trusted_proxies({"203.0.113.66"});
  18069. std::string observed_remote_addr;
  18070. std::string observed_xff;
  18071. svr.Get("/ip", [&](const Request &req, Response &res) {
  18072. observed_remote_addr = req.remote_addr;
  18073. observed_xff = req.get_header_value("X-Forwarded-For");
  18074. res.set_content("ok", "text/plain");
  18075. });
  18076. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18077. auto se = detail::scope_exit([&] {
  18078. svr.stop();
  18079. t.join();
  18080. ASSERT_FALSE(svr.is_running());
  18081. });
  18082. svr.wait_until_ready();
  18083. Client cli(HOST, PORT);
  18084. auto res = cli.Get("/ip");
  18085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18086. EXPECT_EQ(StatusCode::OK_200, res->status);
  18087. EXPECT_EQ(observed_xff, "");
  18088. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18089. observed_remote_addr == "127.0.0.1");
  18090. }
  18091. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18092. Server svr;
  18093. // Include the loopback address the test client actually connects from, so
  18094. // the direct connection itself is recognized as the trusted proxy hop.
  18095. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18096. std::string observed_remote_addr;
  18097. std::string observed_xff;
  18098. svr.Get("/ip", [&](const Request &req, Response &res) {
  18099. observed_remote_addr = req.remote_addr;
  18100. observed_xff = req.get_header_value("X-Forwarded-For");
  18101. res.set_content("ok", "text/plain");
  18102. });
  18103. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18104. auto se = detail::scope_exit([&] {
  18105. svr.stop();
  18106. t.join();
  18107. ASSERT_FALSE(svr.is_running());
  18108. });
  18109. svr.wait_until_ready();
  18110. Client cli(HOST, PORT);
  18111. auto res = cli.Get(
  18112. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18114. EXPECT_EQ(StatusCode::OK_200, res->status);
  18115. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18116. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18117. }
  18118. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18119. Server svr;
  18120. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18121. std::string observed_remote_addr;
  18122. std::string observed_xff;
  18123. svr.Get("/ip", [&](const Request &req, Response &res) {
  18124. observed_remote_addr = req.remote_addr;
  18125. observed_xff = req.get_header_value("X-Forwarded-For");
  18126. res.set_content("ok", "text/plain");
  18127. });
  18128. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18129. auto se = detail::scope_exit([&] {
  18130. svr.stop();
  18131. t.join();
  18132. ASSERT_FALSE(svr.is_running());
  18133. });
  18134. svr.wait_until_ready();
  18135. Client cli(HOST, PORT);
  18136. auto res = cli.Get(
  18137. "/ip",
  18138. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18140. EXPECT_EQ(StatusCode::OK_200, res->status);
  18141. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18142. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18143. }
  18144. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18145. Server svr;
  18146. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18147. std::string observed_remote_addr;
  18148. std::string observed_xff;
  18149. svr.Get("/ip", [&](const Request &req, Response &res) {
  18150. observed_remote_addr = req.remote_addr;
  18151. observed_xff = req.get_header_value("X-Forwarded-For");
  18152. res.set_content("ok", "text/plain");
  18153. });
  18154. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18155. auto se = detail::scope_exit([&] {
  18156. svr.stop();
  18157. t.join();
  18158. ASSERT_FALSE(svr.is_running());
  18159. });
  18160. svr.wait_until_ready();
  18161. Client cli(HOST, PORT);
  18162. auto res = cli.Get(
  18163. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18165. EXPECT_EQ(StatusCode::OK_200, res->status);
  18166. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18167. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18168. // and must not be selected.
  18169. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18170. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18171. }
  18172. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18173. Server svr;
  18174. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18175. std::string observed_remote_addr;
  18176. svr.Get("/ip", [&](const Request &req, Response &res) {
  18177. observed_remote_addr = req.remote_addr;
  18178. res.set_content("ok", "text/plain");
  18179. });
  18180. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18181. auto se = detail::scope_exit([&] {
  18182. svr.stop();
  18183. t.join();
  18184. ASSERT_FALSE(svr.is_running());
  18185. });
  18186. svr.wait_until_ready();
  18187. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18188. // a forged address and the trusted proxy's own address; the forged value must
  18189. // not win over the address the trusted proxy actually recorded.
  18190. Client cli(HOST, PORT);
  18191. auto res = cli.Get(
  18192. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18194. EXPECT_EQ(StatusCode::OK_200, res->status);
  18195. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18196. }
  18197. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18198. Server svr;
  18199. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18200. std::string observed_remote_addr;
  18201. std::string observed_xff;
  18202. svr.Get("/ip", [&](const Request &req, Response &res) {
  18203. observed_remote_addr = req.remote_addr;
  18204. observed_xff = req.get_header_value("X-Forwarded-For");
  18205. res.set_content("ok", "text/plain");
  18206. });
  18207. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18208. auto se = detail::scope_exit([&] {
  18209. svr.stop();
  18210. t.join();
  18211. ASSERT_FALSE(svr.is_running());
  18212. });
  18213. svr.wait_until_ready();
  18214. Client cli(HOST, PORT);
  18215. auto res = cli.Get(
  18216. "/ip",
  18217. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18219. EXPECT_EQ(StatusCode::OK_200, res->status);
  18220. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18221. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18222. }
  18223. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18224. Server svr;
  18225. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18226. std::string observed_remote_addr;
  18227. std::string observed_xff;
  18228. svr.Get("/ip", [&](const Request &req, Response &res) {
  18229. observed_remote_addr = req.remote_addr;
  18230. observed_xff = req.get_header_value("X-Forwarded-For");
  18231. res.set_content("ok", "text/plain");
  18232. });
  18233. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18234. auto se = detail::scope_exit([&] {
  18235. svr.stop();
  18236. t.join();
  18237. ASSERT_FALSE(svr.is_running());
  18238. });
  18239. svr.wait_until_ready();
  18240. std::string raw_req =
  18241. "GET /ip HTTP/1.1\r\n"
  18242. "Host: localhost\r\n"
  18243. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18244. "Connection: close\r\n"
  18245. "\r\n";
  18246. std::string out;
  18247. ASSERT_TRUE(send_request(5, raw_req, &out));
  18248. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18249. // Header parser trims surrounding whitespace of the header value
  18250. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18251. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18252. }
  18253. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18254. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18255. // their own X-Forwarded-For as a separate field line rather than extending the
  18256. // one the client sent, so every occurrence has to be taken into account.
  18257. // Reading only the first one hands back the address the client chose.
  18258. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18259. Server svr;
  18260. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18261. std::string observed_remote_addr;
  18262. size_t observed_xff_count = 0;
  18263. svr.Get("/ip", [&](const Request &req, Response &res) {
  18264. observed_remote_addr = req.remote_addr;
  18265. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18266. res.set_content("ok", "text/plain");
  18267. });
  18268. auto port = svr.bind_to_any_port(HOST);
  18269. thread t = thread([&]() { svr.listen_after_bind(); });
  18270. auto se = detail::scope_exit([&] {
  18271. svr.stop();
  18272. t.join();
  18273. ASSERT_FALSE(svr.is_running());
  18274. });
  18275. svr.wait_until_ready();
  18276. // The client supplies the first field line; the trusted proxy appends the
  18277. // address it observed as a second one.
  18278. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18279. "Host: localhost\r\n"
  18280. "X-Forwarded-For: 1.2.3.4\r\n"
  18281. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18282. "Connection: close\r\n"
  18283. "\r\n";
  18284. std::string out;
  18285. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18286. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18287. EXPECT_EQ(observed_xff_count, 2U);
  18288. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18289. // The same chain spread over one field line per hop derives the same client
  18290. // address, i.e. the split and the comma-joined representations agree.
  18291. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18292. "Host: localhost\r\n"
  18293. "X-Forwarded-For: 1.2.3.4\r\n"
  18294. "X-Forwarded-For: 198.51.100.23\r\n"
  18295. "X-Forwarded-For: 192.0.2.45\r\n"
  18296. "Connection: close\r\n"
  18297. "\r\n";
  18298. out.clear();
  18299. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18300. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18301. EXPECT_EQ(observed_xff_count, 3U);
  18302. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18303. }
  18304. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18305. // crash the server (it used to call front() on an empty vector inside
  18306. // get_client_ip). The connection-level remote address must be retained instead.
  18307. static void run_malformed_xff_test(const std::string &xff_value) {
  18308. Server svr;
  18309. svr.set_trusted_proxies({"192.0.2.45"});
  18310. std::string observed_remote_addr;
  18311. svr.Get("/ip", [&](const Request &req, Response &res) {
  18312. observed_remote_addr = req.remote_addr;
  18313. res.set_content("ok", "text/plain");
  18314. });
  18315. int port = 0;
  18316. thread t = thread([&]() {
  18317. port = svr.bind_to_any_port(HOST);
  18318. svr.listen_after_bind();
  18319. });
  18320. auto se = detail::scope_exit([&] {
  18321. svr.stop();
  18322. t.join();
  18323. ASSERT_FALSE(svr.is_running());
  18324. });
  18325. svr.wait_until_ready();
  18326. Client cli(HOST, port);
  18327. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18329. EXPECT_EQ(StatusCode::OK_200, res->status);
  18330. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18331. observed_remote_addr == "127.0.0.1");
  18332. }
  18333. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18334. run_malformed_xff_test("");
  18335. }
  18336. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18337. run_malformed_xff_test(",");
  18338. }
  18339. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18340. run_malformed_xff_test(", , ,");
  18341. }
  18342. // The same rule applies to Accept: a request whose acceptable types are spread
  18343. // over several field lines must be negotiated against all of them.
  18344. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18345. // case-insensitive connection options. Comparing the whole field value against
  18346. // one option misses a client that sends several of them, and misses every
  18347. // casing but the one written in the comparison.
  18348. //
  18349. // Sends req, reads the response, then reuses the same socket for a second
  18350. // request to find out whether the server kept the connection.
  18351. static void probe_connection_reuse(int port, const std::string &req,
  18352. bool *announced_close, bool *reusable) {
  18353. auto error = Error::Success;
  18354. auto sock = detail::create_client_socket(
  18355. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18356. /*connection_timeout_sec=*/5, 0,
  18357. /*read_timeout_sec=*/1, 0,
  18358. /*write_timeout_sec=*/5, 0, std::string(), error);
  18359. ASSERT_NE(sock, INVALID_SOCKET);
  18360. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18361. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18362. "Host: localhost\r\n"
  18363. "Connection: close\r\n"
  18364. "\r\n";
  18365. std::string first_response;
  18366. std::string second_response;
  18367. detail::process_client_socket(
  18368. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18369. [&](Stream &strm) {
  18370. if (strm.write(req.data(), req.size()) !=
  18371. static_cast<ssize_t>(req.size())) {
  18372. return false;
  18373. }
  18374. char buf[512];
  18375. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18376. // Headers plus the two-byte body of the handler below
  18377. while (reader.getline()) {
  18378. first_response += reader.ptr();
  18379. if (first_response.find("ok") != std::string::npos) { break; }
  18380. }
  18381. if (strm.write(second.data(), second.size()) !=
  18382. static_cast<ssize_t>(second.size())) {
  18383. return true;
  18384. }
  18385. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18386. while (reader2.getline()) {
  18387. second_response += reader2.ptr();
  18388. if (second_response.find("ok") != std::string::npos) { break; }
  18389. }
  18390. return true;
  18391. });
  18392. *announced_close =
  18393. first_response.find("Connection: close") != std::string::npos;
  18394. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18395. }
  18396. class ConnectionTokenTest : public ::testing::Test {
  18397. protected:
  18398. void SetUp() override {
  18399. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18400. res.set_content("ok", "text/plain");
  18401. });
  18402. port_ = svr_.bind_to_any_port(HOST);
  18403. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18404. svr_.wait_until_ready();
  18405. }
  18406. void TearDown() override {
  18407. svr_.stop();
  18408. if (thread_.joinable()) { thread_.join(); }
  18409. }
  18410. Server svr_;
  18411. int port_ = 0;
  18412. thread thread_;
  18413. };
  18414. // "close" alongside another option still closes the connection, and the
  18415. // response says so rather than leaving the peer to discover it.
  18416. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18417. bool announced_close = false;
  18418. bool reusable = true;
  18419. probe_connection_reuse(port_,
  18420. "GET /keepalive HTTP/1.1\r\n"
  18421. "Host: localhost\r\n"
  18422. "Connection: keep-alive, close\r\n"
  18423. "\r\n",
  18424. &announced_close, &reusable);
  18425. EXPECT_TRUE(announced_close);
  18426. EXPECT_FALSE(reusable);
  18427. }
  18428. // "close" split over two field lines is the same list, so it is honored too.
  18429. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18430. bool announced_close = false;
  18431. bool reusable = true;
  18432. probe_connection_reuse(port_,
  18433. "GET /keepalive HTTP/1.1\r\n"
  18434. "Host: localhost\r\n"
  18435. "Connection: keep-alive\r\n"
  18436. "Connection: close\r\n"
  18437. "\r\n",
  18438. &announced_close, &reusable);
  18439. EXPECT_TRUE(announced_close);
  18440. EXPECT_FALSE(reusable);
  18441. }
  18442. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18443. // keep-alive in the spelling everyone actually sends keeps its connection.
  18444. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18445. bool announced_close = false;
  18446. bool reusable = false;
  18447. probe_connection_reuse(port_,
  18448. "GET /keepalive HTTP/1.0\r\n"
  18449. "Host: localhost\r\n"
  18450. "Connection: keep-alive\r\n"
  18451. "\r\n",
  18452. &announced_close, &reusable);
  18453. EXPECT_FALSE(announced_close);
  18454. EXPECT_TRUE(reusable);
  18455. }
  18456. // A token the value merely contains is not the token itself.
  18457. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18458. bool announced_close = false;
  18459. bool reusable = false;
  18460. probe_connection_reuse(port_,
  18461. "GET /keepalive HTTP/1.1\r\n"
  18462. "Host: localhost\r\n"
  18463. "Connection: notclose\r\n"
  18464. "\r\n",
  18465. &announced_close, &reusable);
  18466. EXPECT_FALSE(announced_close);
  18467. EXPECT_TRUE(reusable);
  18468. }
  18469. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18470. Server svr;
  18471. std::vector<std::string> observed_types;
  18472. svr.Get("/", [&](const Request &req, Response &res) {
  18473. observed_types = req.accept_content_types;
  18474. res.set_content("ok", "text/plain");
  18475. });
  18476. auto port = svr.bind_to_any_port(HOST);
  18477. thread t = thread([&]() { svr.listen_after_bind(); });
  18478. auto se = detail::scope_exit([&] {
  18479. svr.stop();
  18480. t.join();
  18481. ASSERT_FALSE(svr.is_running());
  18482. });
  18483. svr.wait_until_ready();
  18484. Client cli(HOST, port);
  18485. Headers headers;
  18486. headers.emplace("Accept", "text/plain;q=0.5");
  18487. headers.emplace("Accept", "application/json");
  18488. auto res = cli.Get("/", headers);
  18489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18490. EXPECT_EQ(StatusCode::OK_200, res->status);
  18491. // Sorted by q-value, so the second field line's type comes first
  18492. ASSERT_EQ(2U, observed_types.size());
  18493. EXPECT_EQ("application/json", observed_types[0]);
  18494. EXPECT_EQ("text/plain", observed_types[1]);
  18495. }
  18496. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18497. // empty field line must not contribute a bare comma to the combined value.
  18498. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18499. Server svr;
  18500. std::vector<std::string> observed_types;
  18501. svr.Get("/", [&](const Request &req, Response &res) {
  18502. observed_types = req.accept_content_types;
  18503. res.set_content("ok", "text/plain");
  18504. });
  18505. auto port = svr.bind_to_any_port(HOST);
  18506. thread t = thread([&]() { svr.listen_after_bind(); });
  18507. auto se = detail::scope_exit([&] {
  18508. svr.stop();
  18509. t.join();
  18510. ASSERT_FALSE(svr.is_running());
  18511. });
  18512. svr.wait_until_ready();
  18513. // Empty first field line, then a real one
  18514. std::string raw_req = "GET / HTTP/1.1\r\n"
  18515. "Host: localhost\r\n"
  18516. "Accept:\r\n"
  18517. "Accept: application/json\r\n"
  18518. "Connection: close\r\n"
  18519. "\r\n";
  18520. std::string out;
  18521. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18522. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18523. ASSERT_EQ(1U, observed_types.size());
  18524. EXPECT_EQ("application/json", observed_types[0]);
  18525. }
  18526. // The skip in get_combined_header_value() is what keeps an empty field line
  18527. // from contributing a bare comma. Only a trailing empty field line exercises
  18528. // it: a leading one is already covered by the "combined is still empty" check,
  18529. // and parse_accept_header() now ignores the empty element either way, so the
  18530. // request-level test above can no longer tell the two apart.
  18531. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18532. Headers headers;
  18533. headers.emplace("Accept", "text/html");
  18534. headers.emplace("Accept", "");
  18535. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18536. headers.clear();
  18537. headers.emplace("Accept", "");
  18538. headers.emplace("Accept", "application/json");
  18539. EXPECT_EQ("application/json",
  18540. detail::get_combined_header_value(headers, "Accept"));
  18541. }
  18542. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18543. // An encoding offered on a later Accept-Encoding field line is still offered.
  18544. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18545. Server svr;
  18546. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18547. res.set_content(std::string(1024, 'x'), "text/plain");
  18548. });
  18549. auto port = svr.bind_to_any_port(HOST);
  18550. thread t = thread([&]() { svr.listen_after_bind(); });
  18551. auto se = detail::scope_exit([&] {
  18552. svr.stop();
  18553. t.join();
  18554. ASSERT_FALSE(svr.is_running());
  18555. });
  18556. svr.wait_until_ready();
  18557. Client cli(HOST, port);
  18558. cli.set_decompress(false);
  18559. Headers headers;
  18560. headers.emplace("Accept-Encoding", "identity");
  18561. headers.emplace("Accept-Encoding", "gzip");
  18562. auto res = cli.Get("/", headers);
  18563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18564. EXPECT_EQ(StatusCode::OK_200, res->status);
  18565. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18566. }
  18567. #endif
  18568. #ifndef _WIN32
  18569. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18570. Server svr;
  18571. svr.Post("/post", [&](const Request &req, Response &res) {
  18572. res.set_content(req.body, "text/plain");
  18573. });
  18574. svr.Put("/put", [&](const Request &req, Response &res) {
  18575. res.set_content(req.body, "text/plain");
  18576. });
  18577. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18578. res.set_content(req.body, "text/plain");
  18579. });
  18580. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18581. res.set_content(req.body, "text/plain");
  18582. });
  18583. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18584. auto se = detail::scope_exit([&] {
  18585. svr.stop();
  18586. t.join();
  18587. ASSERT_FALSE(svr.is_running());
  18588. });
  18589. svr.wait_until_ready();
  18590. std::string resp;
  18591. // POST without Content-Length
  18592. ASSERT_TRUE(send_request(5,
  18593. "POST /post HTTP/1.1\r\n"
  18594. "Host: localhost\r\n"
  18595. "Connection: close\r\n"
  18596. "\r\n",
  18597. &resp));
  18598. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18599. // PUT without Content-Length
  18600. resp.clear();
  18601. ASSERT_TRUE(send_request(5,
  18602. "PUT /put HTTP/1.1\r\n"
  18603. "Host: localhost\r\n"
  18604. "Connection: close\r\n"
  18605. "\r\n",
  18606. &resp));
  18607. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18608. // PATCH without Content-Length
  18609. resp.clear();
  18610. ASSERT_TRUE(send_request(5,
  18611. "PATCH /patch HTTP/1.1\r\n"
  18612. "Host: localhost\r\n"
  18613. "Connection: close\r\n"
  18614. "\r\n",
  18615. &resp));
  18616. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18617. // DELETE without Content-Length
  18618. resp.clear();
  18619. ASSERT_TRUE(send_request(5,
  18620. "DELETE /delete HTTP/1.1\r\n"
  18621. "Host: localhost\r\n"
  18622. "Connection: close\r\n"
  18623. "\r\n",
  18624. &resp));
  18625. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18626. }
  18627. #endif
  18628. //==============================================================================
  18629. // open_stream() Tests
  18630. //==============================================================================
  18631. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18632. std::string result;
  18633. char buf[8192];
  18634. ssize_t n;
  18635. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18636. result.append(buf, static_cast<size_t>(n));
  18637. }
  18638. return result;
  18639. }
  18640. // Mock stream for unit tests
  18641. class MockStream : public Stream {
  18642. public:
  18643. std::string data;
  18644. size_t pos = 0;
  18645. ssize_t error_after = -1; // -1 = no error
  18646. explicit MockStream(const std::string &d, ssize_t err = -1)
  18647. : data(d), error_after(err) {}
  18648. bool is_readable() const override { return true; }
  18649. bool wait_readable() const override { return true; }
  18650. bool wait_writable() const override { return true; }
  18651. ssize_t read(char *ptr, size_t size) override {
  18652. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18653. if (pos >= data.size()) return 0;
  18654. size_t limit =
  18655. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18656. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18657. std::memcpy(ptr, data.data() + pos, to_read);
  18658. pos += to_read;
  18659. return static_cast<ssize_t>(to_read);
  18660. }
  18661. ssize_t write(const char *, size_t) override { return -1; }
  18662. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18663. ip = "127.0.0.1";
  18664. port = 0;
  18665. }
  18666. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18667. ip = "127.0.0.1";
  18668. port = 0;
  18669. }
  18670. socket_t socket() const override { return INVALID_SOCKET; }
  18671. time_t duration() const override { return 0; }
  18672. };
  18673. TEST(StreamHandleTest, Basic) {
  18674. ClientImpl::StreamHandle handle;
  18675. EXPECT_FALSE(handle.is_valid());
  18676. handle.response = detail::make_unique<Response>();
  18677. handle.error = Error::Connection;
  18678. EXPECT_FALSE(handle.is_valid());
  18679. handle.error = Error::Success;
  18680. EXPECT_TRUE(handle.is_valid());
  18681. }
  18682. TEST(BodyReaderTest, Basic) {
  18683. MockStream stream("Hello, World!");
  18684. detail::BodyReader reader;
  18685. reader.stream = &stream;
  18686. reader.content_length = 13;
  18687. char buf[32];
  18688. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18689. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18690. EXPECT_TRUE(reader.eof);
  18691. }
  18692. TEST(BodyReaderTest, NoStream) {
  18693. detail::BodyReader reader;
  18694. char buf[32];
  18695. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18696. EXPECT_EQ(Error::Connection, reader.last_error);
  18697. }
  18698. TEST(BodyReaderTest, Error) {
  18699. MockStream stream("Hello, World!", 5);
  18700. detail::BodyReader reader;
  18701. reader.stream = &stream;
  18702. reader.content_length = 13;
  18703. char buf[32];
  18704. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18705. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18706. EXPECT_EQ(Error::Read, reader.last_error);
  18707. }
  18708. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18709. // Mock-based StreamHandle tests relying on private internals are removed.
  18710. class OpenStreamTest : public ::testing::Test {
  18711. protected:
  18712. void SetUp() override {
  18713. svr_.Get("/hello", [](const Request &, Response &res) {
  18714. res.set_content("Hello World!", "text/plain");
  18715. });
  18716. svr_.Get("/large", [](const Request &, Response &res) {
  18717. res.set_content(std::string(10000, 'X'), "text/plain");
  18718. });
  18719. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18720. res.set_content("Hello World!", "image/jpeg");
  18721. res.set_header("Content-Encoding", "UTF-8");
  18722. });
  18723. svr_.Get("/chunked", [](const Request &, Response &res) {
  18724. res.set_chunked_content_provider("text/plain",
  18725. [](size_t offset, DataSink &sink) {
  18726. if (offset < 15) {
  18727. sink.write("chunk", 5);
  18728. return true;
  18729. }
  18730. sink.done();
  18731. return true;
  18732. });
  18733. });
  18734. svr_.Get("/compressible", [](const Request &, Response &res) {
  18735. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18736. DataSink &sink) {
  18737. if (offset < 100 * 1024) {
  18738. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18739. sink.write(chunk.data(), chunk.size());
  18740. return true;
  18741. }
  18742. sink.done();
  18743. return true;
  18744. });
  18745. });
  18746. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18747. [](const Request & /*req*/, Response &res) {
  18748. auto i = new int(0);
  18749. res.set_header("Trailer", "Content-Length, X-Allowed");
  18750. res.set_chunked_content_provider(
  18751. "text/plain",
  18752. [i](size_t /*offset*/, DataSink &sink) {
  18753. switch (*i) {
  18754. case 0: sink.os << "123"; break;
  18755. case 1: sink.os << "456"; break;
  18756. case 2: sink.os << "789"; break;
  18757. case 3: {
  18758. sink.done_with_trailer(
  18759. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18760. } break;
  18761. }
  18762. (*i)++;
  18763. return true;
  18764. },
  18765. [i](bool success) {
  18766. EXPECT_TRUE(success);
  18767. delete i;
  18768. });
  18769. });
  18770. // Echo headers endpoint for header-related tests
  18771. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18772. std::string body;
  18773. for (const auto &h : req.headers) {
  18774. body.append(h.first);
  18775. body.push_back(':');
  18776. body.append(h.second);
  18777. body.push_back('\n');
  18778. }
  18779. res.set_content(body, "text/plain");
  18780. });
  18781. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18782. std::string body;
  18783. for (const auto &h : req.headers) {
  18784. body.append(h.first);
  18785. body.push_back(':');
  18786. body.append(h.second);
  18787. body.push_back('\n');
  18788. }
  18789. res.set_content(body, "text/plain");
  18790. });
  18791. port_ = svr_.bind_to_any_port("127.0.0.1");
  18792. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18793. svr_.wait_until_ready();
  18794. }
  18795. void TearDown() override {
  18796. svr_.stop();
  18797. if (thread_.joinable()) thread_.join();
  18798. }
  18799. Server svr_;
  18800. std::thread thread_;
  18801. int port_ = 0;
  18802. };
  18803. TEST_F(OpenStreamTest, Basic) {
  18804. Client cli("127.0.0.1", port_);
  18805. auto handle = cli.open_stream("GET", "/hello");
  18806. EXPECT_TRUE(handle.is_valid());
  18807. EXPECT_EQ("Hello World!", read_all(handle));
  18808. }
  18809. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18810. Client cli("127.0.0.1", port_);
  18811. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18812. ASSERT_TRUE(handle.is_valid());
  18813. EXPECT_EQ("Hello World!", read_all(handle));
  18814. }
  18815. TEST_F(OpenStreamTest, SmallBuffer) {
  18816. Client cli("127.0.0.1", port_);
  18817. auto handle = cli.open_stream("GET", "/hello");
  18818. std::string result;
  18819. char buf[4];
  18820. ssize_t n;
  18821. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18822. result.append(buf, static_cast<size_t>(n));
  18823. EXPECT_EQ("Hello World!", result);
  18824. }
  18825. TEST_F(OpenStreamTest, DefaultHeaders) {
  18826. Client cli("127.0.0.1", port_);
  18827. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18828. {
  18829. auto handle = cli.open_stream("GET", "/echo-headers");
  18830. ASSERT_TRUE(handle.is_valid());
  18831. auto body = read_all(handle);
  18832. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18833. std::string::npos);
  18834. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18835. std::string::npos);
  18836. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18837. }
  18838. // open_stream POST with body and no explicit content_type should NOT add
  18839. // text/plain Content-Type (behavior differs from non-streaming path), but
  18840. // should include Content-Length
  18841. {
  18842. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18843. ASSERT_TRUE(handle.is_valid());
  18844. auto body = read_all(handle);
  18845. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18846. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18847. }
  18848. // open_stream POST with explicit Content-Type should preserve it
  18849. {
  18850. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18851. {{"Content-Type", "application/custom"}},
  18852. "{}", "application/custom");
  18853. ASSERT_TRUE(handle.is_valid());
  18854. auto body = read_all(handle);
  18855. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18856. }
  18857. // User-specified User-Agent must not be overwritten for stream API
  18858. {
  18859. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18860. {{"User-Agent", "MyAgent/1.2"}});
  18861. ASSERT_TRUE(handle.is_valid());
  18862. auto body = read_all(handle);
  18863. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18864. }
  18865. }
  18866. TEST_F(OpenStreamTest, Large) {
  18867. Client cli("127.0.0.1", port_);
  18868. auto handle = cli.open_stream("GET", "/large");
  18869. EXPECT_EQ(10000u, read_all(handle).size());
  18870. }
  18871. TEST_F(OpenStreamTest, ConnectionError) {
  18872. Client cli("127.0.0.1", 9999);
  18873. auto handle = cli.open_stream("GET", "/hello");
  18874. EXPECT_FALSE(handle.is_valid());
  18875. }
  18876. TEST_F(OpenStreamTest, Chunked) {
  18877. Client cli("127.0.0.1", port_);
  18878. auto handle = cli.open_stream("GET", "/chunked");
  18879. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18880. "Transfer-Encoding") == "chunked");
  18881. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18882. }
  18883. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18884. Client cli("127.0.0.1", port_);
  18885. auto handle =
  18886. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18887. ASSERT_TRUE(handle.is_valid());
  18888. // Consume body to allow trailers to be received/parsed
  18889. auto body = read_all(handle);
  18890. // Explicitly parse trailers (ensure trailers are available for assertion)
  18891. handle.parse_trailers_if_needed();
  18892. EXPECT_EQ(std::string("123456789"), body);
  18893. // The response should include a Trailer header declaring both names
  18894. ASSERT_TRUE(handle.response);
  18895. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18896. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18897. handle.response->get_header_value("Trailer"));
  18898. // Prohibited trailer must not be present
  18899. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18900. // Allowed trailer should be present
  18901. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18902. EXPECT_EQ(std::string("yes"),
  18903. handle.response->get_trailer_value("X-Allowed"));
  18904. // Verify trailers are NOT present as regular headers
  18905. EXPECT_EQ(std::string(""),
  18906. handle.response->get_header_value("Content-Length"));
  18907. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18908. }
  18909. // Accepts one connection on an OS-assigned port, which it hands over through
  18910. // port_promise, reads the request head and sends back response. after_send,
  18911. // if given, runs on the connection before it is closed.
  18912. static std::thread
  18913. serve_single_response(std::promise<int> &port_promise,
  18914. const std::string &response,
  18915. std::function<void(socket_t)> after_send = nullptr) {
  18916. return std::thread([&port_promise, response, after_send] {
  18917. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18918. default_socket_options(srv);
  18919. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18920. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18921. sockaddr_in addr{};
  18922. addr.sin_family = AF_INET;
  18923. addr.sin_port = htons(0); // Let OS assign a free port
  18924. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18925. int opt = 1;
  18926. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18927. #ifdef _WIN32
  18928. reinterpret_cast<const char *>(&opt),
  18929. #else
  18930. &opt,
  18931. #endif
  18932. sizeof(opt));
  18933. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18934. ::listen(srv, 1) != 0) {
  18935. port_promise.set_value(-1);
  18936. detail::close_socket(srv);
  18937. return;
  18938. }
  18939. socklen_t addr_len = sizeof(addr);
  18940. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18941. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18942. sockaddr_in cli_addr{};
  18943. socklen_t cli_len = sizeof(cli_addr);
  18944. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18945. if (cli != INVALID_SOCKET) {
  18946. // Read the complete HTTP request (until the blank line that terminates
  18947. // headers) before sending the response. If the server closes the socket
  18948. // while the client's request data is still unread in the kernel receive
  18949. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18950. // connection on both sides: it discards the client's receive buffer
  18951. // (which already holds our response) and causes any in-progress write on
  18952. // the client to fail with ECONNRESET. Reading all request data first
  18953. // ensures close() emits a graceful FIN.
  18954. {
  18955. char rbuf[256];
  18956. std::string req;
  18957. while (req.find("\r\n\r\n") == std::string::npos) {
  18958. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18959. if (n <= 0) { break; }
  18960. req.append(rbuf, static_cast<size_t>(n));
  18961. }
  18962. }
  18963. ::send(cli,
  18964. #ifdef _WIN32
  18965. static_cast<const char *>(response.c_str()),
  18966. static_cast<int>(response.size()),
  18967. #else
  18968. response.c_str(), response.size(),
  18969. #endif
  18970. 0);
  18971. if (after_send) { after_send(cli); }
  18972. detail::close_socket(cli);
  18973. }
  18974. detail::close_socket(srv);
  18975. });
  18976. }
  18977. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18978. #ifndef _WIN32
  18979. signal(SIGPIPE, SIG_IGN);
  18980. #endif
  18981. std::promise<int> port_promise;
  18982. auto port_future = port_promise.get_future();
  18983. auto server_thread =
  18984. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18985. "Content-Type: text/plain\r\n"
  18986. "Content-Length: not-a-number\r\n"
  18987. "Connection: close\r\n"
  18988. "\r\n"
  18989. "hello");
  18990. auto port = port_future.get();
  18991. ASSERT_GT(port, 0);
  18992. Client cli("127.0.0.1", port);
  18993. auto handle = cli.open_stream("GET", "/");
  18994. EXPECT_FALSE(handle.is_valid());
  18995. server_thread.join();
  18996. }
  18997. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18998. #ifndef _WIN32
  18999. signal(SIGPIPE, SIG_IGN);
  19000. #endif
  19001. std::promise<int> port_promise;
  19002. auto port_future = port_promise.get_future();
  19003. auto server_thread = serve_single_response(
  19004. port_promise, "HTTP/1.1 200 OK\r\n"
  19005. "Content-Type: text/plain\r\n"
  19006. "Content-Length: 99999999999999999999999999\r\n"
  19007. "Connection: close\r\n"
  19008. "\r\n"
  19009. "hello");
  19010. auto port = port_future.get();
  19011. ASSERT_GT(port, 0);
  19012. // Historically std::stoull would throw std::out_of_range here and crash
  19013. // the process, then parsing silently clamped to a bogus framing length and
  19014. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19015. // so the stream fails to open, matching the not-a-number case above. The
  19016. // process still must NOT terminate.
  19017. Client cli("127.0.0.1", port);
  19018. auto handle = cli.open_stream("GET", "/");
  19019. EXPECT_FALSE(handle.is_valid());
  19020. server_thread.join();
  19021. }
  19022. // Serves `response` to the single request `fn` makes with a fresh client.
  19023. template <typename Fn>
  19024. static void with_single_response(const std::string &response, Fn fn) {
  19025. #ifndef _WIN32
  19026. signal(SIGPIPE, SIG_IGN);
  19027. #endif
  19028. std::promise<int> port_promise;
  19029. auto port_future = port_promise.get_future();
  19030. auto server_thread = serve_single_response(port_promise, response);
  19031. auto se = detail::scope_exit([&] { server_thread.join(); });
  19032. auto port = port_future.get();
  19033. ASSERT_GT(port, 0);
  19034. Client cli("127.0.0.1", port);
  19035. fn(cli);
  19036. }
  19037. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19038. const char *responses[] = {
  19039. "HTTP/1.1 103 Early Hints\r\n"
  19040. "Link: </style.css>; rel=preload\r\n"
  19041. "\r\n"
  19042. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19043. "HTTP/1.1 100 Continue\r\n"
  19044. "X-Note: interim\r\n"
  19045. "\r\n"
  19046. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19047. };
  19048. for (auto response : responses) {
  19049. with_single_response(response, [](Client &cli) {
  19050. auto res = cli.Get("/");
  19051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19052. EXPECT_EQ(StatusCode::OK_200, res->status);
  19053. EXPECT_EQ("ok", res->body);
  19054. });
  19055. }
  19056. }
  19057. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19058. #ifndef _WIN32
  19059. signal(SIGPIPE, SIG_IGN);
  19060. #endif
  19061. // The server answers the head without asking for the body. Bytes it then
  19062. // reads on the connection would be taken for the body the request declared.
  19063. auto closed_by_client = false;
  19064. std::promise<int> port_promise;
  19065. auto server_thread = serve_single_response(
  19066. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19067. [&](socket_t sock) {
  19068. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19069. char buf[256];
  19070. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19071. });
  19072. Client cli("127.0.0.1", port_promise.get_future().get());
  19073. cli.set_keep_alive(true);
  19074. cli.set_read_timeout(1, 0);
  19075. // Long enough for the client to send Expect: 100-continue.
  19076. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19078. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19079. cli.Get("/second");
  19080. server_thread.join();
  19081. EXPECT_TRUE(closed_by_client);
  19082. }
  19083. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19084. // Long enough for the client to send Expect: 100-continue
  19085. with_single_response(
  19086. "HTTP/1.1 103 Early Hints\r\n"
  19087. "Link: </style.css>; rel=preload\r\n"
  19088. "\r\n"
  19089. "HTTP/1.1 401 Unauthorized\r\n"
  19090. "Content-Length: 0\r\n\r\n",
  19091. [](Client &cli) {
  19092. cli.set_read_timeout(2, 0);
  19093. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19095. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19096. });
  19097. }
  19098. #ifdef CPPHTTPLIB_SSL_ENABLED
  19099. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19100. #ifndef _WIN32
  19101. signal(SIGPIPE, SIG_IGN);
  19102. #endif
  19103. auto reused = false;
  19104. std::promise<int> port_promise;
  19105. auto server_thread = serve_single_response(
  19106. port_promise,
  19107. "HTTP/1.1 401 Unauthorized\r\n"
  19108. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19109. "Content-Length: 0\r\n\r\n",
  19110. [&](socket_t sock) {
  19111. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19112. char buf[256];
  19113. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19114. });
  19115. Client cli("127.0.0.1", port_promise.get_future().get());
  19116. cli.set_keep_alive(true);
  19117. cli.set_digest_auth("user", "pass");
  19118. cli.set_read_timeout(1, 0);
  19119. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19120. server_thread.join();
  19121. EXPECT_FALSE(reused);
  19122. }
  19123. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19124. // Any other answer to CONNECT would read as the origin's response.
  19125. struct {
  19126. const char *response;
  19127. bool passed_on;
  19128. } cases[] = {
  19129. {"HTTP/1.1 201 Created\r\n"
  19130. "Set-Cookie: session=from-proxy\r\n"
  19131. "Content-Length: 0\r\n\r\n",
  19132. false},
  19133. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19134. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19135. "Content-Length: 0\r\n\r\n",
  19136. true},
  19137. };
  19138. for (const auto &c : cases) {
  19139. std::promise<int> port_promise;
  19140. auto server_thread = serve_single_response(port_promise, c.response);
  19141. SSLClient cli("example.com", 443);
  19142. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19143. auto res = cli.Get("/");
  19144. server_thread.join();
  19145. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19146. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19147. if (res) {
  19148. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19149. }
  19150. }
  19151. }
  19152. #endif
  19153. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19154. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19155. // the chunked coding and drop Content-Length, so a front-end that trusts
  19156. // Content-Length would disagree about where the body ends (response
  19157. // smuggling). The client must reject such a response.
  19158. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19159. for (const char *te : {"chunked", "gzip, chunked"}) {
  19160. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19161. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19162. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19163. "5\r\nhello\r\n0\r\n\r\n";
  19164. with_single_response(response, [&](Client &cli) {
  19165. auto res = cli.Get("/");
  19166. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19167. EXPECT_EQ(Error::Read, res.error()) << te;
  19168. });
  19169. with_single_response(response, [&](Client &cli) {
  19170. auto handle = cli.open_stream("GET", "/");
  19171. EXPECT_FALSE(handle.is_valid()) << te;
  19172. EXPECT_EQ(Error::Read, handle.error) << te;
  19173. });
  19174. }
  19175. }
  19176. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19177. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19178. // closing the connection (unlike a request, which must be rejected).
  19179. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19180. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19181. "Transfer-Encoding: chunked\r\n"
  19182. "Connection: close\r\n"
  19183. "\r\n"
  19184. "5\r\nhello\r\n0\r\n\r\n",
  19185. "HTTP/1.1 200 OK\r\n"
  19186. "Transfer-Encoding: gzip\r\n"
  19187. "Connection: close\r\n"
  19188. "\r\n"
  19189. "hello"}) {
  19190. with_single_response(response, [&](Client &cli) {
  19191. auto res = cli.Get("/");
  19192. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19193. EXPECT_EQ("hello", res->body);
  19194. });
  19195. with_single_response(response, [&](Client &cli) {
  19196. auto handle = cli.open_stream("GET", "/");
  19197. ASSERT_TRUE(handle.is_valid()) << response;
  19198. EXPECT_EQ("hello", read_all(handle));
  19199. });
  19200. }
  19201. }
  19202. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19203. // framing headers describe nothing to read and must not be rejected.
  19204. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19205. const std::string framing = "Content-Length: 5\r\n"
  19206. "Transfer-Encoding: chunked\r\n"
  19207. "Connection: close\r\n"
  19208. "\r\n";
  19209. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19210. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19211. });
  19212. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19213. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19214. });
  19215. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19216. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19217. with_single_response(response, [&](Client &cli) {
  19218. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19219. });
  19220. with_single_response(response, [&](Client &cli) {
  19221. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19222. });
  19223. }
  19224. }
  19225. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19226. // response, is faulty framing, so the connection is not reused after it.
  19227. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19228. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19229. "Content-Length: 0\r\n"
  19230. "Transfer-Encoding: chunked\r\n"
  19231. "\r\n"
  19232. "5\r\nhello\r\n0\r\n\r\n",
  19233. "HTTP/1.0 200 Connection established\r\n"
  19234. "Connection: keep-alive\r\n"
  19235. "Transfer-Encoding: chunked\r\n"
  19236. "\r\n"
  19237. "5\r\nhello\r\n0\r\n\r\n"}) {
  19238. with_single_response(response, [&](Client &cli) {
  19239. cli.set_keep_alive(true);
  19240. auto res = cli.Get("/");
  19241. ASSERT_TRUE(res) << response;
  19242. EXPECT_EQ("hello", res->body);
  19243. EXPECT_FALSE(cli.is_socket_open()) << response;
  19244. });
  19245. }
  19246. }
  19247. // A payload max length of 0 means no limit, however the body is framed.
  19248. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19249. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19250. "Transfer-Encoding: chunked\r\n"
  19251. "\r\n"
  19252. "5\r\nhello\r\n0\r\n\r\n",
  19253. "HTTP/1.1 200 OK\r\n"
  19254. "Connection: close\r\n"
  19255. "\r\n"
  19256. "hello"}) {
  19257. with_single_response(response, [&](Client &cli) {
  19258. cli.set_payload_max_length(0);
  19259. auto res = cli.Get("/");
  19260. ASSERT_TRUE(res) << response;
  19261. EXPECT_EQ("hello", res->body) << response;
  19262. });
  19263. }
  19264. }
  19265. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19266. Server svr;
  19267. svr.set_payload_max_length(0);
  19268. svr.Post("/echo", [](const Request &req, Response &res) {
  19269. res.set_content(req.body, "text/plain");
  19270. });
  19271. auto port = svr.bind_to_any_port(HOST);
  19272. thread t = thread([&] { svr.listen_after_bind(); });
  19273. auto se = detail::scope_exit([&] {
  19274. svr.stop();
  19275. t.join();
  19276. ASSERT_FALSE(svr.is_running());
  19277. });
  19278. svr.wait_until_ready();
  19279. Client cli(HOST, port);
  19280. auto res = cli.Post(
  19281. "/echo",
  19282. [](size_t /*offset*/, DataSink &sink) {
  19283. sink.write("hello", 5);
  19284. sink.done();
  19285. return true;
  19286. },
  19287. "text/plain");
  19288. ASSERT_TRUE(res);
  19289. EXPECT_EQ(StatusCode::OK_200, res->status);
  19290. EXPECT_EQ("hello", res->body);
  19291. }
  19292. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19293. TEST_F(OpenStreamTest, Gzip) {
  19294. Client cli("127.0.0.1", port_);
  19295. auto handle = cli.open_stream("GET", "/compressible", {},
  19296. {{"Accept-Encoding", "gzip"}});
  19297. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19298. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19299. }
  19300. #endif
  19301. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19302. TEST_F(OpenStreamTest, Brotli) {
  19303. Client cli("127.0.0.1", port_);
  19304. auto handle =
  19305. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19306. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19307. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19308. }
  19309. #endif
  19310. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19311. TEST_F(OpenStreamTest, Zstd) {
  19312. Client cli("127.0.0.1", port_);
  19313. auto handle = cli.open_stream("GET", "/compressible", {},
  19314. {{"Accept-Encoding", "zstd"}});
  19315. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19316. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19317. }
  19318. #endif
  19319. #ifdef CPPHTTPLIB_SSL_ENABLED
  19320. class SSLOpenStreamTest : public ::testing::Test {
  19321. protected:
  19322. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19323. void SetUp() override {
  19324. svr_.Get("/hello", [](const Request &, Response &res) {
  19325. res.set_content("Hello SSL World!", "text/plain");
  19326. });
  19327. svr_.Get("/chunked", [](const Request &, Response &res) {
  19328. res.set_chunked_content_provider("text/plain",
  19329. [](size_t offset, DataSink &sink) {
  19330. if (offset < 15) {
  19331. sink.write("chunk", 5);
  19332. return true;
  19333. }
  19334. sink.done();
  19335. return true;
  19336. });
  19337. });
  19338. svr_.Post("/echo", [](const Request &req, Response &res) {
  19339. res.set_content(req.body, req.get_header_value("Content-Type"));
  19340. });
  19341. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19342. std::string body = req.body;
  19343. res.set_chunked_content_provider(
  19344. "text/plain", [body](size_t offset, DataSink &sink) {
  19345. if (offset < body.size()) {
  19346. sink.write(body.data() + offset, body.size() - offset);
  19347. }
  19348. sink.done();
  19349. return true;
  19350. });
  19351. });
  19352. port_ = svr_.bind_to_any_port("127.0.0.1");
  19353. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19354. svr_.wait_until_ready();
  19355. }
  19356. void TearDown() override {
  19357. svr_.stop();
  19358. if (thread_.joinable()) thread_.join();
  19359. }
  19360. SSLServer svr_;
  19361. std::thread thread_;
  19362. int port_ = 0;
  19363. };
  19364. TEST_F(SSLOpenStreamTest, Basic) {
  19365. SSLClient cli("127.0.0.1", port_);
  19366. cli.enable_server_certificate_verification(false);
  19367. auto handle = cli.open_stream("GET", "/hello");
  19368. ASSERT_TRUE(handle.is_valid());
  19369. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19370. }
  19371. TEST_F(SSLOpenStreamTest, Chunked) {
  19372. SSLClient cli("127.0.0.1", port_);
  19373. cli.enable_server_certificate_verification(false);
  19374. auto handle = cli.open_stream("GET", "/chunked");
  19375. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19376. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19377. "Transfer-Encoding") == "chunked");
  19378. auto body = read_all(handle);
  19379. EXPECT_EQ("chunkchunkchunk", body);
  19380. }
  19381. TEST_F(SSLOpenStreamTest, Post) {
  19382. SSLClient cli("127.0.0.1", port_);
  19383. cli.enable_server_certificate_verification(false);
  19384. auto handle =
  19385. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19386. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19387. EXPECT_EQ(200, handle.response->status);
  19388. auto body = read_all(handle);
  19389. EXPECT_EQ("Hello SSL POST", body);
  19390. }
  19391. TEST_F(SSLOpenStreamTest, PostChunked) {
  19392. SSLClient cli("127.0.0.1", port_);
  19393. cli.enable_server_certificate_verification(false);
  19394. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19395. "Chunked SSL Data", "text/plain");
  19396. ASSERT_TRUE(handle.is_valid());
  19397. EXPECT_EQ(200, handle.response->status);
  19398. auto body = read_all(handle);
  19399. EXPECT_EQ("Chunked SSL Data", body);
  19400. }
  19401. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19402. // Content-Length is terminated by the server closing the connection. When the
  19403. // SSL peer sends a close_notify after the body, the client must treat it as a
  19404. // clean EOF and return a successful response rather than an error.
  19405. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19406. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19407. ASSERT_TRUE(svr.is_valid());
  19408. svr.set_keep_alive_max_count(1);
  19409. const std::string expected_body = "Hello from connection-close response!";
  19410. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19411. res.set_content_provider("text/plain",
  19412. [&](size_t offset, DataSink &sink) -> bool {
  19413. if (offset < expected_body.size()) {
  19414. sink.write(expected_body.data() + offset,
  19415. expected_body.size() - offset);
  19416. }
  19417. sink.done();
  19418. return true;
  19419. });
  19420. });
  19421. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19422. auto se = detail::scope_exit([&] {
  19423. svr.stop();
  19424. listen_thread.join();
  19425. ASSERT_FALSE(svr.is_running());
  19426. });
  19427. svr.wait_until_ready();
  19428. SSLClient cli(HOST, PORT);
  19429. cli.enable_server_certificate_verification(false);
  19430. auto res = cli.Get("/no-content-length");
  19431. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19432. EXPECT_EQ(StatusCode::OK_200, res->status);
  19433. EXPECT_EQ(expected_body, res->body);
  19434. }
  19435. #endif // CPPHTTPLIB_SSL_ENABLED
  19436. //==============================================================================
  19437. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19438. // results for various scenarios.
  19439. //==============================================================================
  19440. TEST(ParityTest, GetVsOpenStream) {
  19441. Server svr;
  19442. const std::string path = "/parity";
  19443. const std::string content = "Parity test content: hello world";
  19444. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19445. res.set_content(content, "text/plain");
  19446. });
  19447. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19448. auto se = detail::scope_exit([&] {
  19449. svr.stop();
  19450. t.join();
  19451. ASSERT_FALSE(svr.is_running());
  19452. });
  19453. svr.wait_until_ready();
  19454. Client cli(HOST, PORT);
  19455. // Non-stream path
  19456. auto r1 = cli.Get(path);
  19457. ASSERT_TRUE(r1);
  19458. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19459. // Stream path
  19460. auto h = cli.open_stream("GET", path);
  19461. ASSERT_TRUE(h.is_valid());
  19462. EXPECT_EQ(r1->body, read_all(h));
  19463. }
  19464. // Helper to compress data with provided compressor type T
  19465. template <typename Compressor>
  19466. static std::string compress_payload_for_parity(const std::string &in) {
  19467. std::string out;
  19468. Compressor compressor;
  19469. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19470. [&](const char *data, size_t n) {
  19471. out.append(data, n);
  19472. return true;
  19473. });
  19474. EXPECT_TRUE(ok);
  19475. return out;
  19476. }
  19477. // Helper function for compression parity tests
  19478. template <typename Compressor>
  19479. static void test_compression_parity(const std::string &original,
  19480. const std::string &path,
  19481. const std::string &encoding) {
  19482. const std::string compressed =
  19483. compress_payload_for_parity<Compressor>(original);
  19484. Server svr;
  19485. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19486. res.set_content(compressed, "application/octet-stream");
  19487. res.set_header("Content-Encoding", encoding);
  19488. });
  19489. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19490. auto se = detail::scope_exit([&] {
  19491. svr.stop();
  19492. t.join();
  19493. ASSERT_FALSE(svr.is_running());
  19494. });
  19495. svr.wait_until_ready();
  19496. Client cli(HOST, PORT);
  19497. // Non-streaming
  19498. {
  19499. auto res = cli.Get(path);
  19500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19501. EXPECT_EQ(StatusCode::OK_200, res->status);
  19502. EXPECT_EQ(original, res->body);
  19503. }
  19504. // Streaming
  19505. {
  19506. auto h = cli.open_stream("GET", path);
  19507. ASSERT_TRUE(h.is_valid());
  19508. EXPECT_EQ(original, read_all(h));
  19509. }
  19510. }
  19511. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19512. TEST(ParityTest, Gzip) {
  19513. test_compression_parity<detail::gzip_compressor>(
  19514. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19515. }
  19516. #endif
  19517. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19518. TEST(ParityTest, Brotli) {
  19519. test_compression_parity<detail::brotli_compressor>(
  19520. "Hello, brotli parity test payload", "/parity-br", "br");
  19521. }
  19522. #endif
  19523. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19524. TEST(ParityTest, Zstd) {
  19525. test_compression_parity<detail::zstd_compressor>(
  19526. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19527. }
  19528. #endif
  19529. //==============================================================================
  19530. // New Stream API Tests
  19531. //==============================================================================
  19532. inline std::string read_body(httplib::stream::Result &result) {
  19533. std::string body;
  19534. while (result.next()) {
  19535. body.append(result.data(), result.size());
  19536. }
  19537. return body;
  19538. }
  19539. TEST(ClientConnectionTest, Basic) {
  19540. httplib::ClientConnection conn;
  19541. EXPECT_FALSE(conn.is_open());
  19542. conn.sock = 1;
  19543. EXPECT_TRUE(conn.is_open());
  19544. httplib::ClientConnection conn2(std::move(conn));
  19545. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19546. conn2.sock = INVALID_SOCKET;
  19547. }
  19548. // Unified test server for all stream::* tests
  19549. class StreamApiTest : public ::testing::Test {
  19550. protected:
  19551. void SetUp() override {
  19552. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19553. res.set_content("Hello World!", "text/plain");
  19554. });
  19555. svr_.Get("/echo-params",
  19556. [](const httplib::Request &req, httplib::Response &res) {
  19557. std::string r;
  19558. for (const auto &p : req.params) {
  19559. if (!r.empty()) r += "&";
  19560. r += p.first + "=" + p.second;
  19561. }
  19562. res.set_content(r, "text/plain");
  19563. });
  19564. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19565. res.set_content(req.body, req.get_header_value("Content-Type"));
  19566. });
  19567. svr_.Post("/echo-headers",
  19568. [](const httplib::Request &req, httplib::Response &res) {
  19569. std::string r;
  19570. for (const auto &h : req.headers)
  19571. r += h.first + ": " + h.second + "\n";
  19572. res.set_content(r, "text/plain");
  19573. });
  19574. svr_.Post("/echo-params",
  19575. [](const httplib::Request &req, httplib::Response &res) {
  19576. std::string r = "params:";
  19577. for (const auto &p : req.params)
  19578. r += p.first + "=" + p.second + ";";
  19579. res.set_content(r + " body:" + req.body, "text/plain");
  19580. });
  19581. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19582. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19583. });
  19584. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19585. res.set_content("PUT:" + req.body, "text/plain");
  19586. });
  19587. svr_.Patch("/echo",
  19588. [](const httplib::Request &req, httplib::Response &res) {
  19589. res.set_content("PATCH:" + req.body, "text/plain");
  19590. });
  19591. svr_.Delete(
  19592. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19593. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19594. "text/plain");
  19595. });
  19596. svr_.Get("/head-test",
  19597. [](const httplib::Request &, httplib::Response &res) {
  19598. res.set_content("body for HEAD", "text/plain");
  19599. });
  19600. svr_.Options("/options",
  19601. [](const httplib::Request &, httplib::Response &res) {
  19602. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19603. });
  19604. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19605. svr_.wait_until_ready();
  19606. }
  19607. void TearDown() override {
  19608. svr_.stop();
  19609. if (thread_.joinable()) thread_.join();
  19610. }
  19611. httplib::Server svr_;
  19612. std::thread thread_;
  19613. };
  19614. // stream::Get tests
  19615. TEST_F(StreamApiTest, GetBasic) {
  19616. httplib::Client cli(HOST, PORT);
  19617. auto result = httplib::stream::Get(cli, "/hello");
  19618. ASSERT_TRUE(result.is_valid());
  19619. EXPECT_EQ(200, result.status());
  19620. EXPECT_EQ("Hello World!", read_body(result));
  19621. }
  19622. TEST_F(StreamApiTest, GetWithParams) {
  19623. httplib::Client cli(HOST, PORT);
  19624. httplib::Params params{{"foo", "bar"}};
  19625. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19626. ASSERT_TRUE(result.is_valid());
  19627. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19628. }
  19629. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19630. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19631. httplib::Client cli(HOST, PORT);
  19632. cli.set_payload_max_length(0);
  19633. auto result = httplib::stream::Get(cli, "/hello");
  19634. ASSERT_TRUE(result.is_valid());
  19635. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19636. EXPECT_EQ("Hello World!", read_body(result));
  19637. }
  19638. #endif
  19639. TEST_F(StreamApiTest, GetConnectionError) {
  19640. httplib::Client cli(HOST, 9999);
  19641. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19642. }
  19643. TEST_F(StreamApiTest, Get404) {
  19644. httplib::Client cli(HOST, PORT);
  19645. auto result = httplib::stream::Get(cli, "/nonexistent");
  19646. EXPECT_TRUE(result.is_valid());
  19647. EXPECT_EQ(404, result.status());
  19648. }
  19649. // stream::Post tests
  19650. TEST_F(StreamApiTest, PostBasic) {
  19651. httplib::Client cli(HOST, PORT);
  19652. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19653. "application/json");
  19654. ASSERT_TRUE(result.is_valid());
  19655. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19656. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19657. }
  19658. TEST_F(StreamApiTest, PostWithHeaders) {
  19659. httplib::Client cli(HOST, PORT);
  19660. httplib::Headers headers{{"X-Custom", "value"}};
  19661. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19662. "text/plain");
  19663. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19664. }
  19665. TEST_F(StreamApiTest, PostWithParams) {
  19666. httplib::Client cli(HOST, PORT);
  19667. httplib::Params params{{"k", "v"}};
  19668. auto result =
  19669. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19670. auto body = read_body(result);
  19671. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19672. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19673. }
  19674. TEST_F(StreamApiTest, PostLarge) {
  19675. httplib::Client cli(HOST, PORT);
  19676. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19677. size_t total = 0;
  19678. while (result.next()) {
  19679. total += result.size();
  19680. }
  19681. EXPECT_EQ(100u * 1024u, total);
  19682. }
  19683. // stream::Put/Patch tests
  19684. TEST_F(StreamApiTest, PutAndPatch) {
  19685. httplib::Client cli(HOST, PORT);
  19686. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19687. EXPECT_EQ("PUT:test", read_body(put));
  19688. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19689. EXPECT_EQ("PATCH:test", read_body(patch));
  19690. }
  19691. // stream::Delete tests
  19692. TEST_F(StreamApiTest, Delete) {
  19693. httplib::Client cli(HOST, PORT);
  19694. auto del1 = httplib::stream::Delete(cli, "/resource");
  19695. EXPECT_EQ("Deleted", read_body(del1));
  19696. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19697. EXPECT_EQ("Deleted:data", read_body(del2));
  19698. }
  19699. // stream::Head/Options tests
  19700. TEST_F(StreamApiTest, HeadAndOptions) {
  19701. httplib::Client cli(HOST, PORT);
  19702. auto head = httplib::stream::Head(cli, "/head-test");
  19703. EXPECT_TRUE(head.is_valid());
  19704. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19705. auto opts = httplib::stream::Options(cli, "/options");
  19706. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19707. }
  19708. // SSL stream::* tests
  19709. #ifdef CPPHTTPLIB_SSL_ENABLED
  19710. class SSLStreamApiTest : public ::testing::Test {
  19711. protected:
  19712. void SetUp() override {
  19713. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19714. res.set_content("Hello SSL!", "text/plain");
  19715. });
  19716. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19717. res.set_content(req.body, "text/plain");
  19718. });
  19719. port_ = svr_.bind_to_any_port("127.0.0.1");
  19720. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19721. svr_.wait_until_ready();
  19722. }
  19723. void TearDown() override {
  19724. svr_.stop();
  19725. if (thread_.joinable()) thread_.join();
  19726. }
  19727. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19728. std::thread thread_;
  19729. int port_ = 0;
  19730. };
  19731. TEST_F(SSLStreamApiTest, GetAndPost) {
  19732. httplib::SSLClient cli("127.0.0.1", port_);
  19733. cli.enable_server_certificate_verification(false);
  19734. auto get = httplib::stream::Get(cli, "/hello");
  19735. EXPECT_EQ("Hello SSL!", read_body(get));
  19736. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19737. EXPECT_EQ("test", read_body(post));
  19738. }
  19739. #endif
  19740. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19741. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19742. // BodyReader
  19743. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19744. // Test that read timeout during streaming is detected
  19745. // Use a large content-length response where server delays mid-stream
  19746. Server svr;
  19747. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19748. // Send a large response with delay in the middle
  19749. res.set_content_provider(
  19750. 1000, // content_length
  19751. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19752. if (offset < 100) {
  19753. // Send first 100 bytes immediately
  19754. std::string data(100, 'A');
  19755. sink.write(data.c_str(), data.size());
  19756. return true;
  19757. }
  19758. // Then delay longer than client timeout
  19759. std::this_thread::sleep_for(std::chrono::seconds(3));
  19760. std::string data(900, 'B');
  19761. sink.write(data.c_str(), data.size());
  19762. return true;
  19763. });
  19764. });
  19765. auto port = 8091;
  19766. std::thread t([&]() { svr.listen("localhost", port); });
  19767. svr.wait_until_ready();
  19768. Client cli("localhost", port);
  19769. cli.set_read_timeout(1, 0); // 1 second timeout
  19770. auto handle = cli.open_stream("GET", "/slow-stream");
  19771. ASSERT_TRUE(handle.is_valid());
  19772. char buf[256];
  19773. ssize_t total = 0;
  19774. ssize_t n;
  19775. bool got_error = false;
  19776. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19777. total += n;
  19778. }
  19779. if (n < 0) {
  19780. got_error = true;
  19781. // Should be timeout or read error
  19782. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19783. handle.get_read_error() == Error::Read)
  19784. << "Actual error: " << to_string(handle.get_read_error());
  19785. }
  19786. // Either we got an error, or we got less data than expected
  19787. EXPECT_TRUE(got_error || total < 1000)
  19788. << "Expected timeout but got all " << total << " bytes";
  19789. svr.stop();
  19790. t.join();
  19791. }
  19792. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19793. // Test connection closed detection via BodyReader
  19794. Server svr;
  19795. std::atomic<bool> close_now{false};
  19796. svr.Get("/will-close", [&](const Request &, Response &res) {
  19797. res.set_content_provider(
  19798. 10000, // Large content_length that we won't fully send
  19799. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19800. if (offset < 100) {
  19801. std::string data(100, 'X');
  19802. sink.write(data.c_str(), data.size());
  19803. return true;
  19804. }
  19805. // Wait for signal then abort
  19806. while (!close_now) {
  19807. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19808. }
  19809. return false; // Abort - server will close connection
  19810. });
  19811. });
  19812. auto port = 8092;
  19813. std::thread t([&]() { svr.listen("localhost", port); });
  19814. svr.wait_until_ready();
  19815. Client cli("localhost", port);
  19816. auto handle = cli.open_stream("GET", "/will-close");
  19817. ASSERT_TRUE(handle.is_valid());
  19818. char buf[256];
  19819. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19820. EXPECT_GT(n, 0) << "First read should succeed";
  19821. // Signal server to close
  19822. close_now = true;
  19823. // Keep reading until error or EOF
  19824. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19825. // Keep reading
  19826. }
  19827. // Should get an error since content_length wasn't satisfied
  19828. if (n < 0) {
  19829. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19830. handle.get_read_error() == Error::Read)
  19831. << "Actual error: " << to_string(handle.get_read_error());
  19832. }
  19833. svr.stop();
  19834. t.join();
  19835. }
  19836. #ifdef CPPHTTPLIB_SSL_ENABLED
  19837. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19838. // Test that read timeout during SSL streaming is detected
  19839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19840. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19841. res.set_content_provider(
  19842. 1000, "text/plain",
  19843. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19844. if (offset < 100) {
  19845. std::string data(100, 'A');
  19846. sink.write(data.c_str(), data.size());
  19847. return true;
  19848. }
  19849. std::this_thread::sleep_for(std::chrono::seconds(3));
  19850. std::string data(900, 'B');
  19851. sink.write(data.c_str(), data.size());
  19852. return true;
  19853. });
  19854. });
  19855. auto port = 8093;
  19856. std::thread t([&]() { svr.listen("localhost", port); });
  19857. svr.wait_until_ready();
  19858. SSLClient cli("localhost", port);
  19859. cli.enable_server_certificate_verification(false);
  19860. cli.set_read_timeout(1, 0); // 1 second timeout
  19861. auto handle = cli.open_stream("GET", "/slow-stream");
  19862. ASSERT_TRUE(handle.is_valid());
  19863. char buf[256];
  19864. ssize_t total = 0;
  19865. ssize_t n;
  19866. bool got_error = false;
  19867. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19868. total += n;
  19869. }
  19870. if (n < 0) {
  19871. got_error = true;
  19872. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19873. handle.get_read_error() == Error::Read)
  19874. << "Actual error: " << to_string(handle.get_read_error());
  19875. }
  19876. EXPECT_TRUE(got_error || total < 1000)
  19877. << "Expected timeout but got all " << total << " bytes";
  19878. svr.stop();
  19879. t.join();
  19880. }
  19881. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19882. // Test SSL connection closed detection
  19883. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19884. std::atomic<bool> close_now{false};
  19885. svr.Get("/will-close", [&](const Request &, Response &res) {
  19886. res.set_content_provider(
  19887. 10000, "text/plain",
  19888. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19889. if (offset < 100) {
  19890. std::string data(100, 'X');
  19891. sink.write(data.c_str(), data.size());
  19892. return true;
  19893. }
  19894. while (!close_now) {
  19895. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19896. }
  19897. return false;
  19898. });
  19899. });
  19900. auto port = 8094;
  19901. std::thread t([&]() { svr.listen("localhost", port); });
  19902. svr.wait_until_ready();
  19903. SSLClient cli("localhost", port);
  19904. cli.enable_server_certificate_verification(false);
  19905. auto handle = cli.open_stream("GET", "/will-close");
  19906. ASSERT_TRUE(handle.is_valid());
  19907. char buf[256];
  19908. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19909. EXPECT_GT(n, 0);
  19910. // Signal server to close
  19911. close_now = true;
  19912. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19913. // Keep reading
  19914. }
  19915. if (n < 0) {
  19916. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19917. handle.get_read_error() == Error::Read)
  19918. << "Actual error: " << to_string(handle.get_read_error());
  19919. }
  19920. svr.stop();
  19921. t.join();
  19922. }
  19923. #endif
  19924. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19925. using namespace httplib;
  19926. // Create a test file
  19927. const char *fname = "etag_testfile.txt";
  19928. const char *content = "etag-content";
  19929. {
  19930. std::ofstream ofs(fname);
  19931. ofs << content;
  19932. ASSERT_TRUE(ofs.good());
  19933. }
  19934. Server svr;
  19935. svr.set_mount_point("/static", ".");
  19936. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19937. svr.wait_until_ready();
  19938. Client cli(HOST, PORT);
  19939. // First request: should get 200 with ETag header
  19940. auto res1 = cli.Get("/static/etag_testfile.txt");
  19941. ASSERT_TRUE(res1);
  19942. ASSERT_EQ(200, res1->status);
  19943. ASSERT_TRUE(res1->has_header("ETag"));
  19944. std::string etag = res1->get_header_value("ETag");
  19945. EXPECT_FALSE(etag.empty());
  19946. // Verify ETag format: W/"hex-hex"
  19947. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19948. EXPECT_EQ('W', etag[0]);
  19949. EXPECT_EQ('/', etag[1]);
  19950. EXPECT_EQ('"', etag[2]);
  19951. EXPECT_EQ('"', etag.back());
  19952. // Exact match: expect 304 Not Modified
  19953. Headers h2 = {{"If-None-Match", etag}};
  19954. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19955. ASSERT_TRUE(res2);
  19956. EXPECT_EQ(304, res2->status);
  19957. // Wildcard match: expect 304 Not Modified
  19958. Headers h3 = {{"If-None-Match", "*"}};
  19959. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19960. ASSERT_TRUE(res3);
  19961. EXPECT_EQ(304, res3->status);
  19962. // Non-matching ETag: expect 200
  19963. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19964. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19965. ASSERT_TRUE(res4);
  19966. EXPECT_EQ(200, res4->status);
  19967. // Multiple ETags with one matching: expect 304
  19968. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19969. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19970. ASSERT_TRUE(res5);
  19971. EXPECT_EQ(304, res5->status);
  19972. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19973. // that equivalent to the single comma-separated list above, so the match on
  19974. // the second line must still be found.
  19975. Headers h6;
  19976. h6.emplace("If-None-Match", "W/\"other\"");
  19977. h6.emplace("If-None-Match", etag);
  19978. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19979. ASSERT_TRUE(res6);
  19980. EXPECT_EQ(304, res6->status);
  19981. svr.stop();
  19982. t.join();
  19983. std::remove(fname);
  19984. }
  19985. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19986. using namespace httplib;
  19987. Server svr;
  19988. svr.set_mount_point("/static", ".");
  19989. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19990. svr.wait_until_ready();
  19991. Client cli(HOST, PORT);
  19992. // Send If-None-Match: * to a non-existent file
  19993. Headers h = {{"If-None-Match", "*"}};
  19994. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19996. EXPECT_EQ(404, res->status);
  19997. svr.stop();
  19998. t.join();
  19999. }
  20000. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20001. using namespace httplib;
  20002. // Create a test file
  20003. const char *fname = "etag_boundary_testfile.txt";
  20004. const char *content = "boundary-test";
  20005. {
  20006. std::ofstream ofs(fname);
  20007. ofs << content;
  20008. ASSERT_TRUE(ofs.good());
  20009. }
  20010. Server svr;
  20011. svr.set_mount_point("/static", ".");
  20012. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20013. svr.wait_until_ready();
  20014. Client cli(HOST, PORT);
  20015. // Get the actual ETag
  20016. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20017. ASSERT_TRUE(res1);
  20018. ASSERT_EQ(200, res1->status);
  20019. ASSERT_TRUE(res1->has_header("ETag"));
  20020. std::string etag = res1->get_header_value("ETag");
  20021. // Test 1: Very long ETag value (longer than actual ETag)
  20022. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20023. Headers h1 = {{"If-None-Match", "W/"
  20024. "\"very-long-etag-value-that-is-much-longer-"
  20025. "than-the-actual-etag-value\""}};
  20026. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20027. ASSERT_TRUE(res2);
  20028. EXPECT_EQ(200, res2->status); // Should not match
  20029. // Test 2: Long string followed by wildcard
  20030. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20031. // string)
  20032. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20033. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20034. ASSERT_TRUE(res3);
  20035. EXPECT_EQ(304, res3->status); // Should match on "*"
  20036. // Test 3: Wildcard followed by long string
  20037. // Should match on "*" immediately and return 304
  20038. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20039. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20040. ASSERT_TRUE(res4);
  20041. EXPECT_EQ(304, res4->status); // Should match on "*"
  20042. // Test 4: Multiple long non-matching values
  20043. // Should NOT match and return 200 (test that all comparisons are safe)
  20044. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20045. "W/\"second-long-non-matching-value\", "
  20046. "W/\"third-long-non-matching-value\""}};
  20047. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20048. ASSERT_TRUE(res5);
  20049. EXPECT_EQ(200, res5->status); // Should not match
  20050. // Test 5: Single character that is not "*" (edge case)
  20051. Headers h5 = {{"If-None-Match", "X"}};
  20052. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20053. ASSERT_TRUE(res6);
  20054. EXPECT_EQ(200, res6->status); // Should not match
  20055. svr.stop();
  20056. t.join();
  20057. std::remove(fname);
  20058. }
  20059. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20060. using namespace httplib;
  20061. // Create a test file
  20062. const char *fname = "ims_testfile.txt";
  20063. const char *content = "if-modified-since-test";
  20064. {
  20065. std::ofstream ofs(fname);
  20066. ofs << content;
  20067. ASSERT_TRUE(ofs.good());
  20068. }
  20069. Server svr;
  20070. svr.set_mount_point("/static", ".");
  20071. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20072. svr.wait_until_ready();
  20073. Client cli(HOST, PORT);
  20074. // First request: should get 200 with Last-Modified header
  20075. auto res1 = cli.Get("/static/ims_testfile.txt");
  20076. ASSERT_TRUE(res1);
  20077. ASSERT_EQ(200, res1->status);
  20078. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20079. std::string last_modified = res1->get_header_value("Last-Modified");
  20080. EXPECT_FALSE(last_modified.empty());
  20081. // If-Modified-Since with same time: expect 304
  20082. Headers h2 = {{"If-Modified-Since", last_modified}};
  20083. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20084. ASSERT_TRUE(res2);
  20085. EXPECT_EQ(304, res2->status);
  20086. // If-Modified-Since with future time: expect 304
  20087. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20088. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20089. ASSERT_TRUE(res3);
  20090. EXPECT_EQ(304, res3->status);
  20091. // If-Modified-Since with past time: expect 200
  20092. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20093. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20094. ASSERT_TRUE(res4);
  20095. EXPECT_EQ(200, res4->status);
  20096. // If-None-Match takes precedence over If-Modified-Since
  20097. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20098. ASSERT_TRUE(res1->has_header("ETag"));
  20099. std::string etag = res1->get_header_value("ETag");
  20100. Headers h5 = {{"If-None-Match", etag},
  20101. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20102. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20103. ASSERT_TRUE(res5);
  20104. EXPECT_EQ(304, res5->status);
  20105. svr.stop();
  20106. t.join();
  20107. std::remove(fname);
  20108. }
  20109. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20110. using namespace httplib;
  20111. Server svr;
  20112. // Endpoint that returns compressible content
  20113. svr.Get("/compressible", [](const Request &, Response &res) {
  20114. // Return a large enough body to trigger compression
  20115. std::string body(1000, 'a');
  20116. res.set_content(body, "text/plain");
  20117. });
  20118. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20119. svr.wait_until_ready();
  20120. Client cli(HOST, PORT);
  20121. // Request with gzip support: should get Vary header when compressed
  20122. cli.set_compress(true);
  20123. auto res1 = cli.Get("/compressible");
  20124. ASSERT_TRUE(res1);
  20125. EXPECT_EQ(200, res1->status);
  20126. // If Content-Encoding is set, Vary should also be set
  20127. if (res1->has_header("Content-Encoding")) {
  20128. EXPECT_TRUE(res1->has_header("Vary"));
  20129. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20130. }
  20131. // Request without Accept-Encoding header: should not have compression
  20132. Headers h_no_compress;
  20133. auto res2 = cli.Get("/compressible", h_no_compress);
  20134. ASSERT_TRUE(res2);
  20135. EXPECT_EQ(200, res2->status);
  20136. // Verify Vary header is present when compression is applied
  20137. // (the exact behavior depends on server configuration)
  20138. svr.stop();
  20139. t.join();
  20140. }
  20141. TEST(ETagTest, IfRangeWithETag) {
  20142. using namespace httplib;
  20143. // Create a test file with known content
  20144. const char *fname = "if_range_testfile.txt";
  20145. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20146. {
  20147. std::ofstream ofs(fname);
  20148. ofs << content;
  20149. ASSERT_TRUE(ofs.good());
  20150. }
  20151. Server svr;
  20152. svr.set_mount_point("/static", ".");
  20153. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20154. svr.wait_until_ready();
  20155. Client cli(HOST, PORT);
  20156. // First request: get ETag
  20157. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20158. ASSERT_TRUE(res1);
  20159. ASSERT_EQ(200, res1->status);
  20160. ASSERT_TRUE(res1->has_header("ETag"));
  20161. std::string etag = res1->get_header_value("ETag");
  20162. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20163. // Since our server generates weak ETags (W/"..."), If-Range with our
  20164. // ETag should NOT result in partial content - it should return full content.
  20165. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20166. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20167. ASSERT_TRUE(res2);
  20168. // Weak ETag in If-Range -> full content (200), not partial (206)
  20169. EXPECT_EQ(200, res2->status);
  20170. EXPECT_EQ(content, res2->body);
  20171. EXPECT_FALSE(res2->has_header("Content-Range"));
  20172. // Range request with non-matching If-Range (ETag): should get 200 (full
  20173. // content)
  20174. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20175. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20176. ASSERT_TRUE(res3);
  20177. EXPECT_EQ(200, res3->status);
  20178. EXPECT_EQ(content, res3->body);
  20179. EXPECT_FALSE(res3->has_header("Content-Range"));
  20180. // Range request with strong ETag (hypothetical - our server doesn't generate
  20181. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20182. // should return full content)
  20183. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20184. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20185. ASSERT_TRUE(res4);
  20186. EXPECT_EQ(200, res4->status);
  20187. EXPECT_EQ(content, res4->body);
  20188. EXPECT_FALSE(res4->has_header("Content-Range"));
  20189. svr.stop();
  20190. t.join();
  20191. std::remove(fname);
  20192. }
  20193. TEST(ETagTest, IfRangeWithDate) {
  20194. using namespace httplib;
  20195. // Create a test file
  20196. const char *fname = "if_range_date_testfile.txt";
  20197. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20198. {
  20199. std::ofstream ofs(fname);
  20200. ofs << content;
  20201. ASSERT_TRUE(ofs.good());
  20202. }
  20203. Server svr;
  20204. svr.set_mount_point("/static", ".");
  20205. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20206. svr.wait_until_ready();
  20207. Client cli(HOST, PORT);
  20208. // First request: get Last-Modified
  20209. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20210. ASSERT_TRUE(res1);
  20211. ASSERT_EQ(200, res1->status);
  20212. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20213. std::string last_modified = res1->get_header_value("Last-Modified");
  20214. // Range request with matching If-Range (date): should get 206
  20215. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20216. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20217. ASSERT_TRUE(res2);
  20218. EXPECT_EQ(206, res2->status);
  20219. EXPECT_EQ("FGHIJ", res2->body);
  20220. // Range request with old If-Range date: should get 200 (full content)
  20221. Headers h3 = {{"Range", "bytes=5-9"},
  20222. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20223. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20224. ASSERT_TRUE(res3);
  20225. EXPECT_EQ(200, res3->status);
  20226. EXPECT_EQ(content, res3->body);
  20227. // Range request with future If-Range date: should get 206
  20228. Headers h4 = {{"Range", "bytes=0-4"},
  20229. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20230. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20231. ASSERT_TRUE(res4);
  20232. EXPECT_EQ(206, res4->status);
  20233. EXPECT_EQ("ABCDE", res4->body);
  20234. svr.stop();
  20235. t.join();
  20236. std::remove(fname);
  20237. }
  20238. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20239. using namespace httplib;
  20240. const char *fname = "etag_malformed.txt";
  20241. const char *content = "malformed-etag";
  20242. {
  20243. std::ofstream ofs(fname);
  20244. ofs << content;
  20245. ASSERT_TRUE(ofs.good());
  20246. }
  20247. Server svr;
  20248. svr.set_mount_point("/static", ".");
  20249. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20250. svr.wait_until_ready();
  20251. Client cli(HOST, PORT);
  20252. // baseline: should get 200 and an ETag
  20253. auto res1 = cli.Get("/static/etag_malformed.txt");
  20254. ASSERT_TRUE(res1);
  20255. ASSERT_EQ(200, res1->status);
  20256. ASSERT_TRUE(res1->has_header("ETag"));
  20257. // Malformed ETag value (missing quotes) should be treated as non-matching
  20258. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20259. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20260. ASSERT_TRUE(res_bad);
  20261. EXPECT_EQ(200, res_bad->status);
  20262. // Whitespace-only header value should be considered invalid / non-matching
  20263. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20264. "Host: localhost\r\n"
  20265. "If-None-Match: \r\n"
  20266. "Connection: close\r\n"
  20267. "\r\n";
  20268. std::string out;
  20269. ASSERT_TRUE(send_request(5, raw_req, &out));
  20270. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20271. svr.stop();
  20272. t.join();
  20273. std::remove(fname);
  20274. }
  20275. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20276. using namespace httplib;
  20277. const char *fname = "ims_invalid_format.txt";
  20278. const char *content = "ims-bad-format";
  20279. {
  20280. std::ofstream ofs(fname);
  20281. ofs << content;
  20282. ASSERT_TRUE(ofs.good());
  20283. }
  20284. Server svr;
  20285. svr.set_mount_point("/static", ".");
  20286. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20287. svr.wait_until_ready();
  20288. Client cli(HOST, PORT);
  20289. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20290. ASSERT_TRUE(res1);
  20291. ASSERT_EQ(200, res1->status);
  20292. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20293. // If-Modified-Since with invalid format should not result in 304
  20294. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20295. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20296. ASSERT_TRUE(res_bad);
  20297. EXPECT_EQ(200, res_bad->status);
  20298. // If-Range with invalid date format should be treated as mismatch -> full
  20299. // content (200)
  20300. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20301. {"If-Range", "invalid-date"}};
  20302. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20303. ASSERT_TRUE(res_ifrange);
  20304. EXPECT_EQ(200, res_ifrange->status);
  20305. svr.stop();
  20306. t.join();
  20307. std::remove(fname);
  20308. }
  20309. TEST(ETagTest, IfRangeWithMalformedETag) {
  20310. using namespace httplib;
  20311. const char *fname = "ifrange_malformed.txt";
  20312. const std::string content = "0123456789";
  20313. {
  20314. std::ofstream ofs(fname);
  20315. ofs << content;
  20316. ASSERT_TRUE(ofs.good());
  20317. }
  20318. Server svr;
  20319. svr.set_mount_point("/static", ".");
  20320. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20321. svr.wait_until_ready();
  20322. Client cli(HOST, PORT);
  20323. // First request: get ETag
  20324. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20325. ASSERT_TRUE(res1);
  20326. ASSERT_EQ(200, res1->status);
  20327. ASSERT_TRUE(res1->has_header("ETag"));
  20328. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20329. // full content (200)
  20330. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20331. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20332. ASSERT_TRUE(res2);
  20333. EXPECT_EQ(200, res2->status);
  20334. EXPECT_EQ(content, res2->body);
  20335. svr.stop();
  20336. t.join();
  20337. std::remove(fname);
  20338. }
  20339. TEST(ETagTest, ExtremeLargeDateValues) {
  20340. using namespace httplib;
  20341. const char *fname = "ims_extreme_date.txt";
  20342. const char *content = "ims-extreme-date";
  20343. {
  20344. std::ofstream ofs(fname);
  20345. ofs << content;
  20346. ASSERT_TRUE(ofs.good());
  20347. }
  20348. Server svr;
  20349. svr.set_mount_point("/static", ".");
  20350. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20351. svr.wait_until_ready();
  20352. Client cli(HOST, PORT);
  20353. auto res1 = cli.Get(std::string("/static/") + fname);
  20354. ASSERT_TRUE(res1);
  20355. ASSERT_EQ(200, res1->status);
  20356. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20357. // Extremely large year that may overflow date parsing routines.
  20358. Headers h_large_date = {
  20359. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20360. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20361. ASSERT_TRUE(res_bad);
  20362. // Expect server to treat this as invalid/mismatch and return full content
  20363. EXPECT_EQ(200, res_bad->status);
  20364. // If-Range with extremely large date should be treated as mismatch -> full
  20365. // content (200)
  20366. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20367. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20368. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20369. ASSERT_TRUE(res_ifrange);
  20370. EXPECT_EQ(200, res_ifrange->status);
  20371. svr.stop();
  20372. t.join();
  20373. std::remove(fname);
  20374. }
  20375. TEST(ETagTest, NegativeFileModificationTime) {
  20376. using namespace httplib;
  20377. const char *fname = "ims_negative_mtime.txt";
  20378. const std::string content = "negative-mtime";
  20379. {
  20380. std::ofstream ofs(fname);
  20381. ofs << content;
  20382. ASSERT_TRUE(ofs.good());
  20383. }
  20384. // Try to set file mtime to a negative value. This may fail on some
  20385. // platforms/filesystems; if it fails, the test will still verify server
  20386. // behaves safely by performing a regular conditional request.
  20387. #if defined(__APPLE__) || defined(__linux__)
  20388. bool set_negative = false;
  20389. do {
  20390. struct timeval times[2];
  20391. // access time: now
  20392. times[0].tv_sec = time(nullptr);
  20393. times[0].tv_usec = 0;
  20394. // modification time: negative (e.g., -1)
  20395. times[1].tv_sec = -1;
  20396. times[1].tv_usec = 0;
  20397. if (utimes(fname, times) == 0) { set_negative = true; }
  20398. } while (0);
  20399. #else
  20400. bool set_negative = false;
  20401. #endif
  20402. Server svr;
  20403. svr.set_mount_point("/static", ".");
  20404. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20405. svr.wait_until_ready();
  20406. Client cli(HOST, PORT);
  20407. auto res1 = cli.Get(std::string("/static/") + fname);
  20408. ASSERT_TRUE(res1);
  20409. ASSERT_EQ(200, res1->status);
  20410. bool has_last_modified = res1->has_header("Last-Modified");
  20411. std::string last_modified;
  20412. if (has_last_modified) {
  20413. last_modified = res1->get_header_value("Last-Modified");
  20414. }
  20415. if (set_negative) {
  20416. // If we successfully set a negative mtime, ensure server returns a
  20417. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20418. // with an old date and ensure server handles it without crash.
  20419. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20420. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20421. ASSERT_TRUE(res2);
  20422. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20423. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20424. } else {
  20425. // Could not set negative mtime on this platform; fall back to verifying
  20426. // that normal invalid/malformed dates are treated safely (non-304).
  20427. Headers h_bad_date = {
  20428. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20429. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20430. ASSERT_TRUE(res_bad);
  20431. EXPECT_EQ(200, res_bad->status);
  20432. }
  20433. svr.stop();
  20434. t.join();
  20435. std::remove(fname);
  20436. }
  20437. //==============================================================================
  20438. // Integration Tests with Server
  20439. //==============================================================================
  20440. class SSEIntegrationTest : public ::testing::Test {
  20441. protected:
  20442. void SetUp() override {
  20443. stop_server_.store(false);
  20444. events_.clear();
  20445. server_ = httplib::detail::make_unique<Server>();
  20446. setup_server();
  20447. start_server();
  20448. }
  20449. void TearDown() override {
  20450. stop_server_.store(true);
  20451. event_cv_.notify_all();
  20452. server_->stop();
  20453. if (server_thread_.joinable()) { server_thread_.join(); }
  20454. }
  20455. void setup_server() {
  20456. // Simple SSE endpoint
  20457. server_->Get("/events", [this](const Request &req, Response &res) {
  20458. auto last_id = req.get_header_value("Last-Event-ID");
  20459. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20460. res.set_chunked_content_provider(
  20461. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20462. std::unique_lock<std::mutex> lock(event_mutex_);
  20463. if (event_cv_.wait_for(
  20464. lock, std::chrono::milliseconds(200), [this] {
  20465. return !events_.empty() || stop_server_.load();
  20466. })) {
  20467. if (stop_server_.load()) { return false; }
  20468. if (!events_.empty()) {
  20469. std::string event = events_.front();
  20470. events_.erase(events_.begin());
  20471. sink.write(event.data(), event.size());
  20472. return true;
  20473. }
  20474. }
  20475. return !stop_server_.load();
  20476. });
  20477. });
  20478. // Endpoint that returns error
  20479. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20480. res.status = 500;
  20481. res.set_content("Internal Server Error", "text/plain");
  20482. });
  20483. // Endpoint for custom event types
  20484. server_->Get("/custom-events", [](const Request &, Response &res) {
  20485. res.set_chunked_content_provider(
  20486. "text/event-stream", [](size_t offset, DataSink &sink) {
  20487. if (offset == 0) {
  20488. std::string event = "event: update\ndata: updated\n\n"
  20489. "event: delete\ndata: deleted\n\n";
  20490. sink.write(event.data(), event.size());
  20491. }
  20492. return false; // End stream after sending
  20493. });
  20494. });
  20495. }
  20496. void start_server() {
  20497. port_ = server_->bind_to_any_port(HOST);
  20498. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20499. // Wait for server to start
  20500. while (!server_->is_running()) {
  20501. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20502. }
  20503. }
  20504. int get_port() const { return port_; }
  20505. void send_event(const std::string &event) {
  20506. std::lock_guard<std::mutex> lock(event_mutex_);
  20507. events_.push_back(event);
  20508. event_cv_.notify_all();
  20509. }
  20510. std::unique_ptr<Server> server_;
  20511. std::thread server_thread_;
  20512. std::mutex event_mutex_;
  20513. std::condition_variable event_cv_;
  20514. std::vector<std::string> events_;
  20515. std::atomic<bool> stop_server_{false};
  20516. std::string last_received_event_id_;
  20517. int port_ = 0;
  20518. };
  20519. //==============================================================================
  20520. // SSE Parsing Tests
  20521. //==============================================================================
  20522. class SSEParsingTest : public SSEIntegrationTest {
  20523. protected:
  20524. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20525. // A trailing sentinel event tells when the whole stream has been parsed.
  20526. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20527. auto body = stream + "event: end\ndata: end\n\n";
  20528. server_->Get("/parse", [body](const Request &, Response &res) {
  20529. res.set_content(body, "text/event-stream");
  20530. });
  20531. return collect("/parse");
  20532. }
  20533. // Runs SSEClient against path until an "end" event arrives and returns the
  20534. // messages dispatched before it
  20535. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20536. Client client(HOST, get_port());
  20537. sse::SSEClient sse(client, path);
  20538. std::mutex mutex;
  20539. std::condition_variable cv;
  20540. std::vector<sse::SSEMessage> messages;
  20541. auto done = false;
  20542. sse.on_message([&](const sse::SSEMessage &msg) {
  20543. std::lock_guard<std::mutex> lock(mutex);
  20544. // Ignore a replay from a reconnect that races with stop()
  20545. if (!done) { messages.push_back(msg); }
  20546. });
  20547. sse.on_event("end", [&](const sse::SSEMessage &) {
  20548. std::lock_guard<std::mutex> lock(mutex);
  20549. done = true;
  20550. cv.notify_all();
  20551. });
  20552. sse.set_reconnect_interval(100);
  20553. sse.start_async();
  20554. {
  20555. std::unique_lock<std::mutex> lock(mutex);
  20556. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20557. }
  20558. sse.stop();
  20559. EXPECT_TRUE(done);
  20560. return messages;
  20561. }
  20562. };
  20563. TEST_F(SSEParsingTest, SingleLineData) {
  20564. auto msgs = parse("data: hello\n\n");
  20565. ASSERT_EQ(msgs.size(), 1u);
  20566. EXPECT_EQ(msgs[0].data, "hello");
  20567. EXPECT_EQ(msgs[0].event, "message");
  20568. }
  20569. TEST_F(SSEParsingTest, MultiLineData) {
  20570. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20571. ASSERT_EQ(msgs.size(), 1u);
  20572. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20573. }
  20574. TEST_F(SSEParsingTest, CustomEventType) {
  20575. auto msgs = parse("event: update\ndata: payload\n\n");
  20576. ASSERT_EQ(msgs.size(), 1u);
  20577. EXPECT_EQ(msgs[0].event, "update");
  20578. EXPECT_EQ(msgs[0].data, "payload");
  20579. }
  20580. TEST_F(SSEParsingTest, EventIdHandling) {
  20581. auto msgs = parse("id: 12345\ndata: test\n\n");
  20582. ASSERT_EQ(msgs.size(), 1u);
  20583. EXPECT_EQ(msgs[0].id, "12345");
  20584. }
  20585. TEST_F(SSEParsingTest, EmptyEventId) {
  20586. auto msgs = parse("id:\ndata: test\n\n");
  20587. ASSERT_EQ(msgs.size(), 1u);
  20588. EXPECT_EQ(msgs[0].id, "");
  20589. }
  20590. TEST_F(SSEParsingTest, CommentsIgnored) {
  20591. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20592. ASSERT_EQ(msgs.size(), 1u);
  20593. EXPECT_EQ(msgs[0].data, "hello");
  20594. EXPECT_EQ(msgs[0].event, "message");
  20595. }
  20596. TEST_F(SSEParsingTest, ColonInValue) {
  20597. auto msgs = parse("data: hello:world:test\n\n");
  20598. ASSERT_EQ(msgs.size(), 1u);
  20599. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20600. }
  20601. TEST_F(SSEParsingTest, FieldNameOnly) {
  20602. // A line without a colon is a field name with an empty value
  20603. auto msgs = parse("data\n\n");
  20604. ASSERT_EQ(msgs.size(), 1u);
  20605. EXPECT_EQ(msgs[0].data, "");
  20606. }
  20607. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20608. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20609. ASSERT_EQ(msgs.size(), 1u);
  20610. EXPECT_EQ(msgs[0].event, "update");
  20611. EXPECT_EQ(msgs[0].data, "hello");
  20612. }
  20613. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20614. auto msgs = parse("data\r\n\r\n");
  20615. ASSERT_EQ(msgs.size(), 1u);
  20616. EXPECT_EQ(msgs[0].data, "");
  20617. }
  20618. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20619. auto msgs = parse("event: update\rdata: hello\r\r");
  20620. ASSERT_EQ(msgs.size(), 1u);
  20621. EXPECT_EQ(msgs[0].event, "update");
  20622. EXPECT_EQ(msgs[0].data, "hello");
  20623. }
  20624. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20625. // Chunk boundaries fall inside every \r\n and right before the first one
  20626. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20627. "\n\r", "\nevent: end\ndata: end\n\n"};
  20628. server_->Get("/split", [chunks](const Request &, Response &res) {
  20629. auto i = std::make_shared<size_t>(0);
  20630. res.set_chunked_content_provider(
  20631. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20632. if (*i == chunks.size()) {
  20633. sink.done();
  20634. } else {
  20635. sink.write(chunks[*i].data(), chunks[*i].size());
  20636. (*i)++;
  20637. }
  20638. return true;
  20639. });
  20640. });
  20641. auto msgs = collect("/split");
  20642. ASSERT_EQ(msgs.size(), 1u);
  20643. EXPECT_EQ(msgs[0].event, "update");
  20644. EXPECT_EQ(msgs[0].data, "hello");
  20645. }
  20646. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20647. // Only a BOM at the start of the stream is ignored
  20648. auto msgs = parse("\xEF\xBB\xBF"
  20649. "data: first\n\n"
  20650. "\xEF\xBB\xBF"
  20651. "data: second\n\n");
  20652. ASSERT_EQ(msgs.size(), 1u);
  20653. EXPECT_EQ(msgs[0].data, "first");
  20654. }
  20655. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20656. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20657. ASSERT_EQ(msgs.size(), 1u);
  20658. EXPECT_EQ(msgs[0].data, "hello");
  20659. EXPECT_EQ(msgs[0].event, "message");
  20660. }
  20661. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20662. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20663. ASSERT_EQ(msgs.size(), 2u);
  20664. EXPECT_EQ(msgs[0].data, "hello");
  20665. EXPECT_EQ(msgs[1].data, "hello");
  20666. }
  20667. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20668. // An event without data is not dispatched, and its type must not leak
  20669. // into the next event
  20670. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20671. ASSERT_EQ(msgs.size(), 1u);
  20672. EXPECT_EQ(msgs[0].event, "message");
  20673. EXPECT_EQ(msgs[0].data, "hello");
  20674. }
  20675. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20676. // The first connection sends only an id; the second echoes back the
  20677. // Last-Event-ID it was reconnected with
  20678. std::atomic<int> connection_count{0};
  20679. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20680. if (connection_count++ == 0) {
  20681. res.set_content("id: 42\n\n", "text/event-stream");
  20682. } else {
  20683. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20684. "\n\nevent: end\ndata: end\n\n",
  20685. "text/event-stream");
  20686. }
  20687. });
  20688. auto msgs = collect("/id-only");
  20689. ASSERT_EQ(msgs.size(), 1u);
  20690. EXPECT_EQ(msgs[0].data, "42");
  20691. }
  20692. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20693. // The first connection sets an id and then clears it with an empty one; the
  20694. // second reports whether it was reconnected with a Last-Event-ID
  20695. std::atomic<int> connection_count{0};
  20696. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20697. if (connection_count++ == 0) {
  20698. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20699. "text/event-stream");
  20700. } else {
  20701. res.set_content(
  20702. std::string("data: ") +
  20703. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20704. "\n\nevent: end\ndata: end\n\n",
  20705. "text/event-stream");
  20706. }
  20707. });
  20708. auto msgs = collect("/id-clear");
  20709. ASSERT_EQ(msgs.size(), 3u);
  20710. EXPECT_EQ(msgs[0].id, "1");
  20711. EXPECT_EQ(msgs[1].id, "");
  20712. EXPECT_EQ(msgs[2].data, "not sent");
  20713. }
  20714. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20715. // The first connection sets an id and then sends ids that cannot be carried
  20716. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20717. // with
  20718. std::atomic<int> connection_count{0};
  20719. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20720. if (connection_count++ == 0) {
  20721. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20722. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20723. "text/event-stream");
  20724. } else {
  20725. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20726. "\n\nevent: end\ndata: end\n\n",
  20727. "text/event-stream");
  20728. }
  20729. });
  20730. auto msgs = collect("/id-unsendable");
  20731. ASSERT_EQ(msgs.size(), 1u);
  20732. EXPECT_EQ(msgs[0].data, "42");
  20733. }
  20734. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20735. auto msgs = parse("event: notification\nid: evt-42\n"
  20736. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20737. ASSERT_EQ(msgs.size(), 1u);
  20738. EXPECT_EQ(msgs[0].event, "notification");
  20739. EXPECT_EQ(msgs[0].id, "evt-42");
  20740. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20741. }
  20742. TEST(SSEMessageTest, Clear) {
  20743. sse::SSEMessage msg;
  20744. msg.event = "custom";
  20745. msg.data = "some data";
  20746. msg.id = "123";
  20747. msg.clear();
  20748. EXPECT_EQ(msg.event, "message");
  20749. EXPECT_EQ(msg.data, "");
  20750. EXPECT_EQ(msg.id, "");
  20751. }
  20752. //==============================================================================
  20753. // SSE Integration Tests
  20754. //==============================================================================
  20755. // Test: Successful connection and on_open callback
  20756. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20757. // Add a simple endpoint that sends one event and closes
  20758. server_->Get("/simple-event", [](const Request &, Response &res) {
  20759. res.set_chunked_content_provider(
  20760. "text/event-stream", [](size_t offset, DataSink &sink) {
  20761. if (offset == 0) {
  20762. std::string event = "data: hello\n\n";
  20763. sink.write(event.data(), event.size());
  20764. }
  20765. return false; // Close stream after sending
  20766. });
  20767. });
  20768. Client client("localhost", get_port());
  20769. sse::SSEClient sse(client, "/simple-event");
  20770. std::atomic<bool> open_called{false};
  20771. std::atomic<bool> message_received{false};
  20772. sse.on_open([&open_called]() { open_called.store(true); });
  20773. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20774. if (msg.data == "hello") { message_received.store(true); }
  20775. });
  20776. sse.set_reconnect_interval(100);
  20777. sse.set_max_reconnect_attempts(1);
  20778. // Start async
  20779. sse.start_async();
  20780. // Wait for message to be processed
  20781. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20782. sse.stop();
  20783. EXPECT_TRUE(open_called.load());
  20784. EXPECT_TRUE(message_received.load());
  20785. }
  20786. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20787. // A data line that never ends.
  20788. server_->Get("/endless-line", [](const Request &, Response &res) {
  20789. res.set_chunked_content_provider(
  20790. "text/event-stream", [](size_t offset, DataSink &sink) {
  20791. if (offset == 0) { sink.write("data: ", 6); }
  20792. std::string chunk(64 * 1024, 'A');
  20793. return sink.write(chunk.data(), chunk.size());
  20794. });
  20795. });
  20796. Client client("localhost", get_port());
  20797. sse::SSEClient sse(client, "/endless-line");
  20798. std::atomic<bool> too_long{false};
  20799. sse.on_error([&](Error err) {
  20800. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20801. });
  20802. sse.set_max_reconnect_attempts(1);
  20803. sse.start_async();
  20804. for (int i = 0; i < 500 && !too_long; i++) {
  20805. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20806. }
  20807. sse.stop();
  20808. EXPECT_TRUE(too_long);
  20809. }
  20810. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  20811. // Far more in all than the client's payload limit below.
  20812. server_->Get("/many-events", [](const Request &, Response &res) {
  20813. res.set_chunked_content_provider(
  20814. "text/event-stream", [](size_t offset, DataSink &sink) {
  20815. if (offset == 0) {
  20816. std::string events;
  20817. for (int i = 0; i < 1000; i++) {
  20818. events += "data: message\n\n";
  20819. }
  20820. sink.write(events.data(), events.size());
  20821. }
  20822. return false;
  20823. });
  20824. });
  20825. Client client("localhost", get_port());
  20826. client.set_payload_max_length(1024);
  20827. sse::SSEClient sse(client, "/many-events");
  20828. std::atomic<int> messages{0};
  20829. std::atomic<bool> too_large{false};
  20830. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  20831. sse.on_error([&](Error err) {
  20832. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  20833. });
  20834. sse.set_max_reconnect_attempts(1);
  20835. sse.start_async();
  20836. for (int i = 0; i < 500 && messages < 1000; i++) {
  20837. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20838. }
  20839. sse.stop();
  20840. EXPECT_GE(messages.load(), 1000);
  20841. EXPECT_FALSE(too_large);
  20842. }
  20843. // Test: on_message callback
  20844. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20845. // Endpoint that sends multiple events then closes
  20846. server_->Get("/multi-event", [](const Request &, Response &res) {
  20847. res.set_chunked_content_provider(
  20848. "text/event-stream", [](size_t offset, DataSink &sink) {
  20849. if (offset == 0) {
  20850. std::string events = "data: message1\n\ndata: message2\n\n";
  20851. sink.write(events.data(), events.size());
  20852. }
  20853. return false;
  20854. });
  20855. });
  20856. Client client("localhost", get_port());
  20857. sse::SSEClient sse(client, "/multi-event");
  20858. std::vector<std::string> received_messages;
  20859. std::mutex messages_mutex;
  20860. sse.on_message([&](const sse::SSEMessage &msg) {
  20861. std::lock_guard<std::mutex> lock(messages_mutex);
  20862. received_messages.push_back(msg.data);
  20863. });
  20864. sse.set_reconnect_interval(100);
  20865. sse.set_max_reconnect_attempts(1);
  20866. sse.start_async();
  20867. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20868. sse.stop();
  20869. std::lock_guard<std::mutex> lock(messages_mutex);
  20870. EXPECT_GE(received_messages.size(), 2u);
  20871. if (received_messages.size() >= 2) {
  20872. EXPECT_EQ(received_messages[0], "message1");
  20873. EXPECT_EQ(received_messages[1], "message2");
  20874. }
  20875. }
  20876. // Test: on_event for specific types
  20877. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20878. Client client("localhost", get_port());
  20879. sse::SSEClient sse(client, "/custom-events");
  20880. std::atomic<bool> update_received{false};
  20881. std::atomic<bool> delete_received{false};
  20882. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20883. if (msg.data == "updated") { update_received.store(true); }
  20884. });
  20885. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20886. if (msg.data == "deleted") { delete_received.store(true); }
  20887. });
  20888. sse.set_max_reconnect_attempts(1);
  20889. sse.start_async();
  20890. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20891. sse.stop();
  20892. EXPECT_TRUE(update_received.load());
  20893. EXPECT_TRUE(delete_received.load());
  20894. }
  20895. // Test: on_error callback on connection failure
  20896. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20897. // Connect to a non-existent port
  20898. Client client("localhost", 59999);
  20899. sse::SSEClient sse(client, "/events");
  20900. std::atomic<bool> error_called{false};
  20901. Error received_error = Error::Success;
  20902. sse.on_error([&](Error err) {
  20903. error_called.store(true);
  20904. received_error = err;
  20905. });
  20906. sse.set_reconnect_interval(50);
  20907. sse.set_max_reconnect_attempts(1);
  20908. sse.start_async();
  20909. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20910. sse.stop();
  20911. EXPECT_TRUE(error_called.load());
  20912. EXPECT_NE(received_error, Error::Success);
  20913. }
  20914. // Test: Last-Event-ID header sent on reconnect
  20915. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20916. // Endpoint that sends event with ID
  20917. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20918. res.set_chunked_content_provider(
  20919. "text/event-stream", [](size_t offset, DataSink &sink) {
  20920. if (offset == 0) {
  20921. std::string event = "id: evt-123\ndata: test\n\n";
  20922. sink.write(event.data(), event.size());
  20923. }
  20924. return false;
  20925. });
  20926. });
  20927. Client client("localhost", get_port());
  20928. sse::SSEClient sse(client, "/event-with-id");
  20929. std::atomic<bool> id_received{false};
  20930. sse.on_message([&](const sse::SSEMessage &msg) {
  20931. if (!msg.id.empty()) { id_received.store(true); }
  20932. });
  20933. sse.set_reconnect_interval(100);
  20934. sse.set_max_reconnect_attempts(1);
  20935. sse.start_async();
  20936. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20937. sse.stop();
  20938. EXPECT_TRUE(id_received.load());
  20939. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20940. }
  20941. // Test: Manual stop
  20942. TEST_F(SSEIntegrationTest, ManualStop) {
  20943. // Endpoint that sends one event and stays open briefly
  20944. std::atomic<bool> handler_running{true};
  20945. server_->Get("/stay-open", [&handler_running](const Request &,
  20946. Response &res) {
  20947. res.set_chunked_content_provider(
  20948. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20949. if (offset == 0) {
  20950. std::string event = "data: connected\n\n";
  20951. sink.write(event.data(), event.size());
  20952. }
  20953. // Keep connection open while handler_running is true
  20954. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20955. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20956. }
  20957. return false;
  20958. });
  20959. });
  20960. Client client("localhost", get_port());
  20961. sse::SSEClient sse(client, "/stay-open");
  20962. std::atomic<bool> connected{false};
  20963. sse.on_open([&connected]() { connected.store(true); });
  20964. sse.set_reconnect_interval(100);
  20965. sse.set_max_reconnect_attempts(1);
  20966. sse.start_async();
  20967. // Wait for connection to establish
  20968. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20969. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20970. }
  20971. EXPECT_TRUE(connected.load());
  20972. EXPECT_TRUE(sse.is_connected());
  20973. // Signal handler to stop
  20974. handler_running.store(false);
  20975. // Stop SSE client
  20976. sse.stop();
  20977. EXPECT_FALSE(sse.is_connected());
  20978. }
  20979. // Test: SSEClient with custom headers
  20980. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20981. // Setup a server endpoint that checks for custom header
  20982. std::atomic<bool> header_received{false};
  20983. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20984. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20985. header_received.store(true);
  20986. }
  20987. res.set_chunked_content_provider("text/event-stream",
  20988. [](size_t, DataSink &) { return false; });
  20989. });
  20990. Client client("localhost", get_port());
  20991. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20992. sse::SSEClient sse(client, "/header-check", headers);
  20993. sse.set_max_reconnect_attempts(1);
  20994. sse.start_async();
  20995. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20996. sse.stop();
  20997. EXPECT_TRUE(header_received.load());
  20998. }
  20999. // Test: Reconnect interval configuration
  21000. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21001. Client client("localhost", get_port());
  21002. sse::SSEClient sse(client, "/events");
  21003. auto &result = sse.set_reconnect_interval(500);
  21004. // Builder pattern should return reference to self
  21005. EXPECT_EQ(&result, &sse);
  21006. }
  21007. // Test: Max reconnect attempts
  21008. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21009. // Connect to non-existent port to force reconnects
  21010. Client client("localhost", 59998);
  21011. sse::SSEClient sse(client, "/events");
  21012. std::atomic<int> error_count{0};
  21013. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21014. sse.set_reconnect_interval(50);
  21015. sse.set_max_reconnect_attempts(2);
  21016. auto start = std::chrono::steady_clock::now();
  21017. sse.start(); // Blocking call
  21018. auto end = std::chrono::steady_clock::now();
  21019. // Should have stopped after 2 failed attempts
  21020. EXPECT_GE(error_count.load(), 2);
  21021. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21022. auto duration =
  21023. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21024. #ifdef _WIN32
  21025. // Windows is much slower for socket connection failures
  21026. EXPECT_LT(duration.count(), 7000);
  21027. #else
  21028. EXPECT_LT(duration.count(), 1000);
  21029. #endif
  21030. }
  21031. // Test: Multi-line data in integration
  21032. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  21033. // Endpoint with multi-line data
  21034. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21035. res.set_chunked_content_provider(
  21036. "text/event-stream", [](size_t offset, DataSink &sink) {
  21037. if (offset == 0) {
  21038. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21039. sink.write(event.data(), event.size());
  21040. }
  21041. return false;
  21042. });
  21043. });
  21044. Client client("localhost", get_port());
  21045. sse::SSEClient sse(client, "/multiline-data");
  21046. std::string received_data;
  21047. std::mutex data_mutex;
  21048. sse.on_message([&](const sse::SSEMessage &msg) {
  21049. std::lock_guard<std::mutex> lock(data_mutex);
  21050. received_data = msg.data;
  21051. });
  21052. sse.set_reconnect_interval(100);
  21053. sse.set_max_reconnect_attempts(1);
  21054. sse.start_async();
  21055. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21056. sse.stop();
  21057. std::lock_guard<std::mutex> lock(data_mutex);
  21058. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21059. }
  21060. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21061. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21062. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21063. DataSink &sink) {
  21064. if (offset == 0) {
  21065. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21066. sink.write(events.data(), events.size());
  21067. }
  21068. return false;
  21069. });
  21070. });
  21071. Client client("localhost", get_port());
  21072. sse::SSEClient sse(client, "/empty-data-lines");
  21073. std::mutex mutex;
  21074. std::condition_variable cv;
  21075. std::vector<std::string> received;
  21076. sse.on_message([&](const sse::SSEMessage &msg) {
  21077. std::lock_guard<std::mutex> lock(mutex);
  21078. received.push_back(msg.data);
  21079. cv.notify_all();
  21080. });
  21081. sse.set_max_reconnect_attempts(1);
  21082. sse.start_async();
  21083. {
  21084. std::unique_lock<std::mutex> lock(mutex);
  21085. cv.wait_for(lock, std::chrono::seconds(2),
  21086. [&] { return received.size() >= 3; });
  21087. }
  21088. sse.stop();
  21089. ASSERT_GE(received.size(), 3u);
  21090. EXPECT_EQ(received[0], "");
  21091. EXPECT_EQ(received[1], "\nhello");
  21092. EXPECT_EQ(received[2], "");
  21093. }
  21094. // Test: Auto-reconnect after server disconnection
  21095. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21096. std::atomic<int> connection_count{0};
  21097. std::atomic<int> message_count{0};
  21098. // Endpoint that sends one event and closes, forcing reconnect
  21099. server_->Get("/reconnect-test",
  21100. [&connection_count](const Request &, Response &res) {
  21101. connection_count.fetch_add(1);
  21102. res.set_chunked_content_provider(
  21103. "text/event-stream", [](size_t offset, DataSink &sink) {
  21104. if (offset == 0) {
  21105. std::string event = "data: hello\n\n";
  21106. sink.write(event.data(), event.size());
  21107. }
  21108. return false; // Close connection after sending
  21109. });
  21110. });
  21111. Client client("localhost", get_port());
  21112. sse::SSEClient sse(client, "/reconnect-test");
  21113. sse.on_message([&message_count](const sse::SSEMessage &) {
  21114. message_count.fetch_add(1);
  21115. });
  21116. sse.set_reconnect_interval(100);
  21117. sse.set_max_reconnect_attempts(3);
  21118. sse.start_async();
  21119. // Wait long enough for multiple reconnects
  21120. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21121. sse.stop();
  21122. // Should have connected multiple times (initial + reconnects)
  21123. EXPECT_GE(connection_count.load(), 2);
  21124. // Should have received messages from multiple connections
  21125. EXPECT_GE(message_count.load(), 2);
  21126. }
  21127. // Test: A retry field that is not all ASCII digits is ignored
  21128. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21129. std::atomic<int> connection_count{0};
  21130. server_->Get("/bad-retry",
  21131. [&connection_count](const Request &, Response &res) {
  21132. connection_count.fetch_add(1);
  21133. res.set_chunked_content_provider(
  21134. "text/event-stream", [](size_t offset, DataSink &sink) {
  21135. if (offset == 0) {
  21136. std::string event = "retry: -1\ndata: hello\n\n";
  21137. sink.write(event.data(), event.size());
  21138. }
  21139. return false;
  21140. });
  21141. });
  21142. Client client("localhost", get_port());
  21143. sse::SSEClient sse(client, "/bad-retry");
  21144. sse.set_reconnect_interval(10000);
  21145. sse.start_async();
  21146. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21147. sse.stop();
  21148. EXPECT_EQ(connection_count.load(), 1);
  21149. }
  21150. // Test: A retry field of all ASCII digits sets the reconnection time
  21151. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21152. std::mutex mutex;
  21153. std::condition_variable cv;
  21154. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21155. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21156. {
  21157. std::lock_guard<std::mutex> lock(mutex);
  21158. connected_at.push_back(std::chrono::steady_clock::now());
  21159. cv.notify_all();
  21160. }
  21161. res.set_chunked_content_provider(
  21162. "text/event-stream", [](size_t offset, DataSink &sink) {
  21163. if (offset == 0) {
  21164. std::string event = "retry: 0\ndata: hello\n\n";
  21165. sink.write(event.data(), event.size());
  21166. }
  21167. return false;
  21168. });
  21169. });
  21170. Client client("localhost", get_port());
  21171. sse::SSEClient sse(client, "/zero-retry");
  21172. sse.set_reconnect_interval(10000);
  21173. sse.start_async();
  21174. {
  21175. std::unique_lock<std::mutex> lock(mutex);
  21176. cv.wait_for(lock, std::chrono::seconds(5),
  21177. [&] { return connected_at.size() >= 2; });
  21178. }
  21179. sse.stop();
  21180. // The server-supplied interval is applied, but never below 100ms, so
  21181. // "retry: 0" does not cause a busy reconnect loop
  21182. std::lock_guard<std::mutex> lock(mutex);
  21183. ASSERT_GE(connected_at.size(), 2u);
  21184. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21185. connected_at[1] - connected_at[0])
  21186. .count();
  21187. EXPECT_GE(interval_ms, 100);
  21188. }
  21189. // Test: Last-Event-ID sent on reconnect
  21190. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21191. std::atomic<int> connection_count{0};
  21192. std::vector<std::string> received_last_event_ids;
  21193. std::mutex id_mutex;
  21194. // Endpoint that checks Last-Event-ID header and sends event with ID
  21195. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21196. int conn = connection_count.fetch_add(1);
  21197. // Capture the Last-Event-ID header from each connection
  21198. {
  21199. std::lock_guard<std::mutex> lock(id_mutex);
  21200. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21201. }
  21202. res.set_chunked_content_provider(
  21203. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21204. if (offset == 0) {
  21205. std::string event =
  21206. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21207. sink.write(event.data(), event.size());
  21208. }
  21209. return false;
  21210. });
  21211. });
  21212. Client client("localhost", get_port());
  21213. sse::SSEClient sse(client, "/reconnect-with-id");
  21214. sse.set_reconnect_interval(100);
  21215. sse.set_max_reconnect_attempts(3);
  21216. sse.start_async();
  21217. // Wait for at least 2 connections
  21218. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21219. sse.stop();
  21220. // Verify behavior
  21221. std::lock_guard<std::mutex> lock(id_mutex);
  21222. EXPECT_GE(received_last_event_ids.size(), 2u);
  21223. // First connection should have no Last-Event-ID
  21224. if (!received_last_event_ids.empty()) {
  21225. EXPECT_EQ(received_last_event_ids[0], "");
  21226. }
  21227. // Second connection should have Last-Event-ID from first connection
  21228. if (received_last_event_ids.size() >= 2) {
  21229. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21230. }
  21231. }
  21232. // Test: set_headers updates headers used on reconnect
  21233. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21234. std::vector<std::string> received_tokens;
  21235. std::mutex token_mutex;
  21236. // Endpoint that captures Authorization header
  21237. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21238. {
  21239. std::lock_guard<std::mutex> lock(token_mutex);
  21240. received_tokens.push_back(req.get_header_value("Authorization"));
  21241. }
  21242. res.set_chunked_content_provider(
  21243. "text/event-stream", [](size_t offset, DataSink &sink) {
  21244. if (offset == 0) {
  21245. std::string event = "data: hello\n\n";
  21246. sink.write(event.data(), event.size());
  21247. }
  21248. return false; // Close connection to trigger reconnect
  21249. });
  21250. });
  21251. Client client("localhost", get_port());
  21252. Headers headers = {{"Authorization", "Bearer old-token"}};
  21253. sse::SSEClient sse(client, "/auth-check", headers);
  21254. // Update headers on each successful connection
  21255. sse.on_open(
  21256. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21257. sse.set_reconnect_interval(100);
  21258. sse.set_max_reconnect_attempts(3);
  21259. sse.start_async();
  21260. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21261. sse.stop();
  21262. std::lock_guard<std::mutex> lock(token_mutex);
  21263. ASSERT_GE(received_tokens.size(), 2u);
  21264. // First connection uses original header
  21265. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21266. // Second connection uses updated header from set_headers
  21267. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21268. }
  21269. // Test: 401 allows reconnection (so on_error can refresh headers)
  21270. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21271. std::atomic<int> connection_count{0};
  21272. // Endpoint: returns 401 on first attempt, 200 on second
  21273. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21274. int conn = connection_count.fetch_add(1);
  21275. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21276. res.status = StatusCode::Unauthorized_401;
  21277. res.set_content("Unauthorized", "text/plain");
  21278. return;
  21279. }
  21280. res.set_chunked_content_provider(
  21281. "text/event-stream", [](size_t offset, DataSink &sink) {
  21282. if (offset == 0) {
  21283. std::string event = "data: authenticated\n\n";
  21284. sink.write(event.data(), event.size());
  21285. }
  21286. return false;
  21287. });
  21288. });
  21289. Client client("localhost", get_port());
  21290. Headers headers = {{"Authorization", "Bearer expired"}};
  21291. sse::SSEClient sse(client, "/auth-retry", headers);
  21292. std::atomic<bool> message_received{false};
  21293. // Refresh token on error
  21294. sse.on_error(
  21295. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21296. sse.on_message([&](const sse::SSEMessage &msg) {
  21297. if (msg.data == "authenticated") { message_received.store(true); }
  21298. });
  21299. sse.set_reconnect_interval(100);
  21300. sse.set_max_reconnect_attempts(3);
  21301. sse.start_async();
  21302. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21303. sse.stop();
  21304. // Should have reconnected after 401 and succeeded with new token
  21305. EXPECT_GE(connection_count.load(), 2);
  21306. EXPECT_TRUE(message_received.load());
  21307. }
  21308. TEST(Issue2318Test, EmptyHostString) {
  21309. {
  21310. httplib::Client cli_empty("", PORT);
  21311. auto res = cli_empty.Get("/");
  21312. ASSERT_FALSE(res);
  21313. EXPECT_EQ(httplib::Error::Connection, res.error());
  21314. }
  21315. {
  21316. httplib::Client cli(" ", PORT);
  21317. auto res = cli.Get("/");
  21318. ASSERT_FALSE(res);
  21319. EXPECT_EQ(httplib::Error::Connection, res.error());
  21320. }
  21321. }
  21322. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21323. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21324. Server svr;
  21325. // Set a small payload limit (1KB)
  21326. svr.set_payload_max_length(1024);
  21327. svr.Post("/test", [&](const Request &req, Response &res) {
  21328. res.set_content("Body size: " + std::to_string(req.body.size()),
  21329. "text/plain");
  21330. });
  21331. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21332. auto se = detail::scope_exit([&] {
  21333. svr.stop();
  21334. listen_thread.join();
  21335. });
  21336. svr.wait_until_ready();
  21337. // Create data that compresses well but exceeds limit when decompressed
  21338. // 8KB of repeated null bytes compresses to a very small size
  21339. std::string original_data(8 * 1024, '\0');
  21340. // Compress the data using gzip
  21341. std::string compressed_data;
  21342. detail::gzip_compressor compressor;
  21343. compressor.compress(original_data.data(), original_data.size(), true,
  21344. [&](const char *data, size_t size) {
  21345. compressed_data.append(data, size);
  21346. return true;
  21347. });
  21348. // Verify compression worked (compressed should be much smaller)
  21349. ASSERT_LT(compressed_data.size(), original_data.size());
  21350. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21351. // Send compressed data with Content-Encoding: gzip
  21352. Client cli(HOST, PORT);
  21353. Headers headers = {{"Content-Encoding", "gzip"}};
  21354. auto res =
  21355. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21356. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21358. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21359. }
  21360. #endif
  21361. // ============================================================================
  21362. // OpenSSL-Specific Tests
  21363. // ============================================================================
  21364. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21365. X509 *readCertificate(const std::string &strFileName) {
  21366. std::ifstream inStream(strFileName);
  21367. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21368. std::istreambuf_iterator<char>());
  21369. if (strCertPEM.empty()) return (nullptr);
  21370. BIO *pbCert = BIO_new(BIO_s_mem());
  21371. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21372. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21373. BIO_free(pbCert);
  21374. return (pCert);
  21375. }
  21376. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21377. std::ifstream inStream(strFileName);
  21378. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21379. std::istreambuf_iterator<char>());
  21380. if (strPrivateKeyPEM.empty()) return (nullptr);
  21381. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21382. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21383. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21384. BIO_free(pbPrivKey);
  21385. return (pPrivateKey);
  21386. }
  21387. TEST(BindServerTest, UpdateCerts) {
  21388. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21389. int port = svr.bind_to_any_port("0.0.0.0");
  21390. ASSERT_TRUE(svr.is_valid());
  21391. ASSERT_TRUE(port > 0);
  21392. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21393. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21394. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21395. ASSERT_TRUE(cert != nullptr);
  21396. ASSERT_TRUE(ca_cert != nullptr);
  21397. ASSERT_TRUE(key != nullptr);
  21398. X509_STORE *cert_store = X509_STORE_new();
  21399. X509_STORE_add_cert(cert_store, ca_cert);
  21400. // svr.update_certs(cert, key, cert_store); // deprecated
  21401. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21402. CLIENT_CA_CERT_FILE);
  21403. ASSERT_TRUE(svr.is_valid());
  21404. svr.stop();
  21405. X509_STORE_free(cert_store);
  21406. X509_free(cert);
  21407. X509_free(ca_cert);
  21408. EVP_PKEY_free(key);
  21409. }
  21410. // Test that update_certs() updates client CA list correctly
  21411. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21412. // Start with file-based constructor
  21413. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21414. ASSERT_TRUE(svr.is_valid());
  21415. // Initially no client CA list should be set
  21416. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21417. ASSERT_TRUE(ssl_ctx != nullptr);
  21418. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21419. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21420. EXPECT_EQ(0, count_before);
  21421. // Now update with client CA (PEM string)
  21422. std::string cert_pem, key_pem, ca_pem;
  21423. read_file(SERVER_CERT_FILE, cert_pem);
  21424. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21425. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21426. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21427. ASSERT_TRUE(svr.is_valid());
  21428. // Now client CA list should be set
  21429. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21430. ASSERT_TRUE(ca_list_after != nullptr);
  21431. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21432. }
  21433. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21434. // Test that the file-path SSLServer constructor properly sets the client CA
  21435. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21436. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21437. ASSERT_TRUE(svr.is_valid());
  21438. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21439. ASSERT_TRUE(ssl_ctx != nullptr);
  21440. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21441. ASSERT_TRUE(ca_list != nullptr);
  21442. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21443. }
  21444. #endif
  21445. // ============================================================================
  21446. // MbedTLS-Specific Tests
  21447. // ============================================================================
  21448. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21449. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21450. using namespace httplib::tls;
  21451. // Track if callback was invoked
  21452. bool callback_invoked = false;
  21453. // The callback receives void* ctx which is actually MbedTlsContext*
  21454. // We can access the mbedtls_ssl_config via the context
  21455. auto setup_callback = [&callback_invoked](void *ctx) {
  21456. callback_invoked = true;
  21457. // Cast to MbedTlsContext* to access the ssl config
  21458. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21459. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21460. // Use static variables to hold certificate data (simplified for test)
  21461. static mbedtls_x509_crt own_cert;
  21462. static mbedtls_pk_context own_key;
  21463. static mbedtls_x509_crt ca_chain;
  21464. static bool initialized = false;
  21465. if (!initialized) {
  21466. mbedtls_x509_crt_init(&own_cert);
  21467. mbedtls_pk_init(&own_key);
  21468. mbedtls_x509_crt_init(&ca_chain);
  21469. // Load server certificate
  21470. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21471. return false;
  21472. }
  21473. // Load server private key.
  21474. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21475. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21476. #if MBEDTLS_VERSION_MAJOR == 3
  21477. ,
  21478. mbedtls_ctr_drbg_random, nullptr
  21479. #endif
  21480. ) != 0) {
  21481. return false;
  21482. }
  21483. // Load CA chain for client verification
  21484. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21485. return false;
  21486. }
  21487. initialized = true;
  21488. }
  21489. // Configure the SSL config
  21490. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21491. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21492. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21493. // Set minimum TLS version using mbedTLS native API
  21494. #if MBEDTLS_VERSION_MAJOR >= 3
  21495. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21496. #else
  21497. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21498. MBEDTLS_SSL_MINOR_VERSION_3);
  21499. #endif
  21500. return true;
  21501. };
  21502. SSLServer svr(setup_callback);
  21503. ASSERT_TRUE(svr.is_valid());
  21504. ASSERT_TRUE(callback_invoked);
  21505. svr.Get("/test", [&](const Request &req, Response &res) {
  21506. res.set_content("test", "text/plain");
  21507. auto cert = req.peer_cert();
  21508. ASSERT_TRUE(static_cast<bool>(cert));
  21509. auto common_name = cert.subject_cn();
  21510. EXPECT_EQ("Common Name", common_name);
  21511. });
  21512. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21513. auto se = detail::scope_exit([&] {
  21514. svr.stop();
  21515. t.join();
  21516. ASSERT_FALSE(svr.is_running());
  21517. });
  21518. svr.wait_until_ready();
  21519. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21520. cli.enable_server_certificate_verification(false);
  21521. cli.set_connection_timeout(30);
  21522. auto res = cli.Get("/test");
  21523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21524. ASSERT_EQ(StatusCode::OK_200, res->status);
  21525. }
  21526. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21527. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21528. // keep-alive SSL session, which reads through that config in
  21529. // mbedtls_ssl_close_notify.
  21530. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21531. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21532. ASSERT_TRUE(svr.is_valid());
  21533. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21534. res.set_content("test", "text/plain");
  21535. });
  21536. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21537. auto se = detail::scope_exit([&] {
  21538. svr.stop();
  21539. t.join();
  21540. ASSERT_FALSE(svr.is_running());
  21541. });
  21542. svr.wait_until_ready();
  21543. {
  21544. SSLClient cli(HOST, PORT);
  21545. cli.enable_server_certificate_verification(false);
  21546. cli.set_keep_alive(true);
  21547. auto res = cli.Get("/test");
  21548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21549. ASSERT_EQ(StatusCode::OK_200, res->status);
  21550. // cli is destructed here with the keep-alive SSL session still open.
  21551. }
  21552. }
  21553. #endif
  21554. // WebSocket Tests
  21555. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21556. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21557. // defining the meaning of these bits has been negotiated.
  21558. auto make_frame = [](uint8_t first_byte) {
  21559. std::string frame;
  21560. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21561. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21562. frame += "Hello";
  21563. return frame;
  21564. };
  21565. // RSV1 set (0x40)
  21566. {
  21567. detail::BufferStream strm;
  21568. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21569. ws::Opcode opcode;
  21570. std::string payload;
  21571. bool fin;
  21572. EXPECT_EQ(
  21573. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21574. ws::impl::FrameRead::Fail);
  21575. }
  21576. // RSV2 set (0x20)
  21577. {
  21578. detail::BufferStream strm;
  21579. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21580. ws::Opcode opcode;
  21581. std::string payload;
  21582. bool fin;
  21583. EXPECT_EQ(
  21584. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21585. ws::impl::FrameRead::Fail);
  21586. }
  21587. // RSV3 set (0x10)
  21588. {
  21589. detail::BufferStream strm;
  21590. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21591. ws::Opcode opcode;
  21592. std::string payload;
  21593. bool fin;
  21594. EXPECT_EQ(
  21595. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21596. ws::impl::FrameRead::Fail);
  21597. }
  21598. // No RSV bits set - should succeed
  21599. {
  21600. detail::BufferStream strm;
  21601. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21602. ws::Opcode opcode;
  21603. std::string payload;
  21604. bool fin;
  21605. EXPECT_EQ(
  21606. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21607. ws::impl::FrameRead::Ok);
  21608. EXPECT_EQ(ws::Opcode::Text, opcode);
  21609. EXPECT_EQ("Hello", payload);
  21610. EXPECT_TRUE(fin);
  21611. }
  21612. }
  21613. TEST(WebSocketTest, ControlFrameValidation) {
  21614. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21615. // payload length <= 125.
  21616. // Ping with FIN=0 - must be rejected
  21617. {
  21618. detail::BufferStream strm;
  21619. std::string frame;
  21620. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21621. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21622. strm.write(frame.data(), frame.size());
  21623. ws::Opcode opcode;
  21624. std::string payload;
  21625. bool fin;
  21626. EXPECT_EQ(
  21627. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21628. ws::impl::FrameRead::Fail);
  21629. }
  21630. // Close with FIN=0 - must be rejected
  21631. {
  21632. detail::BufferStream strm;
  21633. std::string frame;
  21634. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21635. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21636. strm.write(frame.data(), frame.size());
  21637. ws::Opcode opcode;
  21638. std::string payload;
  21639. bool fin;
  21640. EXPECT_EQ(
  21641. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21642. ws::impl::FrameRead::Fail);
  21643. }
  21644. // Ping with payload_len=126 (extended length) - must be rejected
  21645. {
  21646. detail::BufferStream strm;
  21647. std::string frame;
  21648. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21649. frame += static_cast<char>(126); // payload_len=126 (>125)
  21650. frame += static_cast<char>(0x00); // extended length high byte
  21651. frame += static_cast<char>(126); // extended length low byte
  21652. frame += std::string(126, 'x');
  21653. strm.write(frame.data(), frame.size());
  21654. ws::Opcode opcode;
  21655. std::string payload;
  21656. bool fin;
  21657. EXPECT_EQ(
  21658. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21659. ws::impl::FrameRead::Fail);
  21660. }
  21661. // Ping with FIN=1 and payload_len=125 - should succeed
  21662. {
  21663. detail::BufferStream strm;
  21664. std::string frame;
  21665. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21666. frame += static_cast<char>(125); // payload_len=125
  21667. frame += std::string(125, 'x');
  21668. strm.write(frame.data(), frame.size());
  21669. ws::Opcode opcode;
  21670. std::string payload;
  21671. bool fin;
  21672. EXPECT_EQ(
  21673. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21674. ws::impl::FrameRead::Ok);
  21675. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21676. EXPECT_EQ(125u, payload.size());
  21677. EXPECT_TRUE(fin);
  21678. }
  21679. }
  21680. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21681. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21682. // length MUST be 0.
  21683. // MSB set - must be rejected
  21684. {
  21685. detail::BufferStream strm;
  21686. std::string frame;
  21687. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21688. frame += static_cast<char>(127); // 64-bit extended length
  21689. frame += static_cast<char>(0x80); // MSB set (invalid)
  21690. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21691. strm.write(frame.data(), frame.size());
  21692. ws::Opcode opcode;
  21693. std::string payload;
  21694. bool fin;
  21695. EXPECT_EQ(
  21696. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21697. ws::impl::FrameRead::Fail);
  21698. }
  21699. // MSB clear - should pass length parsing (will be rejected by max_len,
  21700. // but that's a different check; use a small length to verify)
  21701. {
  21702. detail::BufferStream strm;
  21703. std::string frame;
  21704. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21705. frame += static_cast<char>(127); // 64-bit extended length
  21706. frame += std::string(7, '\0'); // high bytes = 0
  21707. frame += static_cast<char>(0x03); // length = 3
  21708. frame += "abc";
  21709. strm.write(frame.data(), frame.size());
  21710. ws::Opcode opcode;
  21711. std::string payload;
  21712. bool fin;
  21713. EXPECT_EQ(
  21714. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21715. ws::impl::FrameRead::Ok);
  21716. EXPECT_EQ(ws::Opcode::Text, opcode);
  21717. EXPECT_EQ("abc", payload);
  21718. }
  21719. }
  21720. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21721. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21722. // Valid UTF-8
  21723. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21724. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21725. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21726. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21727. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21728. // Invalid UTF-8
  21729. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21730. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21731. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21732. EXPECT_FALSE(
  21733. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21734. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21735. }
  21736. TEST(WebSocketTest, ConnectAndDisconnect) {
  21737. Server svr;
  21738. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21739. std::string msg;
  21740. while (ws.read(msg)) {}
  21741. });
  21742. auto port = svr.bind_to_any_port(HOST);
  21743. std::thread t([&]() { svr.listen_after_bind(); });
  21744. svr.wait_until_ready();
  21745. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21746. auto res = client.connect();
  21747. ASSERT_TRUE(res);
  21748. EXPECT_EQ(Error::Success, res.error());
  21749. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21750. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21751. EXPECT_TRUE(client.is_open());
  21752. client.close();
  21753. EXPECT_FALSE(client.is_open());
  21754. svr.stop();
  21755. t.join();
  21756. }
  21757. TEST(WebSocketTest, ValidURL) {
  21758. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21759. EXPECT_TRUE(ws1.is_valid());
  21760. ws::WebSocketClient ws2("ws://example.com/path");
  21761. EXPECT_TRUE(ws2.is_valid());
  21762. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21763. EXPECT_TRUE(ws3.is_valid());
  21764. #ifdef CPPHTTPLIB_SSL_ENABLED
  21765. ws::WebSocketClient wss1("wss://example.com/path");
  21766. EXPECT_TRUE(wss1.is_valid());
  21767. ws::WebSocketClient wss2("wss://example.com:443/path");
  21768. EXPECT_TRUE(wss2.is_valid());
  21769. #endif
  21770. }
  21771. TEST(WebSocketTest, InvalidURL) {
  21772. // No scheme
  21773. ws::WebSocketClient ws1("localhost:8080/path");
  21774. EXPECT_FALSE(ws1.is_valid());
  21775. // No path
  21776. ws::WebSocketClient ws2("ws://localhost:8080");
  21777. EXPECT_FALSE(ws2.is_valid());
  21778. // Empty string
  21779. ws::WebSocketClient ws3("");
  21780. EXPECT_FALSE(ws3.is_valid());
  21781. // Missing host
  21782. ws::WebSocketClient ws4("ws://:8080/path");
  21783. EXPECT_FALSE(ws4.is_valid());
  21784. // Port number overflow — should not crash
  21785. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21786. EXPECT_FALSE(ws5.is_valid());
  21787. // Port out of range
  21788. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21789. EXPECT_FALSE(ws6.is_valid());
  21790. }
  21791. TEST(WebSocketTest, UnsupportedScheme) {
  21792. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21793. ws::WebSocketClient ws1("http://localhost:8080/path");
  21794. EXPECT_FALSE(ws1.is_valid());
  21795. ws::WebSocketClient ws2("https://localhost:8080/path");
  21796. EXPECT_FALSE(ws2.is_valid());
  21797. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21798. EXPECT_FALSE(ws3.is_valid());
  21799. #else
  21800. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21801. std::invalid_argument);
  21802. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21803. std::invalid_argument);
  21804. #endif
  21805. }
  21806. TEST(WebSocketTest, ConnectWhenInvalid) {
  21807. ws::WebSocketClient ws("not a valid url");
  21808. EXPECT_FALSE(ws.is_valid());
  21809. auto res = ws.connect();
  21810. EXPECT_FALSE(res);
  21811. EXPECT_EQ(Error::Connection, res.error());
  21812. EXPECT_EQ(-1, res.status());
  21813. }
  21814. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21815. // Grab a port that is free, then close it again so nothing listens there
  21816. Server svr;
  21817. auto port = svr.bind_to_any_port(HOST);
  21818. svr.stop();
  21819. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21820. auto res = client.connect();
  21821. ASSERT_FALSE(res);
  21822. EXPECT_EQ(Error::Connection, res.error());
  21823. EXPECT_EQ(-1, res.status());
  21824. }
  21825. TEST(WebSocketTest, DefaultPort) {
  21826. ws::WebSocketClient ws1("ws://example.com/path");
  21827. EXPECT_TRUE(ws1.is_valid());
  21828. // ws:// defaults to port 80 (verified by successful parse)
  21829. #ifdef CPPHTTPLIB_SSL_ENABLED
  21830. ws::WebSocketClient ws2("wss://example.com/path");
  21831. EXPECT_TRUE(ws2.is_valid());
  21832. // wss:// defaults to port 443 (verified by successful parse)
  21833. #endif
  21834. }
  21835. TEST(WebSocketTest, IPv6LiteralAddress) {
  21836. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21837. EXPECT_TRUE(ws1.is_valid());
  21838. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21839. EXPECT_TRUE(ws2.is_valid());
  21840. }
  21841. TEST(WebSocketTest, ComplexPath) {
  21842. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21843. EXPECT_TRUE(ws1.is_valid());
  21844. ws::WebSocketClient ws2("ws://localhost:8080/");
  21845. EXPECT_TRUE(ws2.is_valid());
  21846. }
  21847. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21848. Server svr;
  21849. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21850. std::string msg;
  21851. while (ws.read(msg)) {}
  21852. });
  21853. auto port = svr.bind_to_any_port(HOST);
  21854. std::thread t([&]() { svr.listen_after_bind(); });
  21855. svr.wait_until_ready();
  21856. auto another_host = "example.com";
  21857. auto wrong_ip = "192.0.2.1";
  21858. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21859. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21860. ASSERT_TRUE(client.connect());
  21861. EXPECT_TRUE(client.is_open());
  21862. client.close();
  21863. svr.stop();
  21864. t.join();
  21865. }
  21866. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21867. Server svr;
  21868. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21869. std::string msg;
  21870. while (ws.read(msg)) {}
  21871. });
  21872. auto port = svr.bind_to_any_port(HOST);
  21873. std::thread t([&]() { svr.listen_after_bind(); });
  21874. svr.wait_until_ready();
  21875. auto wrong_ip = "192.0.2.1";
  21876. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21877. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21878. client.set_connection_timeout(1);
  21879. client.set_read_timeout(1);
  21880. client.set_write_timeout(1);
  21881. EXPECT_FALSE(client.connect());
  21882. EXPECT_FALSE(client.is_open());
  21883. svr.stop();
  21884. t.join();
  21885. }
  21886. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21887. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21888. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21889. // (RFC 6761) is only a map key and the Host header value.
  21890. auto host = "target.invalid";
  21891. Server svr;
  21892. std::string received_host;
  21893. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21894. received_host = req.get_header_value("Host");
  21895. std::string msg;
  21896. while (ws.read(msg)) {}
  21897. });
  21898. auto port = svr.bind_to_any_port(HOST);
  21899. std::thread t([&]() { svr.listen_after_bind(); });
  21900. // ASSERT_* below returns from the test body, which would leave t joinable
  21901. // and make ~thread call std::terminate.
  21902. auto se = detail::scope_exit([&] {
  21903. svr.stop();
  21904. if (t.joinable()) { t.join(); }
  21905. });
  21906. svr.wait_until_ready();
  21907. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21908. std::to_string(port) + "/ws");
  21909. client.set_hostname_addr_map({{host, HOST}});
  21910. ASSERT_TRUE(client.connect());
  21911. EXPECT_TRUE(client.is_open());
  21912. client.close();
  21913. svr.stop();
  21914. t.join();
  21915. // The mapping only redirects the connection; the identity stays host_.
  21916. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21917. }
  21918. class WebSocketIntegrationTest : public ::testing::Test {
  21919. protected:
  21920. void SetUp() override {
  21921. server_ = httplib::detail::make_unique<Server>();
  21922. setup_server();
  21923. start_server();
  21924. }
  21925. void TearDown() override {
  21926. server_->stop();
  21927. if (server_thread_.joinable()) { server_thread_.join(); }
  21928. }
  21929. void setup_server() {
  21930. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21931. std::string msg;
  21932. ws::ReadResult ret;
  21933. while ((ret = ws.read(msg))) {
  21934. if (ret == ws::Binary) {
  21935. ws.send(msg.data(), msg.size());
  21936. } else {
  21937. ws.send(msg);
  21938. }
  21939. }
  21940. });
  21941. server_->WebSocket("/ws-echo-string",
  21942. [](const Request &, ws::WebSocket &ws) {
  21943. std::string msg;
  21944. while (ws.read(msg)) {
  21945. ws.send("echo: " + msg);
  21946. }
  21947. });
  21948. server_->WebSocket(
  21949. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21950. // Echo back request metadata
  21951. ws.send("path:" + req.path);
  21952. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21953. std::string msg;
  21954. while (ws.read(msg)) {}
  21955. });
  21956. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21957. std::string msg;
  21958. ws.read(msg); // wait for a message
  21959. ws.close();
  21960. });
  21961. server_->WebSocket("/ws-close-status",
  21962. [](const Request &, ws::WebSocket &ws) {
  21963. std::string msg;
  21964. ws.read(msg); // wait for a message
  21965. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21966. });
  21967. server_->WebSocket(
  21968. "/ws-subprotocol",
  21969. [](const Request &, ws::WebSocket &ws) {
  21970. std::string msg;
  21971. while (ws.read(msg)) {
  21972. ws.send(msg);
  21973. }
  21974. },
  21975. [](const std::vector<std::string> &protocols) -> std::string {
  21976. for (const auto &p : protocols) {
  21977. if (p == "graphql-ws") { return p; }
  21978. }
  21979. return "";
  21980. });
  21981. server_->WebSocket(
  21982. "/ws-subprotocol-unoffered",
  21983. [](const Request &, ws::WebSocket &ws) {
  21984. std::string msg;
  21985. while (ws.read(msg)) {
  21986. ws.send(msg);
  21987. }
  21988. },
  21989. [](const std::vector<std::string> &) -> std::string {
  21990. return "admin";
  21991. });
  21992. }
  21993. void start_server() {
  21994. port_ = server_->bind_to_any_port(HOST);
  21995. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21996. server_->wait_until_ready();
  21997. }
  21998. std::unique_ptr<Server> server_;
  21999. std::thread server_thread_;
  22000. int port_ = 0;
  22001. };
  22002. TEST_F(WebSocketIntegrationTest, TextEcho) {
  22003. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22004. "/ws-echo");
  22005. ASSERT_TRUE(client.connect());
  22006. ASSERT_TRUE(client.is_open());
  22007. ASSERT_TRUE(client.send("Hello WebSocket"));
  22008. std::string msg;
  22009. EXPECT_EQ(ws::Text, client.read(msg));
  22010. EXPECT_EQ("Hello WebSocket", msg);
  22011. client.close();
  22012. }
  22013. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  22014. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22015. "/ws-echo");
  22016. ASSERT_TRUE(client.connect());
  22017. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  22018. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  22019. std::string msg;
  22020. EXPECT_EQ(ws::Binary, client.read(msg));
  22021. EXPECT_EQ(binary_data, msg);
  22022. client.close();
  22023. }
  22024. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  22025. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22026. "/ws-echo");
  22027. ASSERT_TRUE(client.connect());
  22028. for (int i = 0; i < 10; i++) {
  22029. auto text = "message " + std::to_string(i);
  22030. ASSERT_TRUE(client.send(text));
  22031. std::string msg;
  22032. ASSERT_TRUE(client.read(msg));
  22033. EXPECT_EQ(text, msg);
  22034. }
  22035. client.close();
  22036. }
  22037. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22039. "/ws-close");
  22040. ASSERT_TRUE(client.connect());
  22041. // Send a message to trigger the server to close
  22042. ASSERT_TRUE(client.send("trigger close"));
  22043. // The server will close, so read should return false
  22044. std::string msg;
  22045. EXPECT_FALSE(client.read(msg));
  22046. EXPECT_FALSE(client.is_open());
  22047. }
  22048. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22049. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22050. "/ws-echo");
  22051. ASSERT_TRUE(client.connect());
  22052. // 128KB message
  22053. std::string large_data(128 * 1024, 'X');
  22054. ASSERT_TRUE(client.send(large_data));
  22055. std::string msg;
  22056. ASSERT_TRUE(client.read(msg));
  22057. EXPECT_EQ(large_data, msg);
  22058. client.close();
  22059. }
  22060. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22061. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22062. "/ws-echo");
  22063. ASSERT_TRUE(client.connect());
  22064. const int num_threads = 4;
  22065. std::vector<std::thread> threads;
  22066. std::atomic<int> send_count{0};
  22067. for (int t = 0; t < num_threads; t++) {
  22068. threads.emplace_back([&client, &send_count, t]() {
  22069. for (int i = 0; i < 5; i++) {
  22070. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22071. if (client.send(text)) { send_count++; }
  22072. }
  22073. });
  22074. }
  22075. for (auto &th : threads) {
  22076. th.join();
  22077. }
  22078. int received = 0;
  22079. std::string msg;
  22080. while (received < send_count.load()) {
  22081. if (!client.read(msg)) { break; }
  22082. received++;
  22083. }
  22084. EXPECT_EQ(send_count.load(), received);
  22085. client.close();
  22086. }
  22087. TEST_F(WebSocketIntegrationTest, ReadString) {
  22088. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22089. "/ws-echo-string");
  22090. ASSERT_TRUE(client.connect());
  22091. ASSERT_TRUE(client.send("hello"));
  22092. std::string msg;
  22093. ASSERT_TRUE(client.read(msg));
  22094. EXPECT_EQ("echo: hello", msg);
  22095. ASSERT_TRUE(client.send("world"));
  22096. ASSERT_TRUE(client.read(msg));
  22097. EXPECT_EQ("echo: world", msg);
  22098. client.close();
  22099. }
  22100. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22101. Headers headers = {{"X-Test-Header", "test-value"}};
  22102. ws::WebSocketClient client(
  22103. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22104. ASSERT_TRUE(client.connect());
  22105. std::string msg;
  22106. ASSERT_TRUE(client.read(msg));
  22107. EXPECT_EQ("path:/ws-request-info", msg);
  22108. ASSERT_TRUE(client.read(msg));
  22109. EXPECT_EQ("header:test-value", msg);
  22110. client.close();
  22111. }
  22112. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22113. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22114. "/ws-echo");
  22115. client.set_read_timeout(1, 0); // 1 second
  22116. ASSERT_TRUE(client.connect());
  22117. // Don't send anything — server echo handler waits for a message, so read()
  22118. // should time out. The connection survives it: nothing was consumed.
  22119. std::string msg;
  22120. EXPECT_EQ(client.read(msg), ws::Timeout);
  22121. EXPECT_TRUE(client.is_open());
  22122. // And it is still usable afterwards.
  22123. EXPECT_TRUE(client.send("after timeout"));
  22124. EXPECT_EQ(client.read(msg), ws::Text);
  22125. EXPECT_EQ(msg, "after timeout");
  22126. }
  22127. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22128. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22129. "/ws-echo");
  22130. client.set_read_timeout(1, 0);
  22131. ASSERT_TRUE(client.connect());
  22132. ASSERT_TRUE(client.send("first"));
  22133. std::string msg;
  22134. ASSERT_EQ(client.read(msg), ws::Text);
  22135. ASSERT_EQ(msg, "first");
  22136. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22137. // not be used with a read timeout: it would reprocess the previous message.
  22138. EXPECT_EQ(client.read(msg), ws::Timeout);
  22139. EXPECT_EQ(msg, "first");
  22140. }
  22141. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22142. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22143. "/ws-echo");
  22144. ASSERT_TRUE(client.connect());
  22145. // Setting it once the connection is open reaches the live stream, not just
  22146. // the seed for the next connect().
  22147. client.set_read_timeout(1, 0);
  22148. std::string msg;
  22149. EXPECT_EQ(client.read(msg), ws::Timeout);
  22150. EXPECT_TRUE(client.is_open());
  22151. }
  22152. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22153. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22154. "/ws-echo");
  22155. client.set_read_timeout(5, 0);
  22156. ASSERT_TRUE(client.connect());
  22157. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22158. // The server should reject it and close the connection.
  22159. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22160. client.send(oversized);
  22161. // The server's read() should have failed due to payload limit,
  22162. // so our read() should return false (connection closed).
  22163. std::string msg;
  22164. EXPECT_FALSE(client.read(msg));
  22165. }
  22166. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22167. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22168. "/ws-echo");
  22169. client.set_read_timeout(10, 0);
  22170. ASSERT_TRUE(client.connect());
  22171. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22172. // This should succeed.
  22173. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22174. ASSERT_TRUE(client.send(at_limit));
  22175. std::string msg;
  22176. ASSERT_TRUE(client.read(msg));
  22177. EXPECT_EQ(at_limit.size(), msg.size());
  22178. client.close();
  22179. }
  22180. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22181. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22182. "/nonexistent");
  22183. auto res = client.connect();
  22184. EXPECT_FALSE(res);
  22185. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22186. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22187. EXPECT_FALSE(client.is_open());
  22188. }
  22189. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22190. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22191. "/ws-echo");
  22192. ASSERT_TRUE(client.connect());
  22193. ASSERT_TRUE(client.send(""));
  22194. std::string msg;
  22195. EXPECT_EQ(ws::Text, client.read(msg));
  22196. EXPECT_EQ("", msg);
  22197. client.close();
  22198. }
  22199. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22200. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22201. "/ws-echo");
  22202. // First connection
  22203. ASSERT_TRUE(client.connect());
  22204. ASSERT_TRUE(client.send("first"));
  22205. std::string msg;
  22206. ASSERT_TRUE(client.read(msg));
  22207. EXPECT_EQ("first", msg);
  22208. client.close();
  22209. EXPECT_FALSE(client.is_open());
  22210. // Reconnect using the same client object
  22211. ASSERT_TRUE(client.connect());
  22212. ASSERT_TRUE(client.is_open());
  22213. ASSERT_TRUE(client.send("second"));
  22214. ASSERT_TRUE(client.read(msg));
  22215. EXPECT_EQ("second", msg);
  22216. client.close();
  22217. }
  22218. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22219. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22220. "/ws-close-status");
  22221. ASSERT_TRUE(client.connect());
  22222. // Trigger the server to close with GoingAway status
  22223. ASSERT_TRUE(client.send("trigger"));
  22224. // read() should return false after receiving the close frame
  22225. std::string msg;
  22226. EXPECT_FALSE(client.read(msg));
  22227. EXPECT_FALSE(client.is_open());
  22228. }
  22229. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22230. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22231. "/ws-echo");
  22232. ASSERT_TRUE(client.connect());
  22233. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22234. EXPECT_FALSE(client.is_open());
  22235. }
  22236. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22237. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22238. ws::WebSocketClient client(
  22239. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22240. ASSERT_TRUE(client.connect());
  22241. // Server should have selected graphql-ws
  22242. EXPECT_EQ("graphql-ws", client.subprotocol());
  22243. client.close();
  22244. }
  22245. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22246. Headers headers;
  22247. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22248. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22249. ws::WebSocketClient client(
  22250. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22251. ASSERT_TRUE(client.connect());
  22252. // The offer on the second field line counts too, so graphql-ws is selected
  22253. EXPECT_EQ("graphql-ws", client.subprotocol());
  22254. client.close();
  22255. }
  22256. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22257. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22258. ws::WebSocketClient client(
  22259. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22260. ASSERT_TRUE(client.connect());
  22261. // Server should not have selected any subprotocol
  22262. EXPECT_TRUE(client.subprotocol().empty());
  22263. client.close();
  22264. }
  22265. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22266. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22267. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22268. "/ws-subprotocol-unoffered",
  22269. headers);
  22270. ASSERT_TRUE(client.connect());
  22271. EXPECT_TRUE(client.subprotocol().empty());
  22272. client.close();
  22273. }
  22274. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22275. // Connect without requesting any subprotocol
  22276. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22277. "/ws-subprotocol");
  22278. ASSERT_TRUE(client.connect());
  22279. EXPECT_TRUE(client.subprotocol().empty());
  22280. client.close();
  22281. }
  22282. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22283. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22284. "/ws-echo");
  22285. client.set_tcp_nodelay(true);
  22286. client.set_connection_timeout(3, 0);
  22287. bool socket_options_called = false;
  22288. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22289. ASSERT_TRUE(client.connect());
  22290. ASSERT_TRUE(client.is_open());
  22291. EXPECT_TRUE(socket_options_called);
  22292. ASSERT_TRUE(client.send("hello"));
  22293. std::string msg;
  22294. auto result = client.read(msg);
  22295. EXPECT_EQ(result, ws::ReadResult::Text);
  22296. EXPECT_EQ(msg, "hello");
  22297. client.close();
  22298. }
  22299. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22300. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22301. "/ws-echo");
  22302. client.set_connection_timeout(std::chrono::seconds(3));
  22303. client.set_write_timeout(std::chrono::seconds(3));
  22304. // A sub-second remainder exercises the seconds/microseconds split.
  22305. client.set_read_timeout(std::chrono::milliseconds(1500));
  22306. ASSERT_TRUE(client.connect());
  22307. auto start = std::chrono::steady_clock::now();
  22308. std::string msg;
  22309. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22310. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22311. std::chrono::steady_clock::now() - start)
  22312. .count();
  22313. // Above 1s so that dropping the microseconds half of the split fails here.
  22314. // Ignoring the setter altogether would not reach this line at all: a client
  22315. // waits forever by default.
  22316. EXPECT_GE(elapsed, 1400);
  22317. EXPECT_LT(elapsed, 30000);
  22318. }
  22319. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22320. Server svr;
  22321. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22322. if (!req.has_header("Authorization")) {
  22323. res.status = StatusCode::Unauthorized_401;
  22324. res.set_content("Unauthorized", "text/plain");
  22325. return Server::HandlerResponse::Handled;
  22326. }
  22327. return Server::HandlerResponse::Unhandled;
  22328. });
  22329. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22330. std::string msg;
  22331. while (ws.read(msg)) {
  22332. ws.send(msg);
  22333. }
  22334. });
  22335. auto port = svr.bind_to_any_port("localhost");
  22336. std::thread t([&]() { svr.listen_after_bind(); });
  22337. svr.wait_until_ready();
  22338. // Without Authorization header - should be rejected before upgrade
  22339. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22340. EXPECT_FALSE(client1.connect());
  22341. // The rejection is framed like any other HTTP response
  22342. {
  22343. Client cli("localhost", port);
  22344. Headers headers = {{"Upgrade", "websocket"},
  22345. {"Connection", "Upgrade"},
  22346. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22347. {"Sec-WebSocket-Version", "13"}};
  22348. auto res = cli.Get("/ws", headers);
  22349. ASSERT_TRUE(res);
  22350. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22351. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22352. EXPECT_EQ("Unauthorized", res->body);
  22353. }
  22354. // With Authorization header - should succeed
  22355. Headers headers = {{"Authorization", "Bearer token123"}};
  22356. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22357. headers);
  22358. ASSERT_TRUE(client2.connect());
  22359. ASSERT_TRUE(client2.send("hello"));
  22360. std::string msg;
  22361. ASSERT_TRUE(client2.read(msg));
  22362. EXPECT_EQ("hello", msg);
  22363. client2.close();
  22364. svr.stop();
  22365. t.join();
  22366. }
  22367. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22368. Server svr;
  22369. std::atomic<int> pre_request_calls{0};
  22370. std::atomic<bool> route_matched{false};
  22371. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22372. pre_request_calls++;
  22373. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22374. if (req.get_header_value("Authorization") != "Bearer token123") {
  22375. res.status = StatusCode::Unauthorized_401;
  22376. res.set_content("Unauthorized", "text/plain");
  22377. return Server::HandlerResponse::Handled;
  22378. }
  22379. return Server::HandlerResponse::Unhandled;
  22380. });
  22381. std::atomic<bool> handler_called{false};
  22382. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22383. handler_called = true;
  22384. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22385. });
  22386. auto port = svr.bind_to_any_port("localhost");
  22387. std::thread t([&]() { svr.listen_after_bind(); });
  22388. svr.wait_until_ready();
  22389. // Without Authorization header - should be rejected before upgrade
  22390. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22391. "/ws/1");
  22392. EXPECT_FALSE(client1.connect());
  22393. EXPECT_FALSE(handler_called);
  22394. EXPECT_EQ(1, pre_request_calls);
  22395. EXPECT_TRUE(route_matched);
  22396. // The rejection is an ordinary HTTP response, not a protocol switch
  22397. {
  22398. Client cli("localhost", port);
  22399. Headers headers = {{"Upgrade", "websocket"},
  22400. {"Connection", "Upgrade"},
  22401. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22402. {"Sec-WebSocket-Version", "13"}};
  22403. auto res = cli.Get("/ws/1", headers);
  22404. ASSERT_TRUE(res);
  22405. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22406. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22407. EXPECT_EQ("Unauthorized", res->body);
  22408. }
  22409. EXPECT_FALSE(handler_called);
  22410. // With Authorization header - should succeed
  22411. Headers headers = {{"Authorization", "Bearer token123"}};
  22412. ws::WebSocketClient client2(
  22413. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22414. ASSERT_TRUE(client2.connect());
  22415. std::string msg;
  22416. ASSERT_TRUE(client2.read(msg));
  22417. EXPECT_EQ("/ws/:id 2", msg);
  22418. EXPECT_TRUE(handler_called);
  22419. client2.close();
  22420. svr.stop();
  22421. t.join();
  22422. }
  22423. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22424. Server svr;
  22425. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22426. // A read timeout is how a handler gets control back. Without it, a handler
  22427. // parked in read() can never write on the connection it is reading.
  22428. ws.set_read_timeout(std::chrono::milliseconds(100));
  22429. std::string msg;
  22430. while (ws.is_open()) {
  22431. auto r = ws.read(msg);
  22432. if (r == httplib::ws::Timeout) {
  22433. ws.send("tick");
  22434. continue;
  22435. }
  22436. if (r == httplib::ws::Fail) { break; }
  22437. ws.send(msg);
  22438. }
  22439. });
  22440. auto port = svr.bind_to_any_port("localhost");
  22441. std::thread t([&]() { svr.listen_after_bind(); });
  22442. svr.wait_until_ready();
  22443. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22444. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22445. ASSERT_TRUE(client.connect());
  22446. // The client sends nothing, so anything it receives came out of the
  22447. // handler's timeout path.
  22448. std::string msg;
  22449. ASSERT_EQ(client.read(msg), ws::Text);
  22450. EXPECT_EQ("tick", msg);
  22451. client.close();
  22452. svr.stop();
  22453. t.join();
  22454. }
  22455. // Stream::read may return fewer bytes than asked for. This is that contract at
  22456. // its worst -- one byte per call -- which is what a frame header straddling a
  22457. // read buffer's boundary looks like to the frame parser.
  22458. class WsByteAtATimeStream : public Stream {
  22459. public:
  22460. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22461. bool is_readable() const override { return true; }
  22462. bool wait_readable() const override { return true; }
  22463. bool wait_writable() const override { return true; }
  22464. ssize_t read(char *ptr, size_t size) override {
  22465. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22466. *ptr = data_[pos_++];
  22467. return 1;
  22468. }
  22469. ssize_t write(const char *, size_t size) override {
  22470. return static_cast<ssize_t>(size);
  22471. }
  22472. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22473. ip = "127.0.0.1";
  22474. port = 0;
  22475. }
  22476. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22477. ip = "127.0.0.1";
  22478. port = 0;
  22479. }
  22480. socket_t socket() const override { return INVALID_SOCKET; }
  22481. time_t duration() const override { return 0; }
  22482. private:
  22483. std::string data_;
  22484. size_t pos_ = 0;
  22485. };
  22486. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22487. // The payload uses the 16-bit extended length, so the header, the length
  22488. // and the mask key are all multi-byte fields here. Each used to be read
  22489. // with a single read() call, which fails as soon as one is split. The
  22490. // payload is also a little over one read chunk, so it is read in two.
  22491. std::string body;
  22492. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22493. body += static_cast<char>(i % 251);
  22494. }
  22495. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22496. std::string frame;
  22497. frame += static_cast<char>(0x81); // FIN + Text
  22498. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22499. frame += static_cast<char>(body.size() >> 8);
  22500. frame += static_cast<char>(body.size() & 0xff);
  22501. for (size_t i = 0; i < 4; i++) {
  22502. frame += static_cast<char>(mask[i]);
  22503. }
  22504. for (size_t i = 0; i < body.size(); i++) {
  22505. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22506. }
  22507. WsByteAtATimeStream strm(frame);
  22508. ws::Opcode opcode;
  22509. std::string payload;
  22510. bool fin = false;
  22511. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22512. /*expect_masked=*/true, body.size()),
  22513. ws::impl::FrameRead::Ok);
  22514. EXPECT_TRUE(fin);
  22515. EXPECT_EQ(opcode, ws::Opcode::Text);
  22516. EXPECT_EQ(payload, body);
  22517. }
  22518. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22519. std::string body(2000, 'x');
  22520. std::string frame;
  22521. frame += static_cast<char>(0x82); // FIN + Binary
  22522. frame += static_cast<char>(126); // 16-bit length follows
  22523. frame += static_cast<char>(body.size() >> 8);
  22524. frame += static_cast<char>(body.size() & 0xff);
  22525. frame += body;
  22526. detail::BufferStream strm;
  22527. strm.write(frame.data(), frame.size());
  22528. ws::Opcode opcode;
  22529. std::string payload;
  22530. bool fin;
  22531. EXPECT_EQ(
  22532. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22533. ws::impl::FrameRead::Ok);
  22534. EXPECT_EQ(body, payload);
  22535. }
  22536. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22537. // The header announces the largest payload allowed, and only 3 bytes of it
  22538. // ever arrive.
  22539. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22540. std::string frame;
  22541. frame += static_cast<char>(0x82); // FIN + Binary
  22542. frame += static_cast<char>(127); // 64-bit length follows
  22543. for (int shift = 56; shift >= 0; shift -= 8) {
  22544. frame += static_cast<char>((len >> shift) & 0xff);
  22545. }
  22546. frame += "abc";
  22547. detail::BufferStream strm;
  22548. strm.write(frame.data(), frame.size());
  22549. ws::Opcode opcode;
  22550. std::string payload;
  22551. bool fin;
  22552. EXPECT_EQ(
  22553. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22554. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22555. ws::impl::FrameRead::Fail);
  22556. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22557. }
  22558. TEST(WebSocketTest, QueryStringInHandshake) {
  22559. Server svr;
  22560. std::mutex mtx;
  22561. std::string received_target;
  22562. std::string received_token;
  22563. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22564. {
  22565. std::lock_guard<std::mutex> lock(mtx);
  22566. received_target = req.target;
  22567. if (req.has_param("token")) {
  22568. received_token = req.get_param_value("token");
  22569. }
  22570. }
  22571. std::string msg;
  22572. while (ws.read(msg)) {
  22573. ws.send(msg);
  22574. }
  22575. });
  22576. auto port = svr.bind_to_any_port("localhost");
  22577. std::thread t([&]() { svr.listen_after_bind(); });
  22578. svr.wait_until_ready();
  22579. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22580. "/ws?token=ABC&session=123");
  22581. ASSERT_TRUE(client.connect());
  22582. // Round-trip ensures the handler has run and captured the request.
  22583. ASSERT_TRUE(client.send("hello"));
  22584. std::string msg;
  22585. ASSERT_TRUE(client.read(msg));
  22586. EXPECT_EQ("hello", msg);
  22587. client.close();
  22588. {
  22589. std::lock_guard<std::mutex> lock(mtx);
  22590. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22591. EXPECT_EQ("ABC", received_token);
  22592. }
  22593. svr.stop();
  22594. t.join();
  22595. }
  22596. // Run a handshake against a throwaway server and hand the request the server
  22597. // received back to the caller, so tests can assert on the headers the client
  22598. // actually put on the wire.
  22599. static void capture_websocket_handshake_request(
  22600. const Headers &client_headers,
  22601. std::function<void(const Request &, int port)> verify) {
  22602. Server svr;
  22603. std::mutex mtx;
  22604. Request received;
  22605. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22606. {
  22607. std::lock_guard<std::mutex> lock(mtx);
  22608. received = req;
  22609. }
  22610. std::string msg;
  22611. while (ws.read(msg)) {
  22612. ws.send(msg);
  22613. }
  22614. });
  22615. auto port = svr.bind_to_any_port("localhost");
  22616. std::thread t([&]() { svr.listen_after_bind(); });
  22617. auto se = detail::scope_exit([&] {
  22618. svr.stop();
  22619. t.join();
  22620. });
  22621. svr.wait_until_ready();
  22622. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22623. client_headers);
  22624. ASSERT_TRUE(client.connect());
  22625. ASSERT_TRUE(client.send("hello"));
  22626. std::string msg;
  22627. ASSERT_TRUE(client.read(msg));
  22628. client.close();
  22629. {
  22630. std::lock_guard<std::mutex> lock(mtx);
  22631. verify(received, port);
  22632. }
  22633. }
  22634. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22635. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22636. // Non-default port must be present in the Host header. Default ports
  22637. // (80/443) are omitted; that logic is covered by
  22638. // MakeHostAndPortStringTest.
  22639. EXPECT_EQ("localhost:" + std::to_string(port),
  22640. req.get_header_value("Host"));
  22641. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22642. req.get_header_value("User-Agent"));
  22643. EXPECT_FALSE(req.has_header("Accept"));
  22644. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22645. EXPECT_FALSE(req.has_header("Content-Length"));
  22646. });
  22647. }
  22648. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22649. capture_websocket_handshake_request(
  22650. {{"Host", "example.com"},
  22651. {"User-Agent", "custom-agent"},
  22652. {"X-Custom", "value"}},
  22653. [](const Request &req, int) {
  22654. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22655. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22656. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22657. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22658. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22659. });
  22660. }
  22661. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22662. capture_websocket_handshake_request(
  22663. {{"Upgrade", "bogus"},
  22664. {"Connection", "close"},
  22665. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22666. {"Sec-WebSocket-Version", "8"}},
  22667. [](const Request &req, int) {
  22668. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22669. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22670. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22671. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22672. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22673. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22674. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22675. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22676. req.get_header_value("Sec-WebSocket-Key"));
  22677. });
  22678. }
  22679. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22680. // A header the client refuses to send must abort the handshake before any
  22681. // part of it reaches the wire; a lone request line would otherwise sit in
  22682. // the peer's buffer as a truncated request.
  22683. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22684. ASSERT_NE(INVALID_SOCKET, srv);
  22685. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22686. sockaddr_in addr{};
  22687. addr.sin_family = AF_INET;
  22688. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22689. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22690. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22691. ASSERT_EQ(0, ::listen(srv, 1));
  22692. sockaddr_in bound{};
  22693. socklen_t bound_len = sizeof(bound);
  22694. ASSERT_EQ(
  22695. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22696. auto port = ntohs(bound.sin_port);
  22697. ssize_t received = -1;
  22698. std::thread t([&] {
  22699. // Bound every blocking call so a regression fails the test with a bad
  22700. // value instead of hanging the suite.
  22701. fd_set rfds;
  22702. FD_ZERO(&rfds);
  22703. FD_SET(srv, &rfds);
  22704. timeval tv{5, 0};
  22705. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22706. 0) {
  22707. return;
  22708. }
  22709. sockaddr_in cli_addr{};
  22710. socklen_t cli_len = sizeof(cli_addr);
  22711. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22712. if (cli == INVALID_SOCKET) { return; }
  22713. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22714. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22715. char buf[4096];
  22716. received = ::recv(cli, buf, sizeof(buf), 0);
  22717. });
  22718. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22719. // connect() has already shut the socket down by the time it returns false,
  22720. // so the peer sees EOF without waiting for the client to be destroyed.
  22721. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22722. {{"X-Bad", "a\r\nInjected: 1"}});
  22723. EXPECT_FALSE(client.connect());
  22724. t.join();
  22725. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22726. EXPECT_EQ(0, received);
  22727. }
  22728. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22729. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22730. // contains "upgrade" as a substring is a different token and must not
  22731. // start a WebSocket handshake.
  22732. auto make_request = [](const std::vector<std::string> &connection_values) {
  22733. Request req;
  22734. req.method = "GET";
  22735. req.headers.emplace("Upgrade", "websocket");
  22736. for (const auto &value : connection_values) {
  22737. req.headers.emplace("Connection", value);
  22738. }
  22739. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22740. req.headers.emplace("Sec-WebSocket-Version", "13");
  22741. return req;
  22742. };
  22743. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22744. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22745. EXPECT_TRUE(
  22746. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22747. EXPECT_TRUE(
  22748. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22749. EXPECT_TRUE(
  22750. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22751. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22752. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22753. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22754. EXPECT_FALSE(
  22755. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22756. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22757. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22758. }
  22759. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22760. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22761. // asks recipients to match each protocol-name case-insensitively, and RFC
  22762. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22763. // client naming websocket alongside another protocol, or on a second field
  22764. // line, is offering websocket; a value that merely contains "websocket" as a
  22765. // substring is a different protocol name and is not.
  22766. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22767. Request req;
  22768. req.method = "GET";
  22769. for (const auto &value : upgrade_values) {
  22770. req.headers.emplace("Upgrade", value);
  22771. }
  22772. req.headers.emplace("Connection", "Upgrade");
  22773. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22774. req.headers.emplace("Sec-WebSocket-Version", "13");
  22775. return req;
  22776. };
  22777. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22778. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22779. EXPECT_TRUE(
  22780. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22781. EXPECT_TRUE(
  22782. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22783. EXPECT_TRUE(
  22784. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22785. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22786. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22787. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22788. EXPECT_FALSE(
  22789. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22790. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22791. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22792. }
  22793. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22794. Server svr;
  22795. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22796. auto port = svr.bind_to_any_port("localhost");
  22797. std::thread t([&]() { svr.listen_after_bind(); });
  22798. auto se = detail::scope_exit([&] {
  22799. svr.stop();
  22800. t.join();
  22801. });
  22802. svr.wait_until_ready();
  22803. Headers headers = {{"Upgrade", "websocket"},
  22804. {"Connection", "notupgrade"},
  22805. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22806. {"Sec-WebSocket-Version", "13"}};
  22807. Client cli("localhost", port);
  22808. auto res = cli.Get("/ws", headers);
  22809. // The route exists only as a WebSocket route, so a request that fails the
  22810. // handshake check falls through to ordinary routing.
  22811. ASSERT_TRUE(res);
  22812. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22813. }
  22814. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22815. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22816. // Connection value is the only thing left for the client to reject.
  22817. Server svr;
  22818. svr.Get("/ws", [](const Request &req, Response &res) {
  22819. res.status = StatusCode::SwitchingProtocol_101;
  22820. res.set_header("Upgrade", "websocket");
  22821. res.set_header("Connection", "notupgrade");
  22822. res.set_header("Sec-WebSocket-Accept",
  22823. detail::websocket_accept_key(
  22824. req.get_header_value("Sec-WebSocket-Key")));
  22825. });
  22826. auto port = svr.bind_to_any_port("localhost");
  22827. std::thread t([&]() { svr.listen_after_bind(); });
  22828. auto se = detail::scope_exit([&] {
  22829. svr.stop();
  22830. t.join();
  22831. });
  22832. svr.wait_until_ready();
  22833. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22834. auto res = client.connect();
  22835. EXPECT_FALSE(res);
  22836. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22837. EXPECT_FALSE(client.is_open());
  22838. }
  22839. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22840. Server svr;
  22841. svr.Get("/ws", [](const Request &req, Response &res) {
  22842. res.status = StatusCode::SwitchingProtocol_101;
  22843. res.set_header("Upgrade", "websocket");
  22844. res.set_header("Connection", "Upgrade");
  22845. res.set_header("Sec-WebSocket-Accept",
  22846. detail::websocket_accept_key(
  22847. req.get_header_value("Sec-WebSocket-Key")));
  22848. res.set_header("Sec-WebSocket-Protocol", "admin");
  22849. });
  22850. auto port = svr.bind_to_any_port("localhost");
  22851. std::thread t([&]() { svr.listen_after_bind(); });
  22852. auto se = detail::scope_exit([&] {
  22853. svr.stop();
  22854. t.join();
  22855. });
  22856. svr.wait_until_ready();
  22857. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22858. // Server selects a subprotocol the client never offered
  22859. {
  22860. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22861. ws::WebSocketClient client(url, headers);
  22862. auto res = client.connect();
  22863. EXPECT_FALSE(res);
  22864. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22865. EXPECT_FALSE(client.is_open());
  22866. EXPECT_TRUE(client.subprotocol().empty());
  22867. }
  22868. // Client offered none but the server named one anyway
  22869. {
  22870. ws::WebSocketClient client(url);
  22871. auto res = client.connect();
  22872. EXPECT_FALSE(res);
  22873. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22874. EXPECT_FALSE(client.is_open());
  22875. EXPECT_TRUE(client.subprotocol().empty());
  22876. }
  22877. }
  22878. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22879. // The socket path doubles as the URL host, so it must not contain '/'.
  22880. const char *shard = getenv("GTEST_SHARD_INDEX");
  22881. const std::string sock_path =
  22882. shard ? std::string("httplib-ws-") + shard + ".sock"
  22883. : std::string("httplib-ws.sock");
  22884. std::remove(sock_path.c_str());
  22885. Server svr;
  22886. std::mutex mtx;
  22887. std::string received_host;
  22888. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22889. {
  22890. std::lock_guard<std::mutex> lock(mtx);
  22891. received_host = req.get_header_value("Host");
  22892. }
  22893. std::string msg;
  22894. while (ws.read(msg)) {
  22895. ws.send(msg);
  22896. }
  22897. });
  22898. svr.set_address_family(AF_UNIX);
  22899. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22900. auto se = detail::scope_exit([&] {
  22901. svr.stop();
  22902. t.join();
  22903. std::remove(sock_path.c_str());
  22904. });
  22905. svr.wait_until_ready();
  22906. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22907. client.set_address_family(AF_UNIX);
  22908. ASSERT_TRUE(client.connect());
  22909. ASSERT_TRUE(client.send("hello"));
  22910. std::string msg;
  22911. ASSERT_TRUE(client.read(msg));
  22912. client.close();
  22913. {
  22914. std::lock_guard<std::mutex> lock(mtx);
  22915. // There is no host:port for a Unix socket, so the same "localhost"
  22916. // placeholder the HTTP client uses is expected.
  22917. EXPECT_EQ("localhost", received_host);
  22918. }
  22919. }
  22920. // Two threads must never parse WebSocket frames from the same stream.
  22921. // close() used to read the peer's Close reply with its own frame read, so it
  22922. // raced a reader thread that was in the middle of a payload: the payload loop
  22923. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22924. // so bytes taken by close() were replaced with bytes from further along the
  22925. // stream. The message kept its length and silently changed content.
  22926. //
  22927. // The raw peer below sends a frame header plus part of the payload, waits for
  22928. // the handler to call close(), and only then sends the rest. Whichever thread
  22929. // would win the race for those bytes, the message must arrive intact, because
  22930. // close() must not touch the stream while read() owns it.
  22931. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22932. #ifndef _WIN32
  22933. signal(SIGPIPE, SIG_IGN);
  22934. #endif
  22935. const size_t payload_len = 120; // fits the 7-bit length field
  22936. const size_t prefix_len = 8;
  22937. const int attempts = 8;
  22938. std::string expected(payload_len, '\0');
  22939. for (size_t i = 0; i < payload_len; i++) {
  22940. expected[i] = static_cast<char>('a' + i % 26);
  22941. }
  22942. std::atomic<bool> peer_stalled{false};
  22943. std::atomic<bool> handler_done{false};
  22944. std::mutex received_mutex;
  22945. std::vector<std::string> received;
  22946. // Bound every wait, so a regression fails the test instead of hanging the
  22947. // suite.
  22948. auto wait_for = [](const std::atomic<bool> &flag) {
  22949. for (int i = 0; i < 500 && !flag; i++) {
  22950. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22951. }
  22952. };
  22953. Server svr;
  22954. svr.set_websocket_ping_interval(0);
  22955. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22956. std::thread reader([&]() {
  22957. std::string msg;
  22958. while (ws.read(msg)) {
  22959. std::lock_guard<std::mutex> guard(received_mutex);
  22960. received.push_back(msg);
  22961. }
  22962. });
  22963. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22964. // inside read_websocket_frame() when close() runs.
  22965. wait_for(peer_stalled);
  22966. ws.close();
  22967. reader.join();
  22968. handler_done = true;
  22969. });
  22970. auto port = svr.bind_to_any_port("127.0.0.1");
  22971. std::thread t([&]() { svr.listen_after_bind(); });
  22972. auto se = detail::scope_exit([&] {
  22973. svr.stop();
  22974. t.join();
  22975. });
  22976. svr.wait_until_ready();
  22977. auto send_bytes = [](socket_t s, const std::string &data) {
  22978. #ifdef _WIN32
  22979. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22980. #else
  22981. auto n = ::send(s, data.data(), data.size(), 0);
  22982. #endif
  22983. return n == static_cast<decltype(n)>(data.size());
  22984. };
  22985. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22986. // Every length used here fits the 7-bit length field.
  22987. auto masked_header = [](uint8_t first_byte, size_t len) {
  22988. std::string h;
  22989. h += static_cast<char>(first_byte);
  22990. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22991. h.append(4, '\0'); // mask key
  22992. return h;
  22993. };
  22994. for (int attempt = 0; attempt < attempts; attempt++) {
  22995. peer_stalled = false;
  22996. handler_done = false;
  22997. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22998. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22999. auto se_sock = detail::scope_exit([&] {
  23000. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  23001. });
  23002. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23003. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  23004. sockaddr_in addr{};
  23005. addr.sin_family = AF_INET;
  23006. addr.sin_port = htons(static_cast<uint16_t>(port));
  23007. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23008. ASSERT_EQ(
  23009. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  23010. << "attempt " << attempt;
  23011. ASSERT_TRUE(send_bytes(sock,
  23012. "GET /ws HTTP/1.1\r\n"
  23013. "Host: 127.0.0.1\r\n"
  23014. "Upgrade: websocket\r\n"
  23015. "Connection: Upgrade\r\n"
  23016. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23017. "Sec-WebSocket-Version: 13\r\n"
  23018. "\r\n"))
  23019. << "attempt " << attempt;
  23020. std::string response;
  23021. while (response.find("\r\n\r\n") == std::string::npos) {
  23022. char buf[512];
  23023. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  23024. if (n <= 0) { break; }
  23025. response.append(buf, static_cast<size_t>(n));
  23026. }
  23027. ASSERT_NE(std::string::npos, response.find(" 101 "))
  23028. << "attempt " << attempt;
  23029. // Send the header of a Binary message but only the first prefix_len bytes
  23030. // of its payload, leaving the reader thread stalled inside the payload.
  23031. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  23032. expected.substr(0, prefix_len)))
  23033. << "attempt " << attempt;
  23034. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23035. peer_stalled = true;
  23036. // Let close() send its Close frame and park in its own read before the
  23037. // rest of the payload arrives, so both threads are waiting for it.
  23038. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23039. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23040. close_frame += static_cast<char>(0x03); // status 1000
  23041. close_frame += static_cast<char>(0xE8);
  23042. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23043. << "attempt " << attempt;
  23044. // Closing the peer releases the reader thread even on the buggy path,
  23045. // where it waits for bytes another thread already consumed.
  23046. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23047. detail::close_socket(sock);
  23048. sock = INVALID_SOCKET;
  23049. wait_for(handler_done);
  23050. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23051. }
  23052. std::lock_guard<std::mutex> guard(received_mutex);
  23053. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23054. << "a message in flight when close() ran was dropped";
  23055. for (size_t i = 0; i < received.size(); i++) {
  23056. EXPECT_EQ(expected, received[i]) << "message " << i;
  23057. }
  23058. }
  23059. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23060. // returning the socket, or INVALID_SOCKET.
  23061. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23062. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23063. if (sock == INVALID_SOCKET) { return sock; }
  23064. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23065. sockaddr_in addr{};
  23066. addr.sin_family = AF_INET;
  23067. addr.sin_port = htons(static_cast<uint16_t>(port));
  23068. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23069. std::string req = "GET " + path +
  23070. " HTTP/1.1\r\n"
  23071. "Host: 127.0.0.1\r\n"
  23072. "Upgrade: websocket\r\n"
  23073. "Connection: Upgrade\r\n"
  23074. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23075. "Sec-WebSocket-Version: 13\r\n"
  23076. "\r\n";
  23077. std::string res;
  23078. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23079. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  23080. static_cast<int>(req.size())) {
  23081. char c;
  23082. while (res.find("\r\n\r\n") == std::string::npos &&
  23083. ::recv(sock, &c, 1, 0) == 1) {
  23084. res += c;
  23085. }
  23086. }
  23087. if (res.find(" 101 ") == std::string::npos) {
  23088. detail::close_socket(sock);
  23089. return INVALID_SOCKET;
  23090. }
  23091. return sock;
  23092. }
  23093. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23094. // The payload must fit the 7-bit length field.
  23095. static std::string masked_frame(uint8_t first_byte,
  23096. const std::string &payload) {
  23097. std::string f;
  23098. f += static_cast<char>(first_byte);
  23099. f += static_cast<char>(0x80 | payload.size());
  23100. f.append(4, '\0');
  23101. return f + payload;
  23102. }
  23103. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23104. std::atomic<bool> done{false};
  23105. std::string received;
  23106. Server svr;
  23107. svr.set_websocket_ping_interval(0);
  23108. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23109. std::string msg;
  23110. if (ws.read(msg) == ws::Binary) { received = msg; }
  23111. done = true;
  23112. });
  23113. auto port = svr.bind_to_any_port("127.0.0.1");
  23114. std::thread t([&]() { svr.listen_after_bind(); });
  23115. auto se = detail::scope_exit([&] {
  23116. svr.stop();
  23117. t.join();
  23118. });
  23119. svr.wait_until_ready();
  23120. auto sock = connect_raw_websocket(port, "/ws");
  23121. ASSERT_NE(INVALID_SOCKET, sock);
  23122. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23123. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23124. masked_frame(0x89, "p") + // FIN + Ping
  23125. masked_frame(0x80, "lo"); // FIN + Continuation
  23126. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23127. for (int i = 0; i < 500 && !done; i++) {
  23128. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23129. }
  23130. ASSERT_TRUE(done);
  23131. EXPECT_EQ("Hello", received);
  23132. // The Ping between the fragments is answered with a Pong.
  23133. char pong[3];
  23134. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23135. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23136. }
  23137. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23138. Server svr;
  23139. svr.set_websocket_ping_interval(-1);
  23140. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23141. std::string msg;
  23142. while (ws.read(msg)) {}
  23143. });
  23144. auto port = svr.bind_to_any_port("127.0.0.1");
  23145. std::thread t([&]() { svr.listen_after_bind(); });
  23146. auto se = detail::scope_exit([&] {
  23147. svr.stop();
  23148. t.join();
  23149. });
  23150. svr.wait_until_ready();
  23151. auto sock = connect_raw_websocket(port, "/ws");
  23152. ASSERT_NE(INVALID_SOCKET, sock);
  23153. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23154. // Nothing comes while the client stays quiet.
  23155. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23156. char c;
  23157. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23158. }
  23159. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23160. Server svr;
  23161. svr.set_websocket_ping_interval(0);
  23162. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23163. std::string msg;
  23164. while (ws.read(msg)) {}
  23165. });
  23166. auto port = svr.bind_to_any_port("127.0.0.1");
  23167. std::thread t([&]() { svr.listen_after_bind(); });
  23168. auto se = detail::scope_exit([&] {
  23169. svr.stop();
  23170. t.join();
  23171. });
  23172. svr.wait_until_ready();
  23173. // Each Close payload and the reply it should get: an echo when valid, 1002
  23174. // otherwise.
  23175. std::vector<std::pair<std::string, std::string>> cases = {
  23176. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23177. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23178. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23179. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23180. };
  23181. // Also between the fragments of a message.
  23182. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23183. for (const auto &c : cases) {
  23184. auto sock = connect_raw_websocket(port, "/ws");
  23185. ASSERT_NE(INVALID_SOCKET, sock);
  23186. auto frames = prefix + masked_frame(0x88, c.first);
  23187. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23188. std::string reply;
  23189. char buf[256];
  23190. while (reply.size() < 2 + c.second.size()) {
  23191. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23192. if (n <= 0) { break; }
  23193. reply.append(buf, static_cast<size_t>(n));
  23194. }
  23195. detail::close_socket(sock);
  23196. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23197. c.second,
  23198. reply);
  23199. }
  23200. }
  23201. }
  23202. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23203. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23204. protected:
  23205. void SetUp() override {
  23206. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23207. SERVER_PRIVATE_KEY_FILE);
  23208. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23209. std::string msg;
  23210. ws::ReadResult ret;
  23211. while ((ret = ws.read(msg))) {
  23212. if (ret == ws::Binary) {
  23213. ws.send(msg.data(), msg.size());
  23214. } else {
  23215. ws.send(msg);
  23216. }
  23217. }
  23218. });
  23219. port_ = server_->bind_to_any_port(HOST);
  23220. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23221. server_->wait_until_ready();
  23222. }
  23223. void TearDown() override {
  23224. server_->stop();
  23225. if (server_thread_.joinable()) { server_thread_.join(); }
  23226. }
  23227. std::unique_ptr<SSLServer> server_;
  23228. std::thread server_thread_;
  23229. int port_ = 0;
  23230. };
  23231. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23232. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23233. {
  23234. ws::WebSocketClient client(url);
  23235. client.enable_server_certificate_verification(false);
  23236. auto calls = 0;
  23237. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23238. calls++;
  23239. return false;
  23240. });
  23241. EXPECT_FALSE(client.connect());
  23242. EXPECT_GT(calls, 0);
  23243. }
  23244. {
  23245. ws::WebSocketClient client(url);
  23246. client.enable_server_certificate_verification(false);
  23247. client.set_session_verifier([](tls::session_t) {
  23248. return SSLVerifierResponse::CertificateRejected;
  23249. });
  23250. EXPECT_FALSE(client.connect());
  23251. }
  23252. {
  23253. ws::WebSocketClient client(url);
  23254. client.enable_server_certificate_verification(false);
  23255. client.set_session_verifier([](tls::session_t) {
  23256. return SSLVerifierResponse::CertificateAccepted;
  23257. });
  23258. EXPECT_TRUE(client.connect());
  23259. }
  23260. }
  23261. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23262. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23263. "/ws-echo");
  23264. client.enable_server_certificate_verification(false);
  23265. ASSERT_TRUE(client.connect());
  23266. ASSERT_TRUE(client.is_open());
  23267. ASSERT_TRUE(client.send("Hello WSS"));
  23268. std::string msg;
  23269. EXPECT_EQ(ws::Text, client.read(msg));
  23270. EXPECT_EQ("Hello WSS", msg);
  23271. client.close();
  23272. }
  23273. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23274. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23275. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23276. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23277. // client (without calling close() first) is the only path that runs
  23278. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23279. // bug exactly.
  23280. //
  23281. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23282. // when linked against an instrumented libssl; run under Valgrind to catch it
  23283. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23284. // suite (the freed session otherwise stalls on the close handshake) — this test
  23285. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23286. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23287. {
  23288. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23289. "/ws-echo");
  23290. client.enable_server_certificate_verification(false);
  23291. client.set_read_timeout(2, 0);
  23292. client.set_write_timeout(2, 0);
  23293. ASSERT_TRUE(client.connect());
  23294. ASSERT_TRUE(client.is_open());
  23295. ASSERT_TRUE(client.send("still open"));
  23296. // Intentionally do NOT call client.close(): leaving scope runs
  23297. // shutdown_and_close() with the WebSocket still open, which must send the
  23298. // close frame while the TLS session is still alive.
  23299. }
  23300. }
  23301. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23302. // shutdown_and_close() at the start of connect(), reproducing the same
  23303. // use-after-free within the test body rather than at scope exit. The second
  23304. // connect must succeed and echo, proving the close handshake ran over a live
  23305. // session. See the note above about memory-tool requirements.
  23306. TEST_F(WebSocketSSLIntegrationTest,
  23307. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23308. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23309. "/ws-echo");
  23310. client.enable_server_certificate_verification(false);
  23311. client.set_read_timeout(2, 0);
  23312. client.set_write_timeout(2, 0);
  23313. ASSERT_TRUE(client.connect());
  23314. ASSERT_TRUE(client.is_open());
  23315. ASSERT_TRUE(client.send("still open"));
  23316. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23317. // the still-open connection, which must not touch a freed TLS session.
  23318. ASSERT_TRUE(client.connect());
  23319. ASSERT_TRUE(client.is_open());
  23320. ASSERT_TRUE(client.send("after reconnect"));
  23321. std::string msg;
  23322. EXPECT_EQ(ws::Text, client.read(msg));
  23323. EXPECT_EQ("after reconnect", msg);
  23324. client.close();
  23325. }
  23326. #endif
  23327. #ifdef CPPHTTPLIB_SSL_ENABLED
  23328. class WebSocketSSLCATest : public ::testing::Test {
  23329. protected:
  23330. void SetUp() override {
  23331. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23332. SERVER_PRIVATE_KEY_FILE);
  23333. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23334. std::string msg;
  23335. while (ws.read(msg)) {
  23336. ws.send(msg);
  23337. }
  23338. });
  23339. port_ = server_->bind_to_any_port("127.0.0.1");
  23340. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23341. server_->wait_until_ready();
  23342. }
  23343. void TearDown() override {
  23344. server_->stop();
  23345. if (server_thread_.joinable()) { server_thread_.join(); }
  23346. }
  23347. std::string url() const {
  23348. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23349. }
  23350. std::unique_ptr<SSLServer> server_;
  23351. std::thread server_thread_;
  23352. int port_ = 0;
  23353. };
  23354. // A custom CA loaded as PEM verifies the server with full certificate
  23355. // verification enabled
  23356. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23357. ws::WebSocketClient client(url());
  23358. std::string cert;
  23359. read_file(SERVER_CERT2_FILE, cert);
  23360. client.load_ca_cert_store(cert.c_str(), cert.size());
  23361. ASSERT_TRUE(client.connect());
  23362. ASSERT_TRUE(client.send("hello"));
  23363. std::string msg;
  23364. EXPECT_EQ(ws::Text, client.read(msg));
  23365. EXPECT_EQ("hello", msg);
  23366. client.close();
  23367. }
  23368. // A custom CA that does not cover the server must fail verification (the
  23369. // custom CA is exclusive; system certs are not loaded alongside it)
  23370. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23371. ws::WebSocketClient client(url());
  23372. std::string cert;
  23373. read_file(CLIENT_CA_CERT_FILE, cert);
  23374. client.load_ca_cert_store(cert.c_str(), cert.size());
  23375. auto res = client.connect();
  23376. ASSERT_FALSE(res);
  23377. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23378. EXPECT_EQ(-1, res.status());
  23379. EXPECT_NE(0u, res.ssl_backend_error());
  23380. }
  23381. // The same CA as a file path rather than PEM in memory
  23382. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23383. ws::WebSocketClient client(url());
  23384. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23385. ASSERT_TRUE(client.connect());
  23386. ASSERT_TRUE(client.send("hello"));
  23387. std::string msg;
  23388. EXPECT_EQ(ws::Text, client.read(msg));
  23389. EXPECT_EQ("hello", msg);
  23390. client.close();
  23391. }
  23392. // ...and a CA file that does not cover the server still fails, so it is the
  23393. // path above that decides the outcome
  23394. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23395. ws::WebSocketClient client(url());
  23396. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23397. ASSERT_FALSE(client.connect());
  23398. }
  23399. // Regression test: reconnecting with a native custom CA store used to reuse
  23400. // a store handle the previous TLS context had already freed (use-after-free
  23401. // under the OpenSSL backend). The context now lives as long as the client.
  23402. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23403. ws::WebSocketClient client(url());
  23404. std::string cert;
  23405. read_file(SERVER_CERT2_FILE, cert);
  23406. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23407. ASSERT_TRUE(client.connect());
  23408. client.close();
  23409. ASSERT_TRUE(client.connect());
  23410. ASSERT_TRUE(client.send("again"));
  23411. std::string msg;
  23412. EXPECT_EQ(ws::Text, client.read(msg));
  23413. EXPECT_EQ("again", msg);
  23414. client.close();
  23415. }
  23416. // Regression test: a certificate with a trusted chain but no identity match
  23417. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23418. // verification entirely for IP hosts, so this connection succeeded there.
  23419. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23420. // chain verification while the identity check must still fail.
  23421. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23422. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23423. ASSERT_TRUE(svr.is_valid());
  23424. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23425. std::string msg;
  23426. while (ws.read(msg)) {
  23427. ws.send(msg);
  23428. }
  23429. });
  23430. auto port = svr.bind_to_any_port("127.0.0.1");
  23431. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23432. auto se = detail::scope_exit([&] {
  23433. svr.stop();
  23434. t.join();
  23435. });
  23436. svr.wait_until_ready();
  23437. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23438. "/echo");
  23439. std::string cert;
  23440. read_file(SERVER_CERT_FILE, cert);
  23441. client.load_ca_cert_store(cert.c_str(), cert.size());
  23442. ASSERT_FALSE(client.connect());
  23443. }
  23444. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23445. // SNI, so nothing binds the host name to the TLS session. These bind the
  23446. // server to "localhost" instead, the only shape that exercises the SNI and
  23447. // hostname-verification path with certificate verification left enabled.
  23448. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23449. protected:
  23450. void Start(const char *cert_file) {
  23451. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23452. SERVER_PRIVATE_KEY_FILE);
  23453. ASSERT_TRUE(server_->is_valid());
  23454. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23455. std::string msg;
  23456. while (ws.read(msg)) {
  23457. ws.send(msg);
  23458. }
  23459. });
  23460. port_ = server_->bind_to_any_port("localhost");
  23461. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23462. server_->wait_until_ready();
  23463. }
  23464. void TearDown() override {
  23465. if (server_) { server_->stop(); }
  23466. if (server_thread_.joinable()) { server_thread_.join(); }
  23467. }
  23468. std::string url() const {
  23469. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23470. }
  23471. std::unique_ptr<SSLServer> server_;
  23472. std::thread server_thread_;
  23473. int port_ = 0;
  23474. };
  23475. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23476. // out and the connection is usable
  23477. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23478. Start(SERVER_CERT2_FILE);
  23479. ws::WebSocketClient client(url());
  23480. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23481. ASSERT_TRUE(client.connect());
  23482. ASSERT_TRUE(client.send("hello"));
  23483. std::string msg;
  23484. EXPECT_EQ(ws::Text, client.read(msg));
  23485. EXPECT_EQ("hello", msg);
  23486. client.close();
  23487. }
  23488. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23489. // while the identity check must still reject "localhost"
  23490. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23491. Start(SERVER_CERT_FILE);
  23492. ws::WebSocketClient client(url());
  23493. client.set_ca_cert_path(SERVER_CERT_FILE);
  23494. auto res = client.connect();
  23495. ASSERT_FALSE(res);
  23496. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23497. EXPECT_EQ(-1, res.status());
  23498. }
  23499. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23500. // disabled: the chain is still checked, only the identity check is skipped
  23501. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23502. Start(SERVER_CERT_FILE);
  23503. ws::WebSocketClient client(url());
  23504. client.set_ca_cert_path(SERVER_CERT_FILE);
  23505. client.enable_server_hostname_verification(false);
  23506. ASSERT_TRUE(client.connect());
  23507. ASSERT_TRUE(client.send("hello"));
  23508. std::string msg;
  23509. EXPECT_EQ(ws::Text, client.read(msg));
  23510. EXPECT_EQ("hello", msg);
  23511. client.close();
  23512. }
  23513. // A CA that did not sign the server certificate fails the chain, even though
  23514. // the name would match
  23515. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23516. Start(SERVER_CERT2_FILE);
  23517. ws::WebSocketClient client(url());
  23518. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23519. ASSERT_FALSE(client.connect());
  23520. }
  23521. // With verification disabled, neither the chain nor the name is checked
  23522. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23523. Start(SERVER_CERT_FILE);
  23524. ws::WebSocketClient client(url());
  23525. client.enable_server_certificate_verification(false);
  23526. ASSERT_TRUE(client.connect());
  23527. ASSERT_TRUE(client.send("hello"));
  23528. std::string msg;
  23529. EXPECT_EQ(ws::Text, client.read(msg));
  23530. EXPECT_EQ("hello", msg);
  23531. client.close();
  23532. }
  23533. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23534. protected:
  23535. void SetUp() override {
  23536. server_ = httplib::detail::make_unique<SSLServer>(
  23537. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23538. ASSERT_TRUE(server_->is_valid());
  23539. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23540. std::string msg;
  23541. while (ws.read(msg)) {
  23542. ws.send(msg);
  23543. }
  23544. });
  23545. port_ = server_->bind_to_any_port("localhost");
  23546. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23547. server_->wait_until_ready();
  23548. }
  23549. void TearDown() override {
  23550. server_->stop();
  23551. if (server_thread_.joinable()) { server_thread_.join(); }
  23552. }
  23553. std::string url() const {
  23554. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23555. }
  23556. void ConnectWithClientCert(const std::string &client_cert_file,
  23557. const std::string &client_private_key_file,
  23558. const char *private_key_password) {
  23559. std::string cert_pem, key_pem;
  23560. read_file(client_cert_file, cert_pem);
  23561. read_file(client_private_key_file, key_pem);
  23562. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23563. key_pem.c_str(), key_pem.size(),
  23564. private_key_password};
  23565. ws::WebSocketClient client(url(), pem);
  23566. ASSERT_TRUE(client.is_valid());
  23567. client.enable_server_certificate_verification(false);
  23568. ASSERT_TRUE(client.connect());
  23569. ASSERT_TRUE(client.send("hello"));
  23570. std::string msg;
  23571. EXPECT_EQ(ws::Text, client.read(msg));
  23572. EXPECT_EQ("hello", msg);
  23573. client.close();
  23574. }
  23575. std::unique_ptr<SSLServer> server_;
  23576. std::thread server_thread_;
  23577. int port_ = 0;
  23578. };
  23579. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23580. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23581. }
  23582. // Control for the tests above: the fixture's server really does require a
  23583. // client certificate, so it is the PEM the constructor installed that decides
  23584. // the outcome.
  23585. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23586. ws::WebSocketClient client(url());
  23587. ASSERT_TRUE(client.is_valid());
  23588. client.enable_server_certificate_verification(false);
  23589. EXPECT_FALSE(client.connect());
  23590. }
  23591. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23592. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23593. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23594. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23595. }
  23596. #endif
  23597. #if !defined(_WIN32)
  23598. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23599. auto secret_dir = std::string("./symlink_test_secret");
  23600. auto served_dir = std::string("./symlink_test_served");
  23601. auto secret_file = secret_dir + "/secret.txt";
  23602. auto symlink_path = served_dir + "/escape";
  23603. // Setup: create directories and files
  23604. mkdir(secret_dir.c_str(), 0755);
  23605. mkdir(served_dir.c_str(), 0755);
  23606. {
  23607. std::ofstream ofs(secret_file);
  23608. ofs << "SECRET_DATA";
  23609. }
  23610. // Create symlink using absolute path so it resolves correctly
  23611. #ifdef PATH_MAX
  23612. char abs_secret[PATH_MAX];
  23613. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23614. #else
  23615. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23616. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23617. ASSERT_NE(nullptr, abs_secret);
  23618. #endif
  23619. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23620. auto se = detail::scope_exit([&] {
  23621. unlink(symlink_path.c_str());
  23622. unlink(secret_file.c_str());
  23623. rmdir(served_dir.c_str());
  23624. rmdir(secret_dir.c_str());
  23625. });
  23626. Server svr;
  23627. svr.set_mount_point("/", served_dir);
  23628. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23629. auto se2 = detail::scope_exit([&] {
  23630. svr.stop();
  23631. listen_thread.join();
  23632. });
  23633. svr.wait_until_ready();
  23634. Client cli("localhost", PORT);
  23635. // Symlink pointing outside base dir should be blocked
  23636. auto res = cli.Get("/escape/secret.txt");
  23637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23638. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23639. }
  23640. #endif
  23641. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23642. // "GET /smuggled" request), reads the first response, and only then sends the
  23643. // embedded request as the body. Returns how many times /smuggled ran.
  23644. //
  23645. // The body is sent AFTER receiving the first response (as in the original
  23646. // PoC) so that the stream_line_reader cannot buffer it together with the
  23647. // headers of the first request.
  23648. static int count_smuggled_requests(const std::string &outer_head,
  23649. std::string &first_response) {
  23650. Server svr;
  23651. svr.set_mount_point("/", "./www");
  23652. std::atomic<int> smuggled_count(0);
  23653. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23654. smuggled_count++;
  23655. res.set_content("oops", "text/plain");
  23656. });
  23657. svr.Post("/post", [&](const Request &req, Response &res) {
  23658. res.set_content(req.body, "text/plain");
  23659. });
  23660. auto port = svr.bind_to_any_port("localhost");
  23661. thread t = thread([&] { svr.listen_after_bind(); });
  23662. auto se = detail::scope_exit([&] {
  23663. svr.stop();
  23664. t.join();
  23665. });
  23666. svr.wait_until_ready();
  23667. auto error = Error::Success;
  23668. auto sock = detail::create_client_socket(
  23669. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23670. /*connection_timeout_sec=*/2, 0,
  23671. /*read_timeout_sec=*/2, 0,
  23672. /*write_timeout_sec=*/2, 0, std::string(), error);
  23673. EXPECT_NE(INVALID_SOCKET, sock);
  23674. if (sock == INVALID_SOCKET) { return -1; }
  23675. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23676. // The "smuggled" request will be sent as the body of the outer request
  23677. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23678. "Host: localhost\r\n"
  23679. "Connection: close\r\n"
  23680. "\r\n";
  23681. auto head = outer_head;
  23682. auto len = std::to_string(smuggled.size());
  23683. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23684. pos = head.find("{len}", pos + len.size())) {
  23685. head.replace(pos, 5, len);
  23686. }
  23687. // Step 1: Send only the outer request headers (no body yet)
  23688. auto sent = send(sock, head.data(), head.size(), 0);
  23689. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23690. // Step 2: Read the first response
  23691. char buf[4096];
  23692. for (;;) {
  23693. auto n = recv(sock, buf, sizeof(buf), 0);
  23694. if (n <= 0) break;
  23695. first_response.append(buf, static_cast<size_t>(n));
  23696. // Stop once we have a complete response (headers + body)
  23697. auto hdr_end = first_response.find("\r\n\r\n");
  23698. if (hdr_end != std::string::npos) {
  23699. // Check for Content-Length to know when the body is complete
  23700. auto cl_pos = first_response.find("Content-Length:");
  23701. if (cl_pos != std::string::npos) {
  23702. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23703. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23704. auto cl = std::stoul(
  23705. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23706. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23707. } else {
  23708. break; // No Content-Length, assume headers-only response
  23709. }
  23710. }
  23711. }
  23712. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23713. // vulnerable server the keep-alive loop reads this as a second request. The
  23714. // server may already have closed the connection, so the result is ignored.
  23715. send(sock, smuggled.data(), smuggled.size(), 0);
  23716. // Half-close so that a server which drained the body sees EOF and closes,
  23717. // instead of the read below waiting for the read timeout.
  23718. #ifdef _WIN32
  23719. ::shutdown(sock, SD_SEND);
  23720. #else
  23721. ::shutdown(sock, SHUT_WR);
  23722. #endif
  23723. // Step 4: Read until the server closes the connection
  23724. for (;;) {
  23725. auto n = recv(sock, buf, sizeof(buf), 0);
  23726. if (n <= 0) break;
  23727. }
  23728. return smuggled_count.load();
  23729. }
  23730. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23731. // A GET request with Content-Length to a static file handler must have its
  23732. // body drained before the keep-alive connection is reused. Otherwise the
  23733. // unread body bytes are interpreted as the next HTTP request.
  23734. std::string first_response;
  23735. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23736. "Host: localhost\r\n"
  23737. "Content-Length: {len}\r\n"
  23738. "\r\n",
  23739. first_response));
  23740. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23741. }
  23742. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23743. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23744. // be answered with 400 and the connection closed. Treating it as "no body"
  23745. // leaves the body to be parsed as the next request.
  23746. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23747. const char *targets[] = {
  23748. "GET /file", // handler that never reads the body
  23749. "GET /not-found", // no handler matches (404)
  23750. "POST /post", // handler that reads the body
  23751. };
  23752. for (auto target : targets) {
  23753. for (auto value : values) {
  23754. std::string first_response;
  23755. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23756. " HTTP/1.1\r\n"
  23757. "Host: localhost\r\n"
  23758. "Content-Length: " +
  23759. value + "\r\n\r\n",
  23760. first_response))
  23761. << target << " with Content-Length: " << value;
  23762. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23763. << target << " with Content-Length: " << value;
  23764. }
  23765. }
  23766. }
  23767. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23768. // A 400 for an unparseable request line leaves the rest of the message
  23769. // unread, so the connection must be closed rather than reused.
  23770. std::string first_response;
  23771. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23772. "Host: localhost\r\n"
  23773. "Content-Length: {len}\r\n"
  23774. "\r\n",
  23775. first_response));
  23776. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23777. }
  23778. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23779. // Same as above for a header block that fails to parse.
  23780. std::string first_response;
  23781. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23782. "Host: localhost\r\n"
  23783. "Bad Header\r\n"
  23784. "Content-Length: {len}\r\n"
  23785. "\r\n",
  23786. first_response));
  23787. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23788. }
  23789. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23790. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23791. // server must not read another request on that connection, even when the
  23792. // request had no body to drain.
  23793. std::string first_response;
  23794. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23795. "Host: localhost\r\n"
  23796. "\r\n",
  23797. first_response));
  23798. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23799. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23800. }
  23801. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23802. // A content reader that stops early leaves the stream inside the body.
  23803. // Draining the whole Content-Length from there, or reading the body again,
  23804. // reads into the next request, and whatever follows is parsed as a request
  23805. // of its own.
  23806. Server svr;
  23807. std::atomic<int> smuggled_count(0);
  23808. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23809. svr.Post("/upload", [](const Request &req, Response &res,
  23810. const ContentReader &content_reader) {
  23811. // Stop at the last chunk, so the whole body has been read however it
  23812. // arrives.
  23813. auto length = req.get_header_value_u64("Content-Length");
  23814. size_t total = 0;
  23815. auto consumed = content_reader([&](const char *, size_t n) {
  23816. total += n;
  23817. return total < length;
  23818. });
  23819. EXPECT_FALSE(consumed);
  23820. if (req.has_param("retry")) {
  23821. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23822. }
  23823. // Replace the 400 the aborted read set, which would close the connection.
  23824. res.set_redirect("/done");
  23825. });
  23826. auto port = svr.bind_to_any_port(HOST);
  23827. thread t = thread([&] { svr.listen_after_bind(); });
  23828. auto se = detail::scope_exit([&] {
  23829. svr.stop();
  23830. t.join();
  23831. });
  23832. svr.wait_until_ready();
  23833. // A front end sees the second request as a POST whose body is the GET. The
  23834. // first body is as long as the POST's headers, so draining it again reads
  23835. // exactly those and leaves the GET to be parsed next.
  23836. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23837. "Host: localhost\r\n"
  23838. "\r\n";
  23839. std::string second_head = "POST /post HTTP/1.1\r\n"
  23840. "Host: localhost\r\n"
  23841. "Content-Length: " +
  23842. std::to_string(inner.size()) +
  23843. "\r\n"
  23844. "\r\n";
  23845. for (auto target : {"/upload", "/upload?retry"}) {
  23846. smuggled_count = 0;
  23847. std::string request = "POST " + std::string(target) +
  23848. " HTTP/1.1\r\n"
  23849. "Host: localhost\r\n"
  23850. "Content-Length: " +
  23851. std::to_string(second_head.size()) +
  23852. "\r\n"
  23853. "\r\n" +
  23854. std::string(second_head.size(), 'A') + second_head +
  23855. inner;
  23856. std::string response;
  23857. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23858. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23859. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23860. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23861. EXPECT_EQ(0, smuggled_count.load()) << target;
  23862. }
  23863. }
  23864. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23865. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23866. // must be rejected with 400 Bad Request.
  23867. Server svr;
  23868. svr.Post("/test", [&](const Request &, Response &res) {
  23869. res.set_content("ok", "text/plain");
  23870. });
  23871. thread t = thread([&] { svr.listen(HOST, PORT); });
  23872. auto se = detail::scope_exit([&] {
  23873. svr.stop();
  23874. t.join();
  23875. ASSERT_FALSE(svr.is_running());
  23876. });
  23877. svr.wait_until_ready();
  23878. // Exact "chunked"
  23879. {
  23880. auto req = "POST /test HTTP/1.1\r\n"
  23881. "Host: localhost\r\n"
  23882. "Content-Length: 5\r\n"
  23883. "Transfer-Encoding: chunked\r\n"
  23884. "Connection: close\r\n"
  23885. "\r\n"
  23886. "hello";
  23887. std::string response;
  23888. ASSERT_TRUE(send_request(1, req, &response));
  23889. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23890. response.substr(0, response.find("\r\n")));
  23891. }
  23892. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23893. {
  23894. auto req = "POST /test HTTP/1.1\r\n"
  23895. "Host: localhost\r\n"
  23896. "Content-Length: 5\r\n"
  23897. "Transfer-Encoding: gzip, chunked\r\n"
  23898. "Connection: close\r\n"
  23899. "\r\n"
  23900. "hello";
  23901. std::string response;
  23902. ASSERT_TRUE(send_request(1, req, &response));
  23903. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23904. response.substr(0, response.find("\r\n")));
  23905. }
  23906. }
  23907. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23908. Server svr;
  23909. svr.Post("/test", [&](const Request &, Response &res) {
  23910. res.set_content("ok", "text/plain");
  23911. });
  23912. thread t = thread([&] { svr.listen(HOST, PORT); });
  23913. auto se = detail::scope_exit([&] {
  23914. svr.stop();
  23915. t.join();
  23916. ASSERT_FALSE(svr.is_running());
  23917. });
  23918. svr.wait_until_ready();
  23919. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23920. // length cannot be determined, so the server must answer 400 and close
  23921. // rather than treat the request as bodyless and leave the body in the
  23922. // socket for the next request to pick up.
  23923. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23924. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23925. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23926. std::string response;
  23927. ASSERT_TRUE(send_request(1, req, &response));
  23928. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23929. response.substr(0, response.find("\r\n")))
  23930. << transfer_encoding;
  23931. }
  23932. // RFC 9110 5.3: the codings may also be split across several
  23933. // Transfer-Encoding lines, which combine in the order they were received.
  23934. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23935. // just like the single-line "chunked, gzip" above.
  23936. {
  23937. auto req = "POST /test HTTP/1.1\r\n"
  23938. "Host: localhost\r\n"
  23939. "Transfer-Encoding: chunked\r\n"
  23940. "Transfer-Encoding: gzip\r\n"
  23941. "\r\n"
  23942. "0\r\n\r\n";
  23943. std::string response;
  23944. ASSERT_TRUE(send_request(1, req, &response));
  23945. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23946. response.substr(0, response.find("\r\n")));
  23947. }
  23948. // A sequence ending in chunked stays valid.
  23949. auto req = "POST /test HTTP/1.1\r\n"
  23950. "Host: localhost\r\n"
  23951. "Transfer-Encoding: gzip, chunked\r\n"
  23952. "Connection: close\r\n"
  23953. "\r\n"
  23954. "0\r\n\r\n";
  23955. std::string response;
  23956. ASSERT_TRUE(send_request(1, req, &response));
  23957. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23958. // ...including when it is spread over several lines.
  23959. auto split_req = "POST /test HTTP/1.1\r\n"
  23960. "Host: localhost\r\n"
  23961. "Transfer-Encoding: gzip\r\n"
  23962. "Transfer-Encoding: chunked\r\n"
  23963. "Connection: close\r\n"
  23964. "\r\n"
  23965. "0\r\n\r\n";
  23966. std::string split_response;
  23967. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23968. EXPECT_EQ("HTTP/1.1 200 OK",
  23969. split_response.substr(0, split_response.find("\r\n")));
  23970. }
  23971. // Regression for issue #2450: a DELETE without Content-Length on a
  23972. // keep-alive connection must not let the post-response drain consume the
  23973. // next request's bytes.
  23974. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23975. Server svr;
  23976. std::atomic<int> delete_count(0);
  23977. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23978. delete_count++;
  23979. res.status = StatusCode::NoContent_204;
  23980. });
  23981. auto port = svr.bind_to_any_port(HOST);
  23982. thread t = thread([&] { svr.listen_after_bind(); });
  23983. auto se = detail::scope_exit([&] {
  23984. svr.stop();
  23985. t.join();
  23986. });
  23987. svr.wait_until_ready();
  23988. auto error = Error::Success;
  23989. auto sock = detail::create_client_socket(
  23990. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23991. /*connection_timeout_sec=*/2, 0,
  23992. /*read_timeout_sec=*/2, 0,
  23993. /*write_timeout_sec=*/2, 0, std::string(), error);
  23994. ASSERT_NE(INVALID_SOCKET, sock);
  23995. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23996. auto send_request_and_read_response = [&](const std::string &req,
  23997. std::string &out) -> bool {
  23998. auto sent = send(sock, req.data(), req.size(), 0);
  23999. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  24000. char buf[4096];
  24001. for (;;) {
  24002. auto n = recv(sock, buf, sizeof(buf), 0);
  24003. if (n <= 0) { return !out.empty(); }
  24004. out.append(buf, static_cast<size_t>(n));
  24005. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  24006. }
  24007. };
  24008. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  24009. "Host: localhost\r\n"
  24010. "\r\n";
  24011. std::string resp1;
  24012. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  24013. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  24014. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  24015. "Host: localhost\r\n"
  24016. "Connection: close\r\n"
  24017. "\r\n";
  24018. std::string resp2;
  24019. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  24020. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  24021. EXPECT_EQ(2, delete_count.load());
  24022. }
  24023. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  24024. Server svr;
  24025. svr.Post("/ingest", [&](const Request &, Response &res,
  24026. const ContentReader &content_reader) {
  24027. auto consumed = content_reader([](const char *, size_t) { return false; });
  24028. EXPECT_FALSE(consumed);
  24029. res.status = StatusCode::Conflict_409;
  24030. res.set_header("Connection", "close");
  24031. });
  24032. auto port = svr.bind_to_any_port(HOST);
  24033. thread t = thread([&] { svr.listen_after_bind(); });
  24034. auto se = detail::scope_exit([&] {
  24035. svr.stop();
  24036. t.join();
  24037. });
  24038. svr.wait_until_ready();
  24039. auto error = Error::Success;
  24040. auto sock = detail::create_client_socket(
  24041. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24042. /*connection_timeout_sec=*/2, 0,
  24043. /*read_timeout_sec=*/1, 0,
  24044. /*write_timeout_sec=*/2, 0, std::string(), error);
  24045. ASSERT_NE(INVALID_SOCKET, sock);
  24046. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24047. std::string request = "POST /ingest HTTP/1.1\r\n"
  24048. "Host: localhost\r\n"
  24049. "Transfer-Encoding: chunked\r\n"
  24050. "\r\n"
  24051. "4\r\n"
  24052. "data\r\n";
  24053. auto sent = send(sock, request.data(), request.size(), 0);
  24054. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24055. std::string response;
  24056. ssize_t received = 0;
  24057. do {
  24058. char buf[4096];
  24059. received = recv(sock, buf, sizeof(buf), 0);
  24060. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24061. } while (received > 0);
  24062. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24063. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24064. EXPECT_EQ(0, received);
  24065. }
  24066. namespace no_proxy_test {
  24067. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24068. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24069. // calling listen().
  24070. class ScopedServer {
  24071. public:
  24072. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24073. ~ScopedServer() {
  24074. svr_.stop();
  24075. if (th_.joinable()) { th_.join(); }
  24076. }
  24077. Server &svr() { return svr_; }
  24078. int port() const { return port_; }
  24079. void listen() {
  24080. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24081. svr_.wait_until_ready();
  24082. }
  24083. private:
  24084. Server svr_;
  24085. std::thread th_;
  24086. int port_ = 0;
  24087. };
  24088. class ProxyAndTargetServers {
  24089. public:
  24090. ProxyAndTargetServers() {
  24091. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24092. proxy_hits_++;
  24093. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24094. res.set_content("via-proxy", "text/plain");
  24095. });
  24096. target_.Get(".*", [this](const Request &req, Response &res) {
  24097. target_hits_++;
  24098. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24099. res.set_content("direct", "text/plain");
  24100. });
  24101. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24102. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24103. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24104. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24105. proxy_mock_.wait_until_ready();
  24106. target_.wait_until_ready();
  24107. }
  24108. ~ProxyAndTargetServers() {
  24109. proxy_mock_.stop();
  24110. target_.stop();
  24111. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24112. if (target_thread_.joinable()) { target_thread_.join(); }
  24113. }
  24114. Server &proxy_mock() { return proxy_mock_; }
  24115. Server &target() { return target_; }
  24116. int proxy_port() const { return proxy_port_; }
  24117. int target_port() const { return target_port_; }
  24118. int proxy_hits() const { return proxy_hits_.load(); }
  24119. int target_hits() const { return target_hits_.load(); }
  24120. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24121. void reset_counters() {
  24122. proxy_hits_ = 0;
  24123. target_hits_ = 0;
  24124. last_had_proxy_authz_ = false;
  24125. }
  24126. private:
  24127. Server proxy_mock_;
  24128. Server target_;
  24129. std::thread proxy_thread_;
  24130. std::thread target_thread_;
  24131. int proxy_port_ = 0;
  24132. int target_port_ = 0;
  24133. std::atomic<int> proxy_hits_{0};
  24134. std::atomic<int> target_hits_{0};
  24135. std::atomic<bool> last_had_proxy_authz_{false};
  24136. };
  24137. inline std::unique_ptr<Client> make_client(const std::string &host,
  24138. ProxyAndTargetServers &s) {
  24139. auto cli = detail::make_unique<Client>(host, s.target_port());
  24140. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24141. cli->set_proxy("127.0.0.1", s.proxy_port());
  24142. return cli;
  24143. }
  24144. } // namespace no_proxy_test
  24145. using no_proxy_test::make_client;
  24146. using no_proxy_test::ProxyAndTargetServers;
  24147. TEST(NoProxyTest, ExactHostnameBypasses) {
  24148. ProxyAndTargetServers s;
  24149. auto cli = make_client("example.com", s);
  24150. cli->set_no_proxy({"example.com"});
  24151. auto res = cli->Get("/");
  24152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24153. EXPECT_EQ(0, s.proxy_hits());
  24154. EXPECT_EQ(1, s.target_hits());
  24155. }
  24156. TEST(NoProxyTest, SubdomainBypasses) {
  24157. ProxyAndTargetServers s;
  24158. auto cli = make_client("foo.example.com", s);
  24159. cli->set_no_proxy({"example.com"});
  24160. auto res = cli->Get("/");
  24161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24162. EXPECT_EQ(0, s.proxy_hits());
  24163. EXPECT_EQ(1, s.target_hits());
  24164. }
  24165. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24166. // Regression guard: "evilexample.com" must not be considered a subdomain
  24167. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24168. // check would let traffic bypass the proxy and leak credentials direct
  24169. // to the attacker host.
  24170. ProxyAndTargetServers s;
  24171. auto cli = make_client("evilexample.com", s);
  24172. cli->set_no_proxy({"example.com"});
  24173. auto res = cli->Get("/");
  24174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24175. EXPECT_GE(s.proxy_hits(), 1);
  24176. EXPECT_EQ(0, s.target_hits());
  24177. }
  24178. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24179. ProxyAndTargetServers s;
  24180. auto cli = make_client("example.com.evil.com", s);
  24181. cli->set_no_proxy({"example.com"});
  24182. auto res = cli->Get("/");
  24183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24184. EXPECT_GE(s.proxy_hits(), 1);
  24185. EXPECT_EQ(0, s.target_hits());
  24186. }
  24187. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24188. ProxyAndTargetServers s;
  24189. auto cli = make_client("example.com", s);
  24190. cli->set_no_proxy({".example.com"});
  24191. auto res = cli->Get("/");
  24192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24193. EXPECT_EQ(0, s.proxy_hits());
  24194. EXPECT_EQ(1, s.target_hits());
  24195. }
  24196. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24197. ProxyAndTargetServers s;
  24198. auto cli = make_client("Example.COM", s);
  24199. cli->set_no_proxy({"EXAMPLE.com"});
  24200. auto res = cli->Get("/");
  24201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24202. EXPECT_EQ(0, s.proxy_hits());
  24203. EXPECT_EQ(1, s.target_hits());
  24204. }
  24205. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24206. ProxyAndTargetServers s;
  24207. auto cli = make_client("example.com.", s);
  24208. cli->set_no_proxy({"example.com"});
  24209. auto res = cli->Get("/");
  24210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24211. EXPECT_EQ(0, s.proxy_hits());
  24212. EXPECT_EQ(1, s.target_hits());
  24213. }
  24214. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24215. // Trailing dots must be normalized on BOTH sides — host and entry.
  24216. // An implementation that only strips the host-side trailing dot would
  24217. // fail to match host "example.com" against entry "example.com." because
  24218. // a literal substring search would compare 11 chars against 12.
  24219. ProxyAndTargetServers s;
  24220. auto cli = make_client("example.com", s);
  24221. cli->set_no_proxy({"example.com."});
  24222. auto res = cli->Get("/");
  24223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24224. EXPECT_EQ(0, s.proxy_hits());
  24225. EXPECT_EQ(1, s.target_hits());
  24226. }
  24227. TEST(NoProxyTest, WildcardBypassesEverything) {
  24228. ProxyAndTargetServers s;
  24229. auto cli = make_client("anything.invalid.test", s);
  24230. cli->set_no_proxy({"*"});
  24231. auto res = cli->Get("/");
  24232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24233. EXPECT_EQ(0, s.proxy_hits());
  24234. EXPECT_EQ(1, s.target_hits());
  24235. }
  24236. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24237. ProxyAndTargetServers s;
  24238. Client cli("127.0.0.1", s.target_port());
  24239. cli.set_proxy("127.0.0.1", s.proxy_port());
  24240. cli.set_no_proxy({"127.0.0.1"});
  24241. auto res = cli.Get("/");
  24242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24243. EXPECT_EQ(0, s.proxy_hits());
  24244. EXPECT_EQ(1, s.target_hits());
  24245. }
  24246. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24247. ProxyAndTargetServers s;
  24248. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24249. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24250. cli.set_proxy("127.0.0.1", s.proxy_port());
  24251. cli.set_no_proxy({"::1"});
  24252. auto res = cli.Get("/");
  24253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24254. EXPECT_EQ(0, s.proxy_hits());
  24255. EXPECT_EQ(1, s.target_hits());
  24256. }
  24257. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24258. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24259. // must still be recognized as IPv6 for CIDR matching. Implementations
  24260. // that detect IPv6 only when the host begins with '[' would parse the
  24261. // host as a hostname and miss the match.
  24262. ProxyAndTargetServers s;
  24263. Client cli("fe80::1", s.target_port());
  24264. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24265. cli.set_proxy("127.0.0.1", s.proxy_port());
  24266. cli.set_no_proxy({"fe80::/10"});
  24267. auto res = cli.Get("/");
  24268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24269. EXPECT_EQ(0, s.proxy_hits());
  24270. EXPECT_EQ(1, s.target_hits());
  24271. }
  24272. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24273. ProxyAndTargetServers s;
  24274. Client cli("::1", s.target_port());
  24275. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24276. cli.set_proxy("127.0.0.1", s.proxy_port());
  24277. cli.set_no_proxy({"[::1]"});
  24278. auto res = cli.Get("/");
  24279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24280. EXPECT_EQ(0, s.proxy_hits());
  24281. EXPECT_EQ(1, s.target_hits());
  24282. }
  24283. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24284. ProxyAndTargetServers s;
  24285. Client cli("fe80::1", s.target_port());
  24286. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24287. cli.set_proxy("127.0.0.1", s.proxy_port());
  24288. cli.set_no_proxy({"[fe80::]/10"});
  24289. auto res = cli.Get("/");
  24290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24291. EXPECT_EQ(0, s.proxy_hits());
  24292. EXPECT_EQ(1, s.target_hits());
  24293. }
  24294. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24295. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24296. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24297. // tricks via address-family conversion.
  24298. ProxyAndTargetServers s;
  24299. Client cli("::ffff:127.0.0.1", s.target_port());
  24300. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24301. cli.set_proxy("127.0.0.1", s.proxy_port());
  24302. cli.set_no_proxy({"127.0.0.1"});
  24303. auto res = cli.Get("/");
  24304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24305. EXPECT_GE(s.proxy_hits(), 1);
  24306. EXPECT_EQ(0, s.target_hits());
  24307. }
  24308. TEST(NoProxyTest, IPv4CidrMatch) {
  24309. ProxyAndTargetServers s;
  24310. Client cli("127.0.0.1", s.target_port());
  24311. cli.set_proxy("127.0.0.1", s.proxy_port());
  24312. cli.set_no_proxy({"127.0.0.0/8"});
  24313. auto res = cli.Get("/");
  24314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24315. EXPECT_EQ(0, s.proxy_hits());
  24316. EXPECT_EQ(1, s.target_hits());
  24317. }
  24318. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24319. ProxyAndTargetServers s;
  24320. Client cli("127.0.0.1", s.target_port());
  24321. cli.set_proxy("127.0.0.1", s.proxy_port());
  24322. cli.set_no_proxy({"10.0.0.0/8"});
  24323. auto res = cli.Get("/");
  24324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24325. EXPECT_GE(s.proxy_hits(), 1);
  24326. EXPECT_EQ(0, s.target_hits());
  24327. }
  24328. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24329. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24330. // IPv4 target matches.
  24331. ProxyAndTargetServers s;
  24332. Client cli("127.0.0.1", s.target_port());
  24333. cli.set_proxy("127.0.0.1", s.proxy_port());
  24334. cli.set_no_proxy({"0.0.0.0/0"});
  24335. auto res = cli.Get("/");
  24336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24337. EXPECT_EQ(0, s.proxy_hits());
  24338. EXPECT_EQ(1, s.target_hits());
  24339. }
  24340. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24341. ProxyAndTargetServers s;
  24342. Client cli("127.0.0.1", s.target_port());
  24343. cli.set_proxy("127.0.0.1", s.proxy_port());
  24344. cli.set_no_proxy({"127.0.0.1"});
  24345. auto res = cli.Get("/");
  24346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24347. EXPECT_EQ(0, s.proxy_hits());
  24348. EXPECT_EQ(1, s.target_hits());
  24349. }
  24350. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24351. ProxyAndTargetServers s;
  24352. Client cli("127.0.0.1", s.target_port());
  24353. cli.set_proxy("127.0.0.1", s.proxy_port());
  24354. cli.set_no_proxy({"127.0.0.0/33"});
  24355. auto res = cli.Get("/");
  24356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24357. EXPECT_GE(s.proxy_hits(), 1);
  24358. EXPECT_EQ(0, s.target_hits());
  24359. }
  24360. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24361. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24362. ProxyAndTargetServers s;
  24363. Client cli("127.0.0.1", s.target_port());
  24364. cli.set_proxy("127.0.0.1", s.proxy_port());
  24365. cli.set_no_proxy({"127.0.0.1/"});
  24366. auto res = cli.Get("/");
  24367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24368. EXPECT_GE(s.proxy_hits(), 1);
  24369. EXPECT_EQ(0, s.target_hits());
  24370. }
  24371. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24372. ProxyAndTargetServers s;
  24373. auto cli = make_client("internal.corp", s);
  24374. cli->set_proxy_basic_auth("u", "p");
  24375. cli->set_no_proxy({"internal.corp"});
  24376. auto res = cli->Get("/");
  24377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24378. EXPECT_EQ(1, s.target_hits());
  24379. EXPECT_EQ(0, s.proxy_hits());
  24380. EXPECT_FALSE(s.last_had_proxy_authz())
  24381. << "Proxy-Authorization must not be sent direct to the target";
  24382. }
  24383. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24384. ProxyAndTargetServers s;
  24385. auto cli = make_client("public.example", s);
  24386. cli->set_proxy_basic_auth("u", "p");
  24387. cli->set_no_proxy({"internal.corp"}); // does not match
  24388. auto res = cli->Get("/");
  24389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24390. EXPECT_GE(s.proxy_hits(), 1);
  24391. EXPECT_TRUE(s.last_had_proxy_authz());
  24392. }
  24393. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24394. std::atomic<int> hits{0};
  24395. std::atomic<int> hits_with_authz{0};
  24396. no_proxy_test::ScopedServer proxy_mock;
  24397. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24398. hits++;
  24399. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24400. if (req.target.find("/redir") != std::string::npos) {
  24401. res.set_redirect("http://other.example/landed");
  24402. } else {
  24403. res.set_content("via-proxy", "text/plain");
  24404. }
  24405. });
  24406. proxy_mock.listen();
  24407. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24408. hits = 0;
  24409. hits_with_authz = 0;
  24410. Client cli("public.example", 80);
  24411. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24412. cli.set_proxy_basic_auth(c.first, c.second);
  24413. cli.set_follow_location(true);
  24414. // The redirect to another host goes through the proxy as well
  24415. auto res = cli.Get("/redir");
  24416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24417. EXPECT_EQ(2, hits.load());
  24418. EXPECT_EQ(2, hits_with_authz.load());
  24419. }
  24420. }
  24421. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24422. ProxyAndTargetServers s;
  24423. auto cli = make_client("anything.test", s);
  24424. auto res = cli->Get("/");
  24425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24426. EXPECT_GE(s.proxy_hits(), 1);
  24427. EXPECT_EQ(0, s.target_hits());
  24428. }
  24429. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24430. ProxyAndTargetServers s;
  24431. auto cli = make_client("example.com", s);
  24432. cli->set_no_proxy({"example.com:8080"});
  24433. auto res = cli->Get("/");
  24434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24435. EXPECT_GE(s.proxy_hits(), 1);
  24436. EXPECT_EQ(0, s.target_hits());
  24437. }
  24438. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24439. ProxyAndTargetServers s;
  24440. auto cli = make_client("anything.test", s);
  24441. cli->set_no_proxy({"", " ", "\t"});
  24442. auto res = cli->Get("/");
  24443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24444. EXPECT_GE(s.proxy_hits(), 1);
  24445. EXPECT_EQ(0, s.target_hits());
  24446. }
  24447. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24448. // An entry with leading/trailing whitespace must still match — env-style
  24449. // values are commonly pasted with stray spaces and an implementation
  24450. // that feeds the raw token directly to inet_pton would fail to match
  24451. // valid CIDRs because of the spaces.
  24452. ProxyAndTargetServers s;
  24453. Client cli("127.0.0.1", s.target_port());
  24454. cli.set_proxy("127.0.0.1", s.proxy_port());
  24455. cli.set_no_proxy({" 127.0.0.0/8 "});
  24456. auto res = cli.Get("/");
  24457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24458. EXPECT_EQ(0, s.proxy_hits());
  24459. EXPECT_EQ(1, s.target_hits());
  24460. }
  24461. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24462. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24463. // go direct and must NOT carry Proxy-Authorization.
  24464. std::atomic<int> proxy_hits{0};
  24465. std::atomic<int> target_hits{0};
  24466. std::atomic<bool> target_saw_authz{false};
  24467. no_proxy_test::ScopedServer proxy_mock, target;
  24468. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24469. proxy_hits++;
  24470. res.status = 302;
  24471. res.set_header("Location", "http://127.0.0.1:" +
  24472. std::to_string(target.port()) + "/landed");
  24473. });
  24474. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24475. target_hits++;
  24476. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24477. res.set_content("direct", "text/plain");
  24478. });
  24479. proxy_mock.listen();
  24480. target.listen();
  24481. Client cli("public.example", target.port());
  24482. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24483. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24484. cli.set_proxy_basic_auth("u", "p");
  24485. cli.set_no_proxy({"127.0.0.1"});
  24486. cli.set_follow_location(true);
  24487. auto res = cli.Get("/redir");
  24488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24489. EXPECT_GE(proxy_hits.load(), 1);
  24490. EXPECT_GE(target_hits.load(), 1);
  24491. EXPECT_FALSE(target_saw_authz.load());
  24492. }
  24493. #ifdef CPPHTTPLIB_SSL_ENABLED
  24494. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24495. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24496. // proxy creds would be sent to the (possibly hostile) origin.
  24497. std::atomic<int> target_hits{0};
  24498. std::atomic<bool> target_saw_proxy_authz{false};
  24499. no_proxy_test::ScopedServer target;
  24500. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24501. target_hits++;
  24502. if (req.has_header("Proxy-Authorization")) {
  24503. target_saw_proxy_authz = true;
  24504. }
  24505. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24506. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24507. "nonce=\"abc\", algorithm=MD5");
  24508. });
  24509. target.listen();
  24510. // The proxy address is set to the target's port: the bypass MUST kick in;
  24511. // if it doesn't, the test still routes "via proxy" to the same server and
  24512. // the Proxy-Authorization assertion below catches the leak.
  24513. Client cli("evil.example", target.port());
  24514. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24515. cli.set_proxy("127.0.0.1", target.port());
  24516. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24517. cli.set_no_proxy({"evil.example"});
  24518. auto res = cli.Get("/x");
  24519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24520. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24521. EXPECT_EQ(1, target_hits.load());
  24522. EXPECT_FALSE(target_saw_proxy_authz.load());
  24523. }
  24524. #endif
  24525. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24526. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24527. std::atomic<int> proxy_hits{0};
  24528. std::atomic<int> bypass_hits{0};
  24529. std::atomic<bool> proxy_saw_c_url{false};
  24530. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24531. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24532. proxy_hits++;
  24533. if (req.path.find("/start") != std::string::npos) {
  24534. res.status = 302;
  24535. res.set_header("Location", "http://127.0.0.1:" +
  24536. std::to_string(bypass_server.port()) +
  24537. "/middle");
  24538. return;
  24539. }
  24540. if (req.path.find("/end") != std::string::npos) {
  24541. proxy_saw_c_url = true;
  24542. res.set_content("c-via-proxy", "text/plain");
  24543. return;
  24544. }
  24545. res.set_content("unexpected", "text/plain");
  24546. });
  24547. // public.example's "advertised" port is arbitrary (the request never lands
  24548. // there — it goes through the proxy), but use a dynamic value to stay
  24549. // friendly with sharded parallel runs.
  24550. int public_port = bypass_server.port();
  24551. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24552. bypass_hits++;
  24553. res.status = 302;
  24554. res.set_header("Location", "http://public.example:" +
  24555. std::to_string(public_port) + "/end");
  24556. });
  24557. proxy_mock.listen();
  24558. bypass_server.listen();
  24559. Client cli("public.example", public_port);
  24560. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24561. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24562. cli.set_no_proxy({"127.0.0.1"});
  24563. cli.set_follow_location(true);
  24564. auto res = cli.Get("/start");
  24565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24566. EXPECT_EQ(StatusCode::OK_200, res->status);
  24567. EXPECT_EQ("c-via-proxy", res->body);
  24568. EXPECT_GE(proxy_hits.load(), 2);
  24569. EXPECT_GE(bypass_hits.load(), 1);
  24570. EXPECT_TRUE(proxy_saw_c_url.load());
  24571. }
  24572. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24573. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24574. // request reconnects to the correct endpoint.
  24575. std::atomic<int> proxy_hits{0};
  24576. std::atomic<int> target_hits{0};
  24577. no_proxy_test::ScopedServer proxy_mock, target;
  24578. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24579. proxy_hits++;
  24580. res.set_content("via-proxy", "text/plain");
  24581. });
  24582. target.svr().Get(".*", [&](const Request &, Response &res) {
  24583. target_hits++;
  24584. res.set_content("direct", "text/plain");
  24585. });
  24586. proxy_mock.listen();
  24587. target.listen();
  24588. Client cli("public.example", target.port());
  24589. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24590. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24591. cli.set_keep_alive(true);
  24592. auto res1 = cli.Get("/a");
  24593. ASSERT_TRUE(res1);
  24594. EXPECT_EQ("via-proxy", res1->body);
  24595. EXPECT_EQ(1, proxy_hits.load());
  24596. EXPECT_EQ(0, target_hits.load());
  24597. cli.set_no_proxy({"public.example"});
  24598. auto res2 = cli.Get("/b");
  24599. ASSERT_TRUE(res2);
  24600. EXPECT_EQ("direct", res2->body);
  24601. EXPECT_EQ(1, proxy_hits.load());
  24602. EXPECT_EQ(1, target_hits.load());
  24603. }
  24604. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24605. namespace proxy_tunnel_test {
  24606. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24607. class ScopedSSLServer {
  24608. public:
  24609. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24610. port_ = svr_.bind_to_any_port("127.0.0.1");
  24611. }
  24612. ~ScopedSSLServer() {
  24613. svr_.stop();
  24614. if (th_.joinable()) { th_.join(); }
  24615. }
  24616. SSLServer &svr() { return svr_; }
  24617. int port() const { return port_; }
  24618. void listen() {
  24619. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24620. svr_.wait_until_ready();
  24621. }
  24622. private:
  24623. SSLServer svr_;
  24624. std::thread th_;
  24625. int port_ = 0;
  24626. };
  24627. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24628. class ScopedConnectProxy {
  24629. public:
  24630. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24631. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24632. if (listen_fd_ < 0) { return; }
  24633. int yes = 1;
  24634. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24635. sockaddr_in a{};
  24636. a.sin_family = AF_INET;
  24637. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24638. a.sin_port = 0;
  24639. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24640. return;
  24641. }
  24642. socklen_t alen = sizeof(a);
  24643. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24644. 0) {
  24645. return;
  24646. }
  24647. port_ = ntohs(a.sin_port);
  24648. if (::listen(listen_fd_, 1) != 0) { return; }
  24649. th_ = std::thread([this] { run(); });
  24650. }
  24651. ~ScopedConnectProxy() {
  24652. stop_ = true;
  24653. if (listen_fd_ >= 0) {
  24654. ::shutdown(listen_fd_, SHUT_RDWR);
  24655. ::close(listen_fd_);
  24656. }
  24657. if (th_.joinable()) { th_.join(); }
  24658. }
  24659. int port() const { return port_; }
  24660. int connect_hits() const { return connect_hits_.load(); }
  24661. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24662. std::string connect_request() const {
  24663. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24664. return connect_request_;
  24665. }
  24666. private:
  24667. void run() {
  24668. while (!stop_.load()) {
  24669. fd_set rfds;
  24670. FD_ZERO(&rfds);
  24671. FD_SET(listen_fd_, &rfds);
  24672. timeval tv{0, 100 * 1000};
  24673. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24674. if (sel <= 0) { continue; }
  24675. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24676. if (client_fd < 0) { continue; }
  24677. std::string req;
  24678. char buf[2048];
  24679. while (req.find("\r\n\r\n") == std::string::npos) {
  24680. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24681. if (n <= 0) { break; }
  24682. req.append(buf, static_cast<size_t>(n));
  24683. }
  24684. if (req.compare(0, 7, "CONNECT") != 0) {
  24685. ::close(client_fd);
  24686. continue;
  24687. }
  24688. connect_hits_++;
  24689. {
  24690. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24691. connect_request_ = req;
  24692. }
  24693. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24694. ::send(client_fd, ok, std::strlen(ok), 0);
  24695. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24696. sockaddr_in o{};
  24697. o.sin_family = AF_INET;
  24698. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24699. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24700. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24701. 0) {
  24702. ::close(client_fd);
  24703. ::close(origin_fd);
  24704. continue;
  24705. }
  24706. auto forward = [](int from, int to) {
  24707. char b[8192];
  24708. for (;;) {
  24709. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24710. if (n <= 0) { break; }
  24711. ssize_t off = 0;
  24712. while (off < n) {
  24713. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24714. if (s <= 0) {
  24715. off = n;
  24716. break;
  24717. }
  24718. off += s;
  24719. }
  24720. }
  24721. ::shutdown(to, SHUT_WR);
  24722. };
  24723. std::thread t1([&] { forward(client_fd, origin_fd); });
  24724. std::thread t2([&] { forward(origin_fd, client_fd); });
  24725. t1.join();
  24726. t2.join();
  24727. ::close(client_fd);
  24728. ::close(origin_fd);
  24729. }
  24730. }
  24731. int forward_port_ = -1;
  24732. int listen_fd_ = -1;
  24733. int port_ = 0;
  24734. std::thread th_;
  24735. std::atomic<bool> stop_{false};
  24736. std::atomic<int> connect_hits_{0};
  24737. mutable std::mutex connect_request_mutex_;
  24738. std::string connect_request_;
  24739. };
  24740. // Sends one request through the CONNECT proxy to the TLS origin with a
  24741. // credential configured for each hop, and checks that each credential reaches
  24742. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24743. // origin's (every header in origin_headers) on the tunnelled request.
  24744. void CredentialsStayWithTheirHop(
  24745. const std::function<void(SSLClient &)> &set_credentials,
  24746. const std::string &scheme,
  24747. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24748. std::atomic<int> origin_hits{0};
  24749. std::atomic<bool> origin_saw_proxy_authz{false};
  24750. std::atomic<bool> origin_saw_headers{false};
  24751. ScopedSSLServer origin;
  24752. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24753. origin_hits++;
  24754. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24755. origin_saw_headers =
  24756. std::all_of(origin_headers.begin(), origin_headers.end(),
  24757. [&](const std::string &h) { return req.has_header(h); });
  24758. res.set_content("ok", "text/plain");
  24759. });
  24760. origin.listen();
  24761. ScopedConnectProxy proxy(origin.port());
  24762. ASSERT_NE(0, proxy.port());
  24763. // Pinned to 127.0.0.1 for the same reason as the test below.
  24764. SSLClient cli("127.0.0.1", origin.port());
  24765. cli.enable_server_certificate_verification(false);
  24766. cli.set_proxy("127.0.0.1", proxy.port());
  24767. set_credentials(cli);
  24768. auto res = cli.Get("/x");
  24769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24770. EXPECT_EQ(StatusCode::OK_200, res->status);
  24771. EXPECT_EQ(1, origin_hits.load());
  24772. EXPECT_EQ(1, proxy.connect_hits());
  24773. EXPECT_TRUE(origin_saw_headers.load());
  24774. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24775. << "Proxy-Authorization must not be sent inside the tunnel";
  24776. auto connect_req = proxy.connect_request();
  24777. EXPECT_NE(std::string::npos,
  24778. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24779. for (const auto &h : origin_headers) {
  24780. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24781. << h << " must not be sent to the proxy on CONNECT";
  24782. }
  24783. }
  24784. } // namespace proxy_tunnel_test
  24785. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24786. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24787. [](SSLClient &cli) {
  24788. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24789. cli.set_basic_auth("origin-user", "origin-pass");
  24790. },
  24791. "Basic");
  24792. }
  24793. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24794. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24795. [](SSLClient &cli) {
  24796. cli.set_proxy_bearer_token_auth("proxy-token");
  24797. cli.set_bearer_token_auth("origin-token");
  24798. },
  24799. "Bearer");
  24800. }
  24801. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24802. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24803. [](SSLClient &cli) {
  24804. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24805. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24806. {"Cookie", "sid=origin-session"},
  24807. {"X-Api-Key", "origin-key"}});
  24808. },
  24809. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24810. }
  24811. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24812. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24813. // retry; otherwise proxy creds would be sent to the origin.
  24814. std::atomic<int> origin_hits{0};
  24815. std::atomic<bool> origin_saw_proxy_authz{false};
  24816. proxy_tunnel_test::ScopedSSLServer origin;
  24817. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24818. origin_hits++;
  24819. if (req.has_header("Proxy-Authorization")) {
  24820. origin_saw_proxy_authz = true;
  24821. }
  24822. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24823. res.set_header("Proxy-Authenticate",
  24824. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24825. "algorithm=MD5");
  24826. });
  24827. origin.listen();
  24828. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24829. ASSERT_NE(0, proxy.port());
  24830. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24831. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24832. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24833. // and answer with its own status, making this test flaky.
  24834. SSLClient cli("127.0.0.1", origin.port());
  24835. cli.enable_server_certificate_verification(false);
  24836. cli.set_proxy("127.0.0.1", proxy.port());
  24837. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24838. auto res = cli.Get("/x");
  24839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24840. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24841. EXPECT_EQ(1, origin_hits.load());
  24842. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24843. EXPECT_EQ(1, proxy.connect_hits());
  24844. }
  24845. #endif