test.cc 952 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346
  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 Section 3.3 requires realm and nonce on every Digest challenge.
  2988. // make_digest_authentication_header() dereferences both unconditionally, so
  2989. // a server sending a challenge missing either one must not be treated as
  2990. // usable -- doing so used to crash the client with std::out_of_range.
  2991. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2992. Server svr;
  2993. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2994. res.status = StatusCode::Unauthorized_401;
  2995. res.set_header("WWW-Authenticate", challenge);
  2996. });
  2997. auto port = svr.bind_to_any_port(HOST);
  2998. std::thread t([&]() { svr.listen_after_bind(); });
  2999. auto se = detail::scope_exit([&] {
  3000. svr.stop();
  3001. t.join();
  3002. });
  3003. svr.wait_until_ready();
  3004. Client cli(HOST, port);
  3005. cli.set_digest_auth("hello", "world");
  3006. auto res = cli.Get("/x");
  3007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3008. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3009. }
  3010. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3011. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3012. }
  3013. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3014. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3015. }
  3016. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3017. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3018. }
  3019. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3020. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3021. // when storing the values, so the header builder has to re-escape them (and
  3022. // keep algorithm a bare token); otherwise the value breaks out of its
  3023. // quoted-string and injects extra auth-params into the client's Authorization.
  3024. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3025. std::atomic<int> hits{0};
  3026. std::string authorization;
  3027. Server svr;
  3028. svr.Get("/x", [&](const Request &req, Response &res) {
  3029. if (++hits == 1) {
  3030. res.status = StatusCode::Unauthorized_401;
  3031. // On the wire the quotes embedded in the values are backslash-escaped.
  3032. res.set_header("WWW-Authenticate",
  3033. "Digest realm=\"testrealm\", "
  3034. "nonce=\"n\\\"; injected=\\\"x\", "
  3035. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3036. } else {
  3037. authorization = req.get_header_value("Authorization");
  3038. res.set_content("ok", "text/plain");
  3039. }
  3040. });
  3041. auto port = svr.bind_to_any_port(HOST);
  3042. std::thread t([&]() { svr.listen_after_bind(); });
  3043. auto se = detail::scope_exit([&] {
  3044. svr.stop();
  3045. t.join();
  3046. });
  3047. svr.wait_until_ready();
  3048. Client cli(HOST, port);
  3049. cli.set_digest_auth("hello", "world");
  3050. auto res = cli.Get("/x");
  3051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3052. EXPECT_EQ(2, hits.load());
  3053. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3054. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3055. // inside its quoted-string rather than starting an "injected" auth-param.
  3056. EXPECT_NE(std::string::npos,
  3057. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3058. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3059. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3060. }
  3061. #endif
  3062. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3063. auto host = "google.com";
  3064. auto another_host = "example.com";
  3065. auto wrong_ip = "0.0.0.0";
  3066. #ifdef CPPHTTPLIB_SSL_ENABLED
  3067. SSLClient cli(host);
  3068. #else
  3069. Client cli(host);
  3070. #endif
  3071. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3072. auto res = cli.Get("/");
  3073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3074. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3075. }
  3076. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3077. auto host = "google.com";
  3078. auto wrong_ip = "0.0.0.0";
  3079. #ifdef CPPHTTPLIB_SSL_ENABLED
  3080. SSLClient cli(host);
  3081. #else
  3082. Client cli(host);
  3083. #endif
  3084. cli.set_hostname_addr_map({{host, wrong_ip}});
  3085. auto res = cli.Get("/");
  3086. ASSERT_TRUE(!res);
  3087. EXPECT_EQ(Error::Connection, res.error());
  3088. }
  3089. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3090. // A mapped value that is not an IP literal must be resolved. "localhost"
  3091. // resolves from the hosts file, so this test needs no external DNS.
  3092. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3093. auto host = "target.invalid";
  3094. Server svr;
  3095. std::string received_host;
  3096. svr.Get("/hi", [&](const Request &req, Response &res) {
  3097. received_host = req.get_header_value("Host");
  3098. res.set_content("Hello World!", "text/plain");
  3099. });
  3100. auto port = svr.bind_to_any_port(HOST);
  3101. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3102. auto se = detail::scope_exit([&] {
  3103. svr.stop();
  3104. thread.join();
  3105. ASSERT_FALSE(svr.is_running());
  3106. });
  3107. svr.wait_until_ready();
  3108. Client cli(host, port);
  3109. cli.set_hostname_addr_map({{host, HOST}});
  3110. auto res = cli.Get("/hi");
  3111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3112. EXPECT_EQ(StatusCode::OK_200, res->status);
  3113. // The mapping only redirects the connection; the identity stays host_.
  3114. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3115. }
  3116. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3117. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3118. auto host = "target.invalid";
  3119. Server svr;
  3120. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3121. res.set_content("Hello World!", "text/plain");
  3122. });
  3123. auto port = svr.bind_to_any_port("127.0.0.1");
  3124. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3125. auto se = detail::scope_exit([&] {
  3126. svr.stop();
  3127. thread.join();
  3128. ASSERT_FALSE(svr.is_running());
  3129. });
  3130. svr.wait_until_ready();
  3131. Client cli(host, port);
  3132. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3133. auto res = cli.Get("/hi");
  3134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3135. EXPECT_EQ(StatusCode::OK_200, res->status);
  3136. }
  3137. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3138. // An empty mapped value must leave host_ as the connection target. Without
  3139. // that guard the empty value would become the host argument, getaddrinfo
  3140. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3141. // loopback - silently connecting somewhere the caller never asked for.
  3142. // The server listens on loopback, so such a fallback would succeed and is
  3143. // therefore observable as a failure of this test.
  3144. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3145. Server svr;
  3146. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3147. res.set_content("Hello World!", "text/plain");
  3148. });
  3149. auto port = svr.bind_to_any_port(HOST);
  3150. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3151. auto se = detail::scope_exit([&] {
  3152. svr.stop();
  3153. thread.join();
  3154. ASSERT_FALSE(svr.is_running());
  3155. });
  3156. svr.wait_until_ready();
  3157. Client cli(blackhole, port);
  3158. cli.set_hostname_addr_map({{blackhole, ""}});
  3159. cli.set_connection_timeout(1);
  3160. auto res = cli.Get("/hi");
  3161. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3162. }
  3163. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3164. auto host = "httpbingo.org";
  3165. auto path = std::string{"/absolute-redirect/3"};
  3166. #ifdef CPPHTTPLIB_SSL_ENABLED
  3167. SSLClient cli(host);
  3168. #else
  3169. Client cli(host);
  3170. #endif
  3171. cli.set_follow_location(true);
  3172. auto res = cli.Get(path);
  3173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3174. EXPECT_EQ(StatusCode::OK_200, res->status);
  3175. }
  3176. TEST(RedirectTest, Redirect_Online) {
  3177. auto host = "httpbingo.org";
  3178. auto path = std::string{"/redirect/3"};
  3179. #ifdef CPPHTTPLIB_SSL_ENABLED
  3180. SSLClient cli(host);
  3181. #else
  3182. Client cli(host);
  3183. #endif
  3184. cli.set_follow_location(true);
  3185. auto res = cli.Get(path);
  3186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3187. EXPECT_EQ(StatusCode::OK_200, res->status);
  3188. }
  3189. TEST(RelativeRedirectTest, Redirect_Online) {
  3190. auto host = "httpbingo.org";
  3191. auto path = std::string{"/relative-redirect/3"};
  3192. #ifdef CPPHTTPLIB_SSL_ENABLED
  3193. SSLClient cli(host);
  3194. #else
  3195. Client cli(host);
  3196. #endif
  3197. cli.set_follow_location(true);
  3198. auto res = cli.Get(path);
  3199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3200. EXPECT_EQ(StatusCode::OK_200, res->status);
  3201. }
  3202. TEST(TooManyRedirectTest, Redirect_Online) {
  3203. auto host = "httpbingo.org";
  3204. auto path = std::string{"/redirect/21"};
  3205. #ifdef CPPHTTPLIB_SSL_ENABLED
  3206. SSLClient cli(host);
  3207. #else
  3208. Client cli(host);
  3209. #endif
  3210. cli.set_follow_location(true);
  3211. auto res = cli.Get(path);
  3212. ASSERT_TRUE(!res);
  3213. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3214. }
  3215. #ifdef CPPHTTPLIB_SSL_ENABLED
  3216. TEST(YahooRedirectTest, Redirect_Online) {
  3217. Client cli("yahoo.com");
  3218. auto res = cli.Get("/");
  3219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3220. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3221. cli.set_follow_location(true);
  3222. res = cli.Get("/");
  3223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3224. EXPECT_EQ(StatusCode::OK_200, res->status);
  3225. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3226. }
  3227. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3228. #define REDIR_HOST "httpbingo.org"
  3229. #define REDIR_PATH "/redirect-to"
  3230. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3231. SSLClient cli(REDIR_HOST);
  3232. cli.set_follow_location(true);
  3233. auto res =
  3234. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3236. EXPECT_EQ(StatusCode::OK_200, res->status);
  3237. }
  3238. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3239. SSLClient cli(REDIR_HOST);
  3240. cli.set_follow_location(true);
  3241. Params params;
  3242. params.emplace("url", "http://example.com");
  3243. params.emplace("status_code", "302");
  3244. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3246. EXPECT_EQ(StatusCode::OK_200, res->status);
  3247. }
  3248. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3249. SSLClient cli(REDIR_HOST);
  3250. cli.set_follow_location(true);
  3251. Params params;
  3252. params.emplace("url", "http://example.com");
  3253. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3255. EXPECT_EQ(StatusCode::OK_200, res->status);
  3256. }
  3257. TEST(UrlWithSpace, Redirect_Online) {
  3258. SSLClient cli("edge.forgecdn.net");
  3259. cli.set_follow_location(true);
  3260. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3262. EXPECT_EQ(StatusCode::OK_200, res->status);
  3263. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3264. }
  3265. #endif
  3266. #if !defined(_WIN32) && !defined(_WIN64)
  3267. TEST(ReceiveSignals, Signal) {
  3268. auto setupSignalHandlers = []() {
  3269. struct sigaction act;
  3270. sigemptyset(&act.sa_mask);
  3271. act.sa_flags = SA_SIGINFO;
  3272. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3273. switch (sig) {
  3274. case SIGINT:
  3275. default: break;
  3276. }
  3277. };
  3278. ::sigaction(SIGINT, &act, nullptr);
  3279. };
  3280. Server svr;
  3281. int port = 0;
  3282. auto thread = std::thread([&]() {
  3283. setupSignalHandlers();
  3284. port = svr.bind_to_any_port(HOST);
  3285. svr.listen_after_bind();
  3286. });
  3287. auto se = detail::scope_exit([&] {
  3288. svr.stop();
  3289. thread.join();
  3290. ASSERT_FALSE(svr.is_running());
  3291. });
  3292. svr.wait_until_ready();
  3293. ASSERT_TRUE(svr.is_running());
  3294. pthread_kill(thread.native_handle(), SIGINT);
  3295. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3296. ASSERT_TRUE(svr.is_running());
  3297. }
  3298. #endif
  3299. TEST(RedirectToDifferentPort, Redirect) {
  3300. Server svr1;
  3301. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3302. res.set_content("Hello World!", "text/plain");
  3303. });
  3304. int svr1_port = 0;
  3305. auto thread1 = std::thread([&]() {
  3306. svr1_port = svr1.bind_to_any_port(HOST);
  3307. svr1.listen_after_bind();
  3308. });
  3309. Server svr2;
  3310. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3311. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3312. });
  3313. int svr2_port = 0;
  3314. auto thread2 = std::thread([&]() {
  3315. svr2_port = svr2.bind_to_any_port(HOST);
  3316. svr2.listen_after_bind();
  3317. });
  3318. auto se = detail::scope_exit([&] {
  3319. svr2.stop();
  3320. thread2.join();
  3321. svr1.stop();
  3322. thread1.join();
  3323. ASSERT_FALSE(svr2.is_running());
  3324. ASSERT_FALSE(svr1.is_running());
  3325. });
  3326. svr1.wait_until_ready();
  3327. svr2.wait_until_ready();
  3328. Client cli("localhost", svr2_port);
  3329. cli.set_follow_location(true);
  3330. auto res = cli.Get("/2");
  3331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3332. EXPECT_EQ(StatusCode::OK_200, res->status);
  3333. EXPECT_EQ("Hello World!", res->body);
  3334. }
  3335. // GET /redir on one server redirects to /target on another port, so the
  3336. // client follows it with a new client.
  3337. static Result
  3338. GetThroughRedirectToDifferentPort(Server::Handler target,
  3339. const std::function<void(Client &)> &setup,
  3340. const Headers &headers = Headers()) {
  3341. Server target_svr;
  3342. target_svr.Get("/target", target);
  3343. int target_port = 0;
  3344. auto target_thread = std::thread([&]() {
  3345. target_port = target_svr.bind_to_any_port(HOST);
  3346. target_svr.listen_after_bind();
  3347. });
  3348. Server origin_svr;
  3349. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3350. res.set_redirect(
  3351. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3352. });
  3353. int origin_port = 0;
  3354. auto origin_thread = std::thread([&]() {
  3355. origin_port = origin_svr.bind_to_any_port(HOST);
  3356. origin_svr.listen_after_bind();
  3357. });
  3358. auto se = detail::scope_exit([&] {
  3359. origin_svr.stop();
  3360. origin_thread.join();
  3361. target_svr.stop();
  3362. target_thread.join();
  3363. });
  3364. target_svr.wait_until_ready();
  3365. origin_svr.wait_until_ready();
  3366. Client cli("localhost", origin_port);
  3367. cli.set_follow_location(true);
  3368. setup(cli);
  3369. return cli.Get("/redir", headers);
  3370. }
  3371. static void
  3372. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3373. std::string captured_authorization;
  3374. auto result = GetThroughRedirectToDifferentPort(
  3375. [&](const Request &req, Response &res) {
  3376. captured_authorization = req.get_header_value("Authorization");
  3377. res.set_content("OK", "text/plain");
  3378. },
  3379. set_auth);
  3380. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3381. EXPECT_EQ(StatusCode::OK_200, result->status);
  3382. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3383. EXPECT_TRUE(captured_authorization.empty());
  3384. }
  3385. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3386. TestDoNotForwardCredentialsOnRedirect(
  3387. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3388. }
  3389. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3390. TestDoNotForwardCredentialsOnRedirect(
  3391. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3392. }
  3393. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3394. std::string captured_cookie;
  3395. auto result = GetThroughRedirectToDifferentPort(
  3396. [&](const Request &req, Response &res) {
  3397. captured_cookie = req.get_header_value("Cookie");
  3398. res.set_content("OK", "text/plain");
  3399. },
  3400. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3401. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3402. EXPECT_EQ(StatusCode::OK_200, result->status);
  3403. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3404. EXPECT_TRUE(captured_cookie.empty());
  3405. }
  3406. TEST(RedirectToSamePort, ForwardCookie) {
  3407. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3408. // header so that ordinary session flows keep working.
  3409. Server svr;
  3410. std::string captured_cookie;
  3411. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3412. res.set_redirect("/target", 302);
  3413. });
  3414. svr.Get("/target", [&](const Request &req, Response &res) {
  3415. captured_cookie = req.get_header_value("Cookie");
  3416. res.set_content("OK", "text/plain");
  3417. });
  3418. auto port = svr.bind_to_any_port(HOST);
  3419. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3420. auto se = detail::scope_exit([&] {
  3421. svr.stop();
  3422. thread.join();
  3423. ASSERT_FALSE(svr.is_running());
  3424. });
  3425. svr.wait_until_ready();
  3426. Client cli(HOST, port);
  3427. cli.set_follow_location(true);
  3428. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3429. auto res = cli.Get("/redir", headers);
  3430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3431. EXPECT_EQ(StatusCode::OK_200, res->status);
  3432. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3433. }
  3434. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3435. std::string authorization;
  3436. std::string trace_id;
  3437. auto result = GetThroughRedirectToDifferentPort(
  3438. [&](const Request &req, Response &res) {
  3439. authorization = req.get_header_value("Authorization");
  3440. trace_id = req.get_header_value("X-Trace-Id");
  3441. res.set_content("OK", "text/plain");
  3442. },
  3443. [](Client &cli) {
  3444. cli.set_default_headers(
  3445. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3446. });
  3447. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3448. EXPECT_EQ(StatusCode::OK_200, result->status);
  3449. // Like a header given with the request, a default one goes along unless it
  3450. // carries credentials (RFC 9110 15.4).
  3451. EXPECT_TRUE(authorization.empty());
  3452. EXPECT_EQ("42", trace_id);
  3453. }
  3454. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3455. auto result = GetThroughRedirectToDifferentPort(
  3456. [](const Request &, Response &res) {
  3457. res.set_content(std::string(2048, 'x'), "text/plain");
  3458. },
  3459. [](Client &cli) { cli.set_payload_max_length(1024); });
  3460. EXPECT_FALSE(result);
  3461. }
  3462. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3463. auto result = GetThroughRedirectToDifferentPort(
  3464. [](const Request &req, Response &res) {
  3465. // Answer after a second, or once the client gives up.
  3466. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3467. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3468. }
  3469. res.set_content("late", "text/plain");
  3470. },
  3471. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3472. ASSERT_FALSE(result);
  3473. EXPECT_EQ(Error::Read, result.error());
  3474. }
  3475. #ifdef CPPHTTPLIB_SSL_ENABLED
  3476. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3477. auto result = GetThroughRedirectToDifferentPort(
  3478. [](const Request &, Response &res) {
  3479. res.status = StatusCode::Unauthorized_401;
  3480. res.set_header("WWW-Authenticate",
  3481. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3482. },
  3483. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3484. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3485. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3486. }
  3487. #endif
  3488. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3489. Server svr;
  3490. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3491. // Port number that overflows int — should not crash
  3492. res.set_redirect("http://localhost:99999999999999999999/target");
  3493. });
  3494. auto port = svr.bind_to_any_port(HOST);
  3495. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3496. auto se = detail::scope_exit([&] {
  3497. svr.stop();
  3498. thread.join();
  3499. ASSERT_FALSE(svr.is_running());
  3500. });
  3501. svr.wait_until_ready();
  3502. Client cli(HOST, port);
  3503. cli.set_follow_location(true);
  3504. auto res = cli.Get("/redir");
  3505. // Should fail gracefully, not crash (no valid response due to bad port)
  3506. EXPECT_FALSE(res);
  3507. }
  3508. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3509. Server svr;
  3510. auto port = svr.bind_to_any_port(HOST);
  3511. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3512. // The server's own port followed by junk must not be followed
  3513. res.set_redirect("http://" + std::string(HOST) + ":" +
  3514. std::to_string(port) + "junk/target");
  3515. });
  3516. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3517. res.set_content("target", "text/plain");
  3518. });
  3519. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3520. auto se = detail::scope_exit([&] {
  3521. svr.stop();
  3522. thread.join();
  3523. ASSERT_FALSE(svr.is_running());
  3524. });
  3525. svr.wait_until_ready();
  3526. Client cli(HOST, port);
  3527. cli.set_follow_location(true);
  3528. auto res = cli.Get("/redir");
  3529. EXPECT_FALSE(res);
  3530. }
  3531. TEST(RedirectFromPageWithContent, Redirect) {
  3532. Server svr;
  3533. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3534. res.set_content("___", "text/plain");
  3535. res.set_redirect("/2");
  3536. });
  3537. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3538. res.set_content("Hello World!", "text/plain");
  3539. });
  3540. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3541. auto se = detail::scope_exit([&] {
  3542. svr.stop();
  3543. th.join();
  3544. ASSERT_FALSE(svr.is_running());
  3545. });
  3546. svr.wait_until_ready();
  3547. {
  3548. Client cli("localhost", PORT);
  3549. cli.set_follow_location(true);
  3550. std::string body;
  3551. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3552. body.append(data, data_length);
  3553. return true;
  3554. });
  3555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3556. EXPECT_EQ(StatusCode::OK_200, res->status);
  3557. EXPECT_EQ("Hello World!", body);
  3558. }
  3559. {
  3560. Client cli("localhost", PORT);
  3561. std::string body;
  3562. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3563. body.append(data, data_length);
  3564. return true;
  3565. });
  3566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3567. EXPECT_EQ(StatusCode::Found_302, res->status);
  3568. EXPECT_EQ("___", body);
  3569. }
  3570. }
  3571. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3572. Server svr;
  3573. auto port_str = std::to_string(PORT);
  3574. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3575. auto expected_host = "[::1]:" + port_str;
  3576. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3577. res.set_content("___", "text/plain");
  3578. // res.set_redirect("/2");
  3579. res.set_redirect(redirect_url);
  3580. });
  3581. svr.Get("/2", [&](const Request &req, Response &res) {
  3582. auto host_header = req.headers.find("Host");
  3583. ASSERT_TRUE(host_header != req.headers.end());
  3584. EXPECT_EQ(expected_host, host_header->second);
  3585. res.set_content("Hello World!", "text/plain");
  3586. });
  3587. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3588. auto se = detail::scope_exit([&] {
  3589. svr.stop();
  3590. th.join();
  3591. ASSERT_FALSE(svr.is_running());
  3592. });
  3593. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3594. // actually starts anything, so the condition !svr.is_running() will
  3595. // always remain true, and the loop never stops.
  3596. // This basically counts how many milliseconds have passed since the
  3597. // call to svr.listen(), and if after 5 seconds nothing started yet
  3598. // aborts the test.
  3599. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3600. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3601. ASSERT_LT(milliseconds, 5000U);
  3602. }
  3603. {
  3604. Client cli("::1", PORT);
  3605. cli.set_follow_location(true);
  3606. std::string body;
  3607. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3608. body.append(data, data_length);
  3609. return true;
  3610. });
  3611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3612. EXPECT_EQ(StatusCode::OK_200, res->status);
  3613. EXPECT_EQ("Hello World!", body);
  3614. }
  3615. {
  3616. Client cli("::1", PORT);
  3617. std::string body;
  3618. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3619. body.append(data, data_length);
  3620. return true;
  3621. });
  3622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3623. EXPECT_EQ(StatusCode::Found_302, res->status);
  3624. EXPECT_EQ("___", body);
  3625. }
  3626. }
  3627. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3628. Server svr;
  3629. svr.Get("/foo", [](const Request &req, Response &res) {
  3630. auto a = req.params.find("a");
  3631. if (a != req.params.end()) {
  3632. res.set_content((*a).second, "text/plain");
  3633. res.status = StatusCode::OK_200;
  3634. } else {
  3635. res.status = StatusCode::BadRequest_400;
  3636. }
  3637. });
  3638. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3639. auto se = detail::scope_exit([&] {
  3640. svr.stop();
  3641. thread.join();
  3642. ASSERT_FALSE(svr.is_running());
  3643. });
  3644. svr.wait_until_ready();
  3645. {
  3646. Client cli(HOST, PORT);
  3647. cli.set_path_encode(false);
  3648. auto res = cli.Get("/foo?a=explicitly+encoded");
  3649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3650. EXPECT_EQ(StatusCode::OK_200, res->status);
  3651. // This expects it back with a space, as the `+` won't have been
  3652. // url-encoded, and server-side the params get decoded turning `+`
  3653. // into spaces.
  3654. EXPECT_EQ("explicitly encoded", res->body);
  3655. }
  3656. }
  3657. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3658. // When path encoding is disabled the client must transmit the supplied
  3659. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3660. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3661. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3662. // than a space (0x20). Assert on the raw wire target to catch this.
  3663. Server svr;
  3664. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3665. svr.Get("/foo", [&](const Request &req, Response &res) {
  3666. EXPECT_EQ(expected_target, req.target);
  3667. res.status = StatusCode::OK_200;
  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(expected_target.c_str());
  3680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3681. EXPECT_EQ(StatusCode::OK_200, res->status);
  3682. }
  3683. }
  3684. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3685. // `open_stream()` used to skip the path encoding that the buffered send
  3686. // path applies, so the same `path` produced different bytes in the request
  3687. // line depending on which API was used. Assert the two agree.
  3688. Server svr;
  3689. std::string target;
  3690. svr.Get(".*", [&](const Request &req, Response &res) {
  3691. target = req.target;
  3692. res.status = StatusCode::OK_200;
  3693. });
  3694. auto port = svr.bind_to_any_port(HOST);
  3695. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3696. auto se = detail::scope_exit([&] {
  3697. svr.stop();
  3698. thread.join();
  3699. ASSERT_FALSE(svr.is_running());
  3700. });
  3701. svr.wait_until_ready();
  3702. struct {
  3703. const char *path;
  3704. const char *expected;
  3705. } cases[] = {
  3706. {"/a b?x=1", "/a%20b?x=1"},
  3707. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3708. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3709. };
  3710. for (const auto &c : cases) {
  3711. Client cli(HOST, port);
  3712. target.clear();
  3713. auto res = cli.Get(c.path);
  3714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3715. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3716. auto buffered_target = target;
  3717. target.clear();
  3718. auto handle = cli.open_stream("GET", c.path);
  3719. EXPECT_TRUE(handle.is_valid())
  3720. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3721. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3722. }
  3723. }
  3724. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3725. // The `set_path_encode(false)` contract — transmit the supplied target
  3726. // verbatim — must hold for the streaming API too.
  3727. Server svr;
  3728. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3729. std::string target;
  3730. svr.Get("/foo", [&](const Request &req, Response &res) {
  3731. target = req.target;
  3732. res.status = StatusCode::OK_200;
  3733. });
  3734. auto port = svr.bind_to_any_port(HOST);
  3735. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3736. auto se = detail::scope_exit([&] {
  3737. svr.stop();
  3738. thread.join();
  3739. ASSERT_FALSE(svr.is_running());
  3740. });
  3741. svr.wait_until_ready();
  3742. {
  3743. Client cli(HOST, port);
  3744. cli.set_path_encode(false);
  3745. auto handle = cli.open_stream("GET", expected_target);
  3746. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3747. EXPECT_EQ(expected_target, target);
  3748. }
  3749. }
  3750. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3751. // With path encoding enabled a CR/LF in the target is percent-encoded
  3752. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3753. // write_request_line still backstops `set_path_encode(false)`, which is
  3754. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3755. Server svr;
  3756. // Captured before routing: the decoded path contains a newline, which a
  3757. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3758. std::string target;
  3759. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3760. target = req.target;
  3761. res.status = StatusCode::OK_200;
  3762. return Server::HandlerResponse::Handled;
  3763. });
  3764. auto port = svr.bind_to_any_port(HOST);
  3765. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3766. auto se = detail::scope_exit([&] {
  3767. svr.stop();
  3768. thread.join();
  3769. ASSERT_FALSE(svr.is_running());
  3770. });
  3771. svr.wait_until_ready();
  3772. {
  3773. Client cli(HOST, port);
  3774. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3775. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3776. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3777. }
  3778. }
  3779. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3780. // Every control character is percent-encoded, not just CR/LF, so the target
  3781. // passes the request-target check in write_request_line.
  3782. Server svr;
  3783. std::string target;
  3784. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3785. target = req.target;
  3786. res.status = StatusCode::OK_200;
  3787. return Server::HandlerResponse::Handled;
  3788. });
  3789. auto port = svr.bind_to_any_port(HOST);
  3790. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3791. auto se = detail::scope_exit([&] {
  3792. svr.stop();
  3793. thread.join();
  3794. ASSERT_FALSE(svr.is_running());
  3795. });
  3796. svr.wait_until_ready();
  3797. {
  3798. Client cli(HOST, port);
  3799. auto res = cli.Get("/a\tb\x1b\x7f");
  3800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3801. EXPECT_EQ("/a%09b%1B%7F", target);
  3802. }
  3803. }
  3804. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3805. // Nothing may reach the wire: a raw CR/LF target would split the request
  3806. // line and inject headers.
  3807. Server svr;
  3808. // Pre-routing so that "not called" means nothing reached the server at all,
  3809. // rather than merely failing to match a handler pattern.
  3810. auto handler_called = false;
  3811. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3812. handler_called = true;
  3813. res.status = StatusCode::OK_200;
  3814. return Server::HandlerResponse::Handled;
  3815. });
  3816. auto port = svr.bind_to_any_port(HOST);
  3817. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3818. auto se = detail::scope_exit([&] {
  3819. svr.stop();
  3820. thread.join();
  3821. ASSERT_FALSE(svr.is_running());
  3822. });
  3823. svr.wait_until_ready();
  3824. {
  3825. Client cli(HOST, port);
  3826. cli.set_path_encode(false);
  3827. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3828. EXPECT_FALSE(handle.is_valid());
  3829. EXPECT_EQ(Error::Write, handle.error);
  3830. EXPECT_FALSE(handler_called);
  3831. }
  3832. }
  3833. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3834. // Which of the two branches runs is decided by whether the query component
  3835. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3836. // an empty query and must still fall back to building one from
  3837. // `req.params`, while a non-empty query must win over `req.params`.
  3838. Server svr;
  3839. std::string target;
  3840. svr.Get("/foo", [&](const Request &req, Response &res) {
  3841. target = req.target;
  3842. res.status = StatusCode::OK_200;
  3843. });
  3844. auto port = svr.bind_to_any_port(HOST);
  3845. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3846. auto se = detail::scope_exit([&] {
  3847. svr.stop();
  3848. thread.join();
  3849. ASSERT_FALSE(svr.is_running());
  3850. });
  3851. svr.wait_until_ready();
  3852. {
  3853. // Trailing `?` -> empty query component -> `req.params` is used.
  3854. Client cli(HOST, port);
  3855. Request req;
  3856. req.method = "GET";
  3857. req.path = "/foo?";
  3858. req.params.emplace("a", "1");
  3859. target.clear();
  3860. auto res = cli.send(req);
  3861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3862. EXPECT_EQ("/foo?a=1", target);
  3863. }
  3864. {
  3865. // Non-empty query in `req.path` -> `req.params` is not appended.
  3866. Client cli(HOST, port);
  3867. Request req;
  3868. req.method = "GET";
  3869. req.path = "/foo?b=2";
  3870. req.params.emplace("a", "1");
  3871. target.clear();
  3872. auto res = cli.send(req);
  3873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3874. EXPECT_EQ("/foo?b=2", target);
  3875. }
  3876. }
  3877. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3878. Server svr;
  3879. svr.Get("/", [](const Request &req, Response &) {
  3880. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3881. });
  3882. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3883. auto se = detail::scope_exit([&] {
  3884. svr.stop();
  3885. thread.join();
  3886. ASSERT_FALSE(svr.is_running());
  3887. });
  3888. svr.wait_until_ready();
  3889. {
  3890. Client cli(HOST, PORT);
  3891. cli.set_path_encode(false);
  3892. auto res = cli.Get("/?something=%0A");
  3893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3894. EXPECT_EQ(StatusCode::OK_200, res->status);
  3895. }
  3896. }
  3897. TEST(BindServerTest, BindDualStack) {
  3898. Server svr;
  3899. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3900. res.set_content("Hello World!", "text/plain");
  3901. });
  3902. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3903. auto se = detail::scope_exit([&] {
  3904. svr.stop();
  3905. thread.join();
  3906. ASSERT_FALSE(svr.is_running());
  3907. });
  3908. svr.wait_until_ready();
  3909. {
  3910. Client cli("127.0.0.1", PORT);
  3911. auto res = cli.Get("/1");
  3912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3913. EXPECT_EQ(StatusCode::OK_200, res->status);
  3914. EXPECT_EQ("Hello World!", res->body);
  3915. }
  3916. {
  3917. Client cli("::1", PORT);
  3918. auto res = cli.Get("/1");
  3919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3920. EXPECT_EQ(StatusCode::OK_200, res->status);
  3921. EXPECT_EQ("Hello World!", res->body);
  3922. }
  3923. }
  3924. TEST(BindServerTest, BindAndListenSeparately) {
  3925. Server svr;
  3926. int port = svr.bind_to_any_port("0.0.0.0");
  3927. ASSERT_TRUE(svr.is_valid());
  3928. ASSERT_TRUE(port > 0);
  3929. svr.stop();
  3930. }
  3931. // Reports whether anything is still listening on a loopback port. A plain
  3932. // connect() is used instead of a Client request because a socket left bound by
  3933. // mistake accepts the connection into its backlog and never answers, which
  3934. // would hang the test instead of failing it.
  3935. static bool is_loopback_port_accepting(int port) {
  3936. sockaddr_in addr{};
  3937. addr.sin_family = AF_INET;
  3938. addr.sin_port = htons(static_cast<uint16_t>(port));
  3939. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3940. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3941. EXPECT_NE(sock, INVALID_SOCKET);
  3942. if (sock == INVALID_SOCKET) { return false; }
  3943. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3944. static_cast<socklen_t>(sizeof(addr)));
  3945. detail::close_socket(sock);
  3946. return ret == 0;
  3947. }
  3948. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3949. Server svr;
  3950. auto port = svr.bind_to_any_port("127.0.0.1");
  3951. ASSERT_TRUE(port > 0);
  3952. svr.stop();
  3953. // bind_to_any_port() already called listen(2), so until stop() closed the
  3954. // descriptor the port kept accepting connections into the backlog. ASSERT
  3955. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3956. // below blocks forever in the accept loop.
  3957. ASSERT_FALSE(is_loopback_port_accepting(port));
  3958. // Nothing is left to accept on, so listen_after_bind() must report failure
  3959. // instead of returning success without ever serving.
  3960. EXPECT_FALSE(svr.listen_after_bind());
  3961. // The failed listen marks the server decommissioned, so a waiter returns
  3962. // instead of spinning forever.
  3963. svr.wait_until_ready();
  3964. }
  3965. #ifdef CPPHTTPLIB_SSL_ENABLED
  3966. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3967. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3968. CLIENT_CA_CERT_DIR);
  3969. int port = svr.bind_to_any_port("0.0.0.0");
  3970. ASSERT_TRUE(svr.is_valid());
  3971. ASSERT_TRUE(port > 0);
  3972. svr.stop();
  3973. }
  3974. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3975. // or a rejected CustomRoute() registration would not stop the server binding.
  3976. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3977. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3978. CLIENT_CA_CERT_DIR);
  3979. ASSERT_TRUE(svr.is_valid());
  3980. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3981. EXPECT_FALSE(svr.is_valid());
  3982. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3983. }
  3984. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3985. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3986. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3987. int port = svr.bind_to_any_port("0.0.0.0");
  3988. ASSERT_TRUE(svr.is_valid());
  3989. ASSERT_TRUE(port > 0);
  3990. svr.stop();
  3991. }
  3992. TEST(BindServerTest, UpdateCertsPem) {
  3993. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3994. int port = svr.bind_to_any_port("0.0.0.0");
  3995. ASSERT_TRUE(svr.is_valid());
  3996. ASSERT_TRUE(port > 0);
  3997. // Read PEM files
  3998. std::string cert_pem, key_pem, ca_pem;
  3999. read_file(SERVER_CERT_FILE, cert_pem);
  4000. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4001. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4002. // Update server certificates using PEM API
  4003. ASSERT_TRUE(
  4004. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4005. ASSERT_TRUE(svr.is_valid());
  4006. svr.stop();
  4007. }
  4008. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4009. // Start server with client CA (enables client auth)
  4010. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4011. ASSERT_TRUE(svr.is_valid());
  4012. bool handler_called = false;
  4013. svr.Get("/test", [&](const Request &req, Response &res) {
  4014. handler_called = true;
  4015. // Verify client certificate is present
  4016. auto cert = req.peer_cert();
  4017. EXPECT_TRUE(static_cast<bool>(cert));
  4018. res.set_content("ok", "text/plain");
  4019. });
  4020. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4021. auto se = detail::scope_exit([&] {
  4022. svr.stop();
  4023. t.join();
  4024. ASSERT_FALSE(svr.is_running());
  4025. });
  4026. svr.wait_until_ready();
  4027. // Read PEM files
  4028. std::string cert_pem, key_pem, ca_pem;
  4029. read_file(SERVER_CERT_FILE, cert_pem);
  4030. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4031. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4032. // Update server certificates and client CA using PEM API while server running
  4033. ASSERT_TRUE(
  4034. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4035. // Connect with client certificate
  4036. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4037. cli.enable_server_certificate_verification(false);
  4038. cli.set_connection_timeout(30);
  4039. auto res = cli.Get("/test");
  4040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4041. ASSERT_EQ(StatusCode::OK_200, res->status);
  4042. ASSERT_TRUE(handler_called);
  4043. EXPECT_EQ("ok", res->body);
  4044. }
  4045. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4047. ASSERT_TRUE(svr.is_valid());
  4048. svr.Get("/test", [](const Request &, Response &res) {
  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. auto get = [] {
  4059. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4060. cli.enable_server_certificate_verification(false);
  4061. return cli.Get("/test");
  4062. };
  4063. ASSERT_TRUE(get());
  4064. // A CA that did not sign the client's certificate takes the old one's place.
  4065. std::string cert_pem, key_pem, ca_pem;
  4066. read_file(SERVER_CERT_FILE, cert_pem);
  4067. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4068. read_file(SERVER_CERT2_FILE, ca_pem);
  4069. ASSERT_TRUE(
  4070. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4071. EXPECT_FALSE(get());
  4072. }
  4073. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4075. ASSERT_TRUE(svr.is_valid());
  4076. svr.Get("/test", [](const Request &, Response &res) {
  4077. res.set_content("ok", "text/plain");
  4078. });
  4079. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4080. auto se = detail::scope_exit([&] {
  4081. svr.stop();
  4082. t.join();
  4083. ASSERT_FALSE(svr.is_running());
  4084. });
  4085. svr.wait_until_ready();
  4086. // A connection that sends no ClientHello keeps its handshake in progress,
  4087. // once the server has had a moment to start it.
  4088. auto error = Error::Success;
  4089. auto sock = detail::create_client_socket(
  4090. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4091. /*connection_timeout_sec=*/5, 0,
  4092. /*read_timeout_sec=*/5, 0,
  4093. /*write_timeout_sec=*/5, 0, std::string(), error);
  4094. ASSERT_NE(INVALID_SOCKET, sock);
  4095. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4096. std::string cert_pem, key_pem;
  4097. read_file(SERVER_CERT_FILE, cert_pem);
  4098. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4099. auto update = std::async(std::launch::async, [&]() {
  4100. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4101. });
  4102. EXPECT_EQ(std::future_status::timeout,
  4103. update.wait_for(std::chrono::milliseconds(200)));
  4104. detail::close_socket(sock);
  4105. EXPECT_TRUE(update.get());
  4106. SSLClient cli(HOST, PORT);
  4107. cli.enable_server_certificate_verification(false);
  4108. auto res = cli.Get("/test");
  4109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4110. EXPECT_EQ(StatusCode::OK_200, res->status);
  4111. }
  4112. #endif
  4113. TEST(ErrorHandlerTest, ContentLength) {
  4114. Server svr;
  4115. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4116. res.status = StatusCode::OK_200;
  4117. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4118. "text/html"); // <= Content-Length still 13
  4119. });
  4120. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4121. res.set_content("Hello World!\n", "text/plain");
  4122. res.status = 524;
  4123. });
  4124. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4125. auto se = detail::scope_exit([&] {
  4126. svr.stop();
  4127. thread.join();
  4128. ASSERT_FALSE(svr.is_running());
  4129. });
  4130. svr.wait_until_ready();
  4131. {
  4132. Client cli(HOST, PORT);
  4133. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4135. EXPECT_EQ(StatusCode::OK_200, res->status);
  4136. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4137. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4138. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4139. }
  4140. }
  4141. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4142. TEST(ExceptionTest, WithoutExceptionHandler) {
  4143. Server svr;
  4144. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4145. throw std::runtime_error("exception...");
  4146. });
  4147. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4148. throw std::runtime_error("exception\r\n...");
  4149. });
  4150. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4151. auto se = detail::scope_exit([&] {
  4152. svr.stop();
  4153. listen_thread.join();
  4154. ASSERT_FALSE(svr.is_running());
  4155. });
  4156. svr.wait_until_ready();
  4157. Client cli("localhost", PORT);
  4158. {
  4159. auto res = cli.Get("/exception");
  4160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4161. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4162. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4163. }
  4164. {
  4165. auto res = cli.Get("/unknown");
  4166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4167. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4168. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4169. }
  4170. }
  4171. TEST(ExceptionTest, WithExceptionHandler) {
  4172. Server svr;
  4173. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4174. std::exception_ptr ep) {
  4175. EXPECT_FALSE(ep == nullptr);
  4176. try {
  4177. std::rethrow_exception(ep);
  4178. } catch (std::exception &e) {
  4179. EXPECT_EQ("abc", std::string(e.what()));
  4180. } catch (...) {}
  4181. res.status = StatusCode::InternalServerError_500;
  4182. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4183. "text/html"); // <= Content-Length still 13 at this point
  4184. });
  4185. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4186. res.set_content("Hello World!\n", "text/plain");
  4187. throw std::runtime_error("abc");
  4188. });
  4189. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4190. auto se = detail::scope_exit([&] {
  4191. svr.stop();
  4192. thread.join();
  4193. ASSERT_FALSE(svr.is_running());
  4194. });
  4195. svr.wait_until_ready();
  4196. for (size_t i = 0; i < 10; i++) {
  4197. Client cli(HOST, PORT);
  4198. for (size_t j = 0; j < 100; j++) {
  4199. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4201. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4202. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4203. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4204. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4205. }
  4206. cli.set_keep_alive(true);
  4207. for (size_t j = 0; j < 100; j++) {
  4208. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4210. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4211. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4212. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4213. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4214. }
  4215. }
  4216. }
  4217. TEST(ExceptionTest, AndErrorHandler) {
  4218. Server svr;
  4219. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4220. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4221. });
  4222. svr.set_exception_handler(
  4223. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4224. EXPECT_FALSE(ep == nullptr);
  4225. try {
  4226. std::rethrow_exception(ep);
  4227. } catch (std::exception &e) {
  4228. res.set_content(e.what(), "text/html");
  4229. } catch (...) {}
  4230. res.status = StatusCode::InternalServerError_500;
  4231. });
  4232. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4233. throw std::runtime_error("EXCEPTION");
  4234. });
  4235. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4236. res.set_content("ERROR", "text/html");
  4237. res.status = StatusCode::InternalServerError_500;
  4238. });
  4239. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4240. auto se = detail::scope_exit([&] {
  4241. svr.stop();
  4242. thread.join();
  4243. ASSERT_FALSE(svr.is_running());
  4244. });
  4245. svr.wait_until_ready();
  4246. Client cli(HOST, PORT);
  4247. {
  4248. auto res = cli.Get("/exception");
  4249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4250. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4251. EXPECT_EQ("EXCEPTION", res->body);
  4252. }
  4253. {
  4254. auto res = cli.Get("/error");
  4255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4256. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4257. EXPECT_EQ("ERROR", res->body);
  4258. }
  4259. {
  4260. auto res = cli.Get("/invalid");
  4261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4262. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4263. EXPECT_EQ("NOT_FOUND", res->body);
  4264. }
  4265. }
  4266. #endif
  4267. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4268. // process_request() wraps only routing() in a try/catch, so an exception from
  4269. // any other user callback used to unwind into the task queue - which does not
  4270. // catch - and terminate the process. Each test below runs the server on a
  4271. // single worker thread: a guard that catches the exception but still loses the
  4272. // thread would otherwise be hidden by a spare worker serving the follow-up
  4273. // request. Note that a regression here aborts the whole test binary rather
  4274. // than failing one test.
  4275. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4276. Server svr;
  4277. svr.new_task_queue = [] { return new ThreadPool(1); };
  4278. std::atomic<int> reported{0};
  4279. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4280. if (err == Error::UserCallbackException) { reported++; }
  4281. });
  4282. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4283. res.set_content_provider(
  4284. 1024, "text/plain",
  4285. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4286. sink.write("hello", 5);
  4287. throw std::runtime_error("from the content provider");
  4288. });
  4289. });
  4290. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4291. res.set_content("ok", "text/plain");
  4292. });
  4293. auto port = svr.bind_to_any_port(HOST);
  4294. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4295. auto se = detail::scope_exit([&] {
  4296. svr.stop();
  4297. listen_thread.join();
  4298. ASSERT_FALSE(svr.is_running());
  4299. });
  4300. svr.wait_until_ready();
  4301. {
  4302. Client cli(HOST, port);
  4303. cli.set_read_timeout(5, 0);
  4304. EXPECT_FALSE(cli.Get("/throw"));
  4305. }
  4306. EXPECT_TRUE(svr.is_running());
  4307. EXPECT_EQ(1, reported.load());
  4308. // A request on a fresh connection is still served.
  4309. {
  4310. Client cli(HOST, port);
  4311. auto res = cli.Get("/ok");
  4312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4313. EXPECT_EQ(StatusCode::OK_200, res->status);
  4314. EXPECT_EQ("ok", res->body);
  4315. }
  4316. }
  4317. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4318. Server svr;
  4319. svr.new_task_queue = [] { return new ThreadPool(1); };
  4320. std::atomic<bool> should_throw{true};
  4321. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4322. res.set_content("hi", "text/plain");
  4323. });
  4324. svr.set_post_routing_handler(
  4325. [&](const Request & /*req*/, Response & /*res*/) {
  4326. if (should_throw) {
  4327. throw std::runtime_error("from the post-routing handler");
  4328. }
  4329. });
  4330. auto port = svr.bind_to_any_port(HOST);
  4331. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4332. auto se = detail::scope_exit([&] {
  4333. svr.stop();
  4334. listen_thread.join();
  4335. ASSERT_FALSE(svr.is_running());
  4336. });
  4337. svr.wait_until_ready();
  4338. {
  4339. Client cli(HOST, port);
  4340. cli.set_read_timeout(5, 0);
  4341. EXPECT_FALSE(cli.Get("/hi"));
  4342. }
  4343. EXPECT_TRUE(svr.is_running());
  4344. should_throw = false;
  4345. {
  4346. Client cli(HOST, port);
  4347. auto res = cli.Get("/hi");
  4348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4349. EXPECT_EQ(StatusCode::OK_200, res->status);
  4350. EXPECT_EQ("hi", res->body);
  4351. }
  4352. }
  4353. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4354. // The guard reports the caught exception through the error logger, which is
  4355. // a user callback too. A logger that throws has to be contained as well, or
  4356. // the process would terminate from inside the catch.
  4357. Server svr;
  4358. svr.new_task_queue = [] { return new ThreadPool(1); };
  4359. std::atomic<int> reported{0};
  4360. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4361. if (err == Error::UserCallbackException) {
  4362. reported++;
  4363. throw std::runtime_error("from the error logger");
  4364. }
  4365. });
  4366. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4367. res.set_content_provider(
  4368. 1024, "text/plain",
  4369. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4370. sink.write("hello", 5);
  4371. throw std::runtime_error("from the content provider");
  4372. });
  4373. });
  4374. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4375. res.set_content("ok", "text/plain");
  4376. });
  4377. auto port = svr.bind_to_any_port(HOST);
  4378. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4379. auto se = detail::scope_exit([&] {
  4380. svr.stop();
  4381. listen_thread.join();
  4382. ASSERT_FALSE(svr.is_running());
  4383. });
  4384. svr.wait_until_ready();
  4385. {
  4386. Client cli(HOST, port);
  4387. cli.set_read_timeout(5, 0);
  4388. EXPECT_FALSE(cli.Get("/throw"));
  4389. }
  4390. EXPECT_TRUE(svr.is_running());
  4391. EXPECT_EQ(1, reported.load());
  4392. {
  4393. Client cli(HOST, port);
  4394. auto res = cli.Get("/ok");
  4395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4396. EXPECT_EQ(StatusCode::OK_200, res->status);
  4397. EXPECT_EQ("ok", res->body);
  4398. }
  4399. }
  4400. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4401. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4402. // so the exception unwinds through the ws::WebSocket object on its way to
  4403. // the guard. None of the HTTP cases above cross that.
  4404. Server svr;
  4405. svr.new_task_queue = [] { return new ThreadPool(1); };
  4406. std::atomic<int> reported{0};
  4407. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4408. if (err == Error::UserCallbackException) { reported++; }
  4409. });
  4410. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4411. throw std::runtime_error("from the WebSocket handler");
  4412. });
  4413. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4414. res.set_content("ok", "text/plain");
  4415. });
  4416. auto port = svr.bind_to_any_port(HOST);
  4417. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4418. auto se = detail::scope_exit([&] {
  4419. svr.stop();
  4420. listen_thread.join();
  4421. ASSERT_FALSE(svr.is_running());
  4422. });
  4423. svr.wait_until_ready();
  4424. {
  4425. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4426. "/ws");
  4427. auto res = client.connect();
  4428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4429. // The server dropped the connection instead of dying.
  4430. std::string msg;
  4431. EXPECT_FALSE(client.read(msg));
  4432. client.close();
  4433. }
  4434. EXPECT_TRUE(svr.is_running());
  4435. EXPECT_EQ(1, reported.load());
  4436. {
  4437. Client cli(HOST, port);
  4438. auto res = cli.Get("/ok");
  4439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4440. EXPECT_EQ(StatusCode::OK_200, res->status);
  4441. EXPECT_EQ("ok", res->body);
  4442. }
  4443. }
  4444. #ifdef CPPHTTPLIB_SSL_ENABLED
  4445. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4446. // SSLServer::process_and_close_socket() is a separate overload with its own
  4447. // guard, so it is exercised on its own.
  4448. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4449. ASSERT_TRUE(svr.is_valid());
  4450. svr.new_task_queue = [] { return new ThreadPool(1); };
  4451. std::atomic<int> reported{0};
  4452. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4453. if (err == Error::UserCallbackException) { reported++; }
  4454. });
  4455. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4456. res.set_content_provider(
  4457. 1024, "text/plain",
  4458. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4459. sink.write("hello", 5);
  4460. throw std::runtime_error("from the content provider");
  4461. });
  4462. });
  4463. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4464. res.set_content("ok", "text/plain");
  4465. });
  4466. auto port = svr.bind_to_any_port(HOST);
  4467. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4468. auto se = detail::scope_exit([&] {
  4469. svr.stop();
  4470. listen_thread.join();
  4471. ASSERT_FALSE(svr.is_running());
  4472. });
  4473. svr.wait_until_ready();
  4474. {
  4475. SSLClient cli(HOST, port);
  4476. cli.enable_server_certificate_verification(false);
  4477. cli.set_read_timeout(5, 0);
  4478. EXPECT_FALSE(cli.Get("/throw"));
  4479. }
  4480. EXPECT_TRUE(svr.is_running());
  4481. EXPECT_EQ(1, reported.load());
  4482. {
  4483. SSLClient cli(HOST, port);
  4484. cli.enable_server_certificate_verification(false);
  4485. auto res = cli.Get("/ok");
  4486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4487. EXPECT_EQ(StatusCode::OK_200, res->status);
  4488. EXPECT_EQ("ok", res->body);
  4489. }
  4490. }
  4491. #endif
  4492. #endif
  4493. TEST(NoContentTest, ContentLength) {
  4494. Server svr;
  4495. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4496. res.status = StatusCode::NoContent_204;
  4497. });
  4498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4499. auto se = detail::scope_exit([&] {
  4500. svr.stop();
  4501. thread.join();
  4502. ASSERT_FALSE(svr.is_running());
  4503. });
  4504. svr.wait_until_ready();
  4505. {
  4506. Client cli(HOST, PORT);
  4507. auto res = cli.Get("/hi");
  4508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4509. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4510. // RFC 9110 8.6: none in a 204 response
  4511. EXPECT_FALSE(res->has_header("Content-Length"));
  4512. }
  4513. }
  4514. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4515. Server svr;
  4516. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4517. res.set_header("Content-Length", "5");
  4518. res.set_content("hello world", "text/plain");
  4519. });
  4520. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4521. // A body that reads as the last chunk, were it taken as chunked
  4522. res.set_header("Transfer-Encoding", "chunked");
  4523. res.set_content("0\r\n\r\n", "text/plain");
  4524. });
  4525. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4526. res.set_header("Content-Length", "2");
  4527. res.set_content_provider(5, "text/plain",
  4528. [](size_t offset, size_t length, DataSink &sink) {
  4529. sink.write(&"hello"[offset], length);
  4530. return true;
  4531. });
  4532. });
  4533. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4534. res.set_header("Content-Length", "1234");
  4535. });
  4536. thread t = thread([&] { svr.listen(HOST, PORT); });
  4537. auto se = detail::scope_exit([&] {
  4538. svr.stop();
  4539. t.join();
  4540. ASSERT_FALSE(svr.is_running());
  4541. });
  4542. svr.wait_until_ready();
  4543. Client cli(HOST, PORT);
  4544. cli.set_read_timeout(1, 0);
  4545. auto expect_body = [&](const Result &res, const std::string &body) {
  4546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4547. EXPECT_EQ(body, res->body);
  4548. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4549. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4550. };
  4551. Headers identity{{"Accept-Encoding", ""}};
  4552. expect_body(cli.Get("/body", identity), "hello world");
  4553. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4554. expect_body(cli.Get("/body",
  4555. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4556. "he");
  4557. expect_body(cli.Get("/provider", identity), "hello");
  4558. expect_body(cli.Get("/empty", identity), "");
  4559. // A HEAD response may give the length of the body a GET would get.
  4560. auto res = cli.Head("/empty");
  4561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4562. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4563. }
  4564. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4565. Server svr;
  4566. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4567. res.set_content("short", "text/plain");
  4568. });
  4569. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4570. res.body += " with a footer";
  4571. res.set_header("Transfer-Encoding", "chunked");
  4572. });
  4573. thread t = thread([&] { svr.listen(HOST, PORT); });
  4574. auto se = detail::scope_exit([&] {
  4575. svr.stop();
  4576. t.join();
  4577. ASSERT_FALSE(svr.is_running());
  4578. });
  4579. svr.wait_until_ready();
  4580. Client cli(HOST, PORT);
  4581. cli.set_read_timeout(1, 0);
  4582. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4584. EXPECT_EQ("short with a footer", res->body);
  4585. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4586. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4587. }
  4588. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4589. #ifdef CPPHTTPLIB_SSL_ENABLED
  4590. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4591. ASSERT_TRUE(svr.is_valid());
  4592. #else
  4593. Server svr;
  4594. #endif
  4595. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4596. if (req.path == "/routing_handler") {
  4597. res.set_header("PRE_ROUTING", "on");
  4598. res.set_content("Routing Handler", "text/plain");
  4599. return httplib::Server::HandlerResponse::Handled;
  4600. }
  4601. return httplib::Server::HandlerResponse::Unhandled;
  4602. });
  4603. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4604. res.set_content("Error", "text/html");
  4605. });
  4606. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4607. if (req.path == "/routing_handler") {
  4608. res.set_header("POST_ROUTING", "on");
  4609. }
  4610. });
  4611. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4612. res.set_content("Hello World!\n", "text/plain");
  4613. });
  4614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4615. auto se = detail::scope_exit([&] {
  4616. svr.stop();
  4617. thread.join();
  4618. ASSERT_FALSE(svr.is_running());
  4619. });
  4620. svr.wait_until_ready();
  4621. {
  4622. #ifdef CPPHTTPLIB_SSL_ENABLED
  4623. SSLClient cli(HOST, PORT);
  4624. cli.enable_server_certificate_verification(false);
  4625. #else
  4626. Client cli(HOST, PORT);
  4627. #endif
  4628. auto res = cli.Get("/routing_handler");
  4629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4630. EXPECT_EQ(StatusCode::OK_200, res->status);
  4631. EXPECT_EQ("Routing Handler", res->body);
  4632. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4633. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4634. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4635. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4636. }
  4637. {
  4638. #ifdef CPPHTTPLIB_SSL_ENABLED
  4639. SSLClient cli(HOST, PORT);
  4640. cli.enable_server_certificate_verification(false);
  4641. #else
  4642. Client cli(HOST, PORT);
  4643. #endif
  4644. auto res = cli.Get("/hi");
  4645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4646. EXPECT_EQ(StatusCode::OK_200, res->status);
  4647. EXPECT_EQ("Hello World!\n", res->body);
  4648. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4649. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4650. }
  4651. {
  4652. #ifdef CPPHTTPLIB_SSL_ENABLED
  4653. SSLClient cli(HOST, PORT);
  4654. cli.enable_server_certificate_verification(false);
  4655. #else
  4656. Client cli(HOST, PORT);
  4657. #endif
  4658. auto res = cli.Get("/aaa");
  4659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4660. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4661. EXPECT_EQ("Error", res->body);
  4662. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4663. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4664. }
  4665. }
  4666. TEST(RequestHandlerTest, PreRequestHandler) {
  4667. auto route_path = "/user/:user";
  4668. Server svr;
  4669. svr.Get("/hi", [](const Request &, Response &res) {
  4670. res.set_content("hi", "text/plain");
  4671. });
  4672. svr.Get(route_path, [](const Request &req, Response &res) {
  4673. res.set_content(req.path_params.at("user"), "text/plain");
  4674. });
  4675. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4676. if (req.matched_route == route_path) {
  4677. auto user = req.path_params.at("user");
  4678. if (user != "john") {
  4679. res.status = StatusCode::Forbidden_403;
  4680. res.set_content("error", "text/html");
  4681. return Server::HandlerResponse::Handled;
  4682. }
  4683. }
  4684. return Server::HandlerResponse::Unhandled;
  4685. });
  4686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4687. auto se = detail::scope_exit([&] {
  4688. svr.stop();
  4689. thread.join();
  4690. ASSERT_FALSE(svr.is_running());
  4691. });
  4692. svr.wait_until_ready();
  4693. Client cli(HOST, PORT);
  4694. {
  4695. auto res = cli.Get("/hi");
  4696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4697. EXPECT_EQ(StatusCode::OK_200, res->status);
  4698. EXPECT_EQ("hi", res->body);
  4699. }
  4700. {
  4701. auto res = cli.Get("/user/john");
  4702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4703. EXPECT_EQ(StatusCode::OK_200, res->status);
  4704. EXPECT_EQ("john", res->body);
  4705. }
  4706. {
  4707. auto res = cli.Get("/user/invalid-user");
  4708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4709. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4710. EXPECT_EQ("error", res->body);
  4711. }
  4712. }
  4713. // The pre-request handler must run before the request body is read, so a
  4714. // rejected request never forces the server to buffer a (potentially large)
  4715. // body. Here the posted body is larger than the payload limit: if the body
  4716. // were read first the server would answer 413, but because the pre-request
  4717. // handler runs first it answers 403 and the body is never read.
  4718. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4719. Server svr;
  4720. svr.set_payload_max_length(8);
  4721. auto handler_ran = false;
  4722. svr.Post("/reject", [&](const Request &req, Response &res) {
  4723. handler_ran = true;
  4724. res.set_content(req.body, "text/plain");
  4725. });
  4726. svr.Post("/accept", [](const Request &req, Response &res) {
  4727. res.set_content(req.body, "text/plain");
  4728. });
  4729. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4730. if (req.matched_route == "/reject") {
  4731. res.status = StatusCode::Forbidden_403;
  4732. res.set_content("denied", "text/plain");
  4733. return Server::HandlerResponse::Handled;
  4734. }
  4735. return Server::HandlerResponse::Unhandled;
  4736. });
  4737. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4738. auto se = detail::scope_exit([&] {
  4739. svr.stop();
  4740. thread.join();
  4741. ASSERT_FALSE(svr.is_running());
  4742. });
  4743. svr.wait_until_ready();
  4744. Client cli(HOST, PORT);
  4745. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4746. // rejects with 403 before the body is read, so 413 is never reached.
  4747. {
  4748. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4750. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4751. EXPECT_EQ("denied", res->body);
  4752. EXPECT_FALSE(handler_ran);
  4753. }
  4754. // An approved route still reads the body and enforces the payload limit.
  4755. {
  4756. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4758. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4759. }
  4760. }
  4761. TEST(UserDataTest, BasicOperations) {
  4762. httplib::UserData ud;
  4763. // Initially empty
  4764. EXPECT_FALSE(ud.has("key"));
  4765. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4766. // set and get
  4767. ud.set("key", 42);
  4768. EXPECT_TRUE(ud.has("key"));
  4769. auto *p = ud.get<int>("key");
  4770. ASSERT_NE(nullptr, p);
  4771. EXPECT_EQ(42, *p);
  4772. // Type mismatch → nullptr
  4773. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4774. // Overwrite with different type
  4775. ud.set("key", std::string("hello"));
  4776. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4777. auto *s = ud.get<std::string>("key");
  4778. ASSERT_NE(nullptr, s);
  4779. EXPECT_EQ("hello", *s);
  4780. // erase
  4781. ud.erase("key");
  4782. EXPECT_FALSE(ud.has("key"));
  4783. // clear
  4784. ud.set("a", 1);
  4785. ud.set("b", 2);
  4786. ud.clear();
  4787. EXPECT_FALSE(ud.has("a"));
  4788. EXPECT_FALSE(ud.has("b"));
  4789. }
  4790. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4791. struct AuthCtx {
  4792. std::string user_id;
  4793. };
  4794. Server svr;
  4795. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4796. res.user_data.set("auth", AuthCtx{"alice"});
  4797. return Server::HandlerResponse::Unhandled;
  4798. });
  4799. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4800. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4801. ASSERT_NE(nullptr, ctx);
  4802. res.set_content("Hello " + ctx->user_id, "text/plain");
  4803. });
  4804. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4805. auto se = detail::scope_exit([&] {
  4806. svr.stop();
  4807. thread.join();
  4808. ASSERT_FALSE(svr.is_running());
  4809. });
  4810. svr.wait_until_ready();
  4811. Client cli(HOST, PORT);
  4812. auto res = cli.Get("/me");
  4813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. EXPECT_EQ("Hello alice", res->body);
  4816. }
  4817. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4818. struct RoleCtx {
  4819. std::string role;
  4820. };
  4821. Server svr;
  4822. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4823. res.user_data.set("role", RoleCtx{"admin"});
  4824. return Server::HandlerResponse::Unhandled;
  4825. });
  4826. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4827. auto *ctx = res.user_data.get<RoleCtx>("role");
  4828. ASSERT_NE(nullptr, ctx);
  4829. res.set_content(ctx->role, "text/plain");
  4830. });
  4831. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4832. auto se = detail::scope_exit([&] {
  4833. svr.stop();
  4834. thread.join();
  4835. ASSERT_FALSE(svr.is_running());
  4836. });
  4837. svr.wait_until_ready();
  4838. Client cli(HOST, PORT);
  4839. auto res = cli.Get("/role");
  4840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4841. EXPECT_EQ(StatusCode::OK_200, res->status);
  4842. EXPECT_EQ("admin", res->body);
  4843. }
  4844. TEST(InvalidFormatTest, StatusCode) {
  4845. Server svr;
  4846. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4847. res.set_content("Hello World!\n", "text/plain");
  4848. res.status = 9999; // Status should be a three-digit code...
  4849. });
  4850. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4851. auto se = detail::scope_exit([&] {
  4852. svr.stop();
  4853. thread.join();
  4854. ASSERT_FALSE(svr.is_running());
  4855. });
  4856. svr.wait_until_ready();
  4857. {
  4858. Client cli(HOST, PORT);
  4859. auto res = cli.Get("/hi");
  4860. ASSERT_FALSE(res);
  4861. }
  4862. }
  4863. TEST(URLFragmentTest, WithFragment) {
  4864. Server svr;
  4865. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4866. EXPECT_TRUE(req.target == "/hi");
  4867. });
  4868. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4869. auto se = detail::scope_exit([&] {
  4870. svr.stop();
  4871. thread.join();
  4872. ASSERT_FALSE(svr.is_running());
  4873. });
  4874. svr.wait_until_ready();
  4875. {
  4876. Client cli(HOST, PORT);
  4877. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4878. EXPECT_TRUE(res);
  4879. EXPECT_EQ(StatusCode::OK_200, res->status);
  4880. res = cli.Get("/hi%23key1=val1=key2=val2");
  4881. EXPECT_TRUE(res);
  4882. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4883. }
  4884. }
  4885. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  4886. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  4887. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  4888. Server svr;
  4889. std::vector<std::string> targets;
  4890. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  4891. targets.push_back(req.target);
  4892. });
  4893. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4894. auto se = detail::scope_exit([&] {
  4895. svr.stop();
  4896. thread.join();
  4897. ASSERT_FALSE(svr.is_running());
  4898. });
  4899. svr.wait_until_ready();
  4900. Client cli(HOST, PORT);
  4901. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  4902. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  4903. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  4904. // A '?' after the '#' belongs to the fragment, not to the query.
  4905. Request req;
  4906. req.method = "GET";
  4907. req.path = "/hi#f?x=1";
  4908. req.params.emplace("a", "1");
  4909. Response res;
  4910. auto error = Error::Success;
  4911. EXPECT_TRUE(cli.send(req, res, error));
  4912. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  4913. "/hi?a=1"}),
  4914. targets);
  4915. }
  4916. TEST(HeaderWriter, SetHeaderWriter) {
  4917. Server svr;
  4918. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4919. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4920. return detail::write_headers(strm, hdrs);
  4921. });
  4922. svr.Get("/hi", [](const Request &req, Response &res) {
  4923. auto it = req.headers.find("CustomClientHeader");
  4924. EXPECT_TRUE(it != req.headers.end());
  4925. EXPECT_EQ(it->second, "CustomClientValue");
  4926. res.set_content("Hello World!\n", "text/plain");
  4927. });
  4928. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4929. auto se = detail::scope_exit([&] {
  4930. svr.stop();
  4931. thread.join();
  4932. ASSERT_FALSE(svr.is_running());
  4933. });
  4934. svr.wait_until_ready();
  4935. {
  4936. Client cli(HOST, PORT);
  4937. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4938. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4939. return detail::write_headers(strm, hdrs);
  4940. });
  4941. auto res = cli.Get("/hi");
  4942. EXPECT_TRUE(res);
  4943. EXPECT_EQ(StatusCode::OK_200, res->status);
  4944. auto it = res->headers.find("CustomServerHeader");
  4945. EXPECT_TRUE(it != res->headers.end());
  4946. EXPECT_EQ(it->second, "CustomServerValue");
  4947. }
  4948. }
  4949. class ServerTest : public ::testing::Test {
  4950. protected:
  4951. ServerTest()
  4952. : cli_(HOST, PORT)
  4953. #ifdef CPPHTTPLIB_SSL_ENABLED
  4954. ,
  4955. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4956. #endif
  4957. {
  4958. #ifdef CPPHTTPLIB_SSL_ENABLED
  4959. cli_.enable_server_certificate_verification(false);
  4960. #endif
  4961. // Allow LARGE_DATA (100MB) responses
  4962. cli_.set_payload_max_length(200 * 1024 * 1024);
  4963. }
  4964. virtual void SetUp() {
  4965. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4966. svr_.set_payload_max_length(200 * 1024 * 1024);
  4967. svr_.set_mount_point("/", "./www");
  4968. svr_.set_mount_point("/mount", "./www2");
  4969. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4970. svr_.Get("/hi",
  4971. [&](const Request & /*req*/, Response &res) {
  4972. res.set_content("Hello World!", "text/plain");
  4973. })
  4974. .Get("/file_content",
  4975. [&](const Request & /*req*/, Response &res) {
  4976. res.set_file_content("./www/dir/test.html");
  4977. })
  4978. .Get("/file_content_with_content_type",
  4979. [&](const Request & /*req*/, Response &res) {
  4980. res.set_file_content("./www/file", "text/plain");
  4981. })
  4982. .Get("/invalid_file_content",
  4983. [&](const Request & /*req*/, Response &res) {
  4984. res.set_file_content("./www/dir/invalid_file_path");
  4985. })
  4986. .Get("/http_response_splitting",
  4987. [&](const Request & /*req*/, Response &res) {
  4988. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4989. EXPECT_EQ(0U, res.headers.size());
  4990. EXPECT_FALSE(res.has_header("a"));
  4991. res.set_header("a", "1\nSet-Cookie: a=1");
  4992. EXPECT_EQ(0U, res.headers.size());
  4993. EXPECT_FALSE(res.has_header("a"));
  4994. res.set_header("a", "1\rSet-Cookie: a=1");
  4995. EXPECT_EQ(0U, res.headers.size());
  4996. EXPECT_FALSE(res.has_header("a"));
  4997. res.set_header("a\r\nb", "0");
  4998. EXPECT_EQ(0U, res.headers.size());
  4999. EXPECT_FALSE(res.has_header("a"));
  5000. res.set_header("a\rb", "0");
  5001. EXPECT_EQ(0U, res.headers.size());
  5002. EXPECT_FALSE(res.has_header("a"));
  5003. res.set_header("a\nb", "0");
  5004. EXPECT_EQ(0U, res.headers.size());
  5005. EXPECT_FALSE(res.has_header("a"));
  5006. res.set_redirect("1\r\nSet-Cookie: a=1");
  5007. EXPECT_EQ(0U, res.headers.size());
  5008. EXPECT_FALSE(res.has_header("Location"));
  5009. })
  5010. .Get("/slow",
  5011. [&](const Request & /*req*/, Response &res) {
  5012. std::this_thread::sleep_for(std::chrono::seconds(4));
  5013. res.set_content("slow", "text/plain");
  5014. })
  5015. #if 0
  5016. .Post("/slowpost",
  5017. [&](const Request & /*req*/, Response &res) {
  5018. std::this_thread::sleep_for(std::chrono::seconds(2));
  5019. res.set_content("slow", "text/plain");
  5020. })
  5021. #endif
  5022. .Get("/remote_addr",
  5023. [&](const Request &req, Response &res) {
  5024. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5025. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5026. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5027. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5028. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5029. #endif
  5030. res.set_content(req.remote_addr, "text/plain");
  5031. })
  5032. .Get("/local_addr",
  5033. [&](const Request &req, Response &res) {
  5034. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5035. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5036. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5037. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5038. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5039. #endif
  5040. auto local_addr = req.local_addr;
  5041. auto local_port = std::to_string(req.local_port);
  5042. res.set_content(local_addr.append(":").append(local_port),
  5043. "text/plain");
  5044. })
  5045. .Get("/endwith%",
  5046. [&](const Request & /*req*/, Response &res) {
  5047. res.set_content("Hello World!", "text/plain");
  5048. })
  5049. .Get("/a\\+\\+b",
  5050. [&](const Request &req, Response &res) {
  5051. ASSERT_TRUE(req.has_param("a +b"));
  5052. auto val = req.get_param_value("a +b");
  5053. res.set_content(val, "text/plain");
  5054. })
  5055. .Get("/", [&](const Request & /*req*/,
  5056. Response &res) { res.set_redirect("/hi"); })
  5057. .Post("/1",
  5058. [](const Request & /*req*/, Response &res) {
  5059. res.set_redirect("/2", StatusCode::SeeOther_303);
  5060. })
  5061. .Get("/2",
  5062. [](const Request & /*req*/, Response &res) {
  5063. res.set_content("redirected.", "text/plain");
  5064. res.status = StatusCode::OK_200;
  5065. })
  5066. .Post("/person",
  5067. [&](const Request &req, Response &res) {
  5068. if (req.has_param("name") && req.has_param("note")) {
  5069. persons_[req.get_param_value("name")] =
  5070. req.get_param_value("note");
  5071. } else {
  5072. res.status = StatusCode::BadRequest_400;
  5073. }
  5074. })
  5075. .Put("/person",
  5076. [&](const Request &req, Response &res) {
  5077. if (req.has_param("name") && req.has_param("note")) {
  5078. persons_[req.get_param_value("name")] =
  5079. req.get_param_value("note");
  5080. } else {
  5081. res.status = StatusCode::BadRequest_400;
  5082. }
  5083. })
  5084. .Get("/person/(.*)",
  5085. [&](const Request &req, Response &res) {
  5086. string name = req.matches[1];
  5087. if (persons_.find(name) != persons_.end()) {
  5088. auto note = persons_[name];
  5089. res.set_content(note, "text/plain");
  5090. } else {
  5091. res.status = StatusCode::NotFound_404;
  5092. }
  5093. })
  5094. .Delete("/person",
  5095. [&](const Request &req, Response &res) {
  5096. if (req.has_param("name")) {
  5097. string name = req.get_param_value("name");
  5098. if (persons_.find(name) != persons_.end()) {
  5099. persons_.erase(name);
  5100. res.set_content("DELETED", "text/plain");
  5101. } else {
  5102. res.status = StatusCode::NotFound_404;
  5103. }
  5104. } else {
  5105. res.status = StatusCode::BadRequest_400;
  5106. }
  5107. })
  5108. .Post("/x-www-form-urlencoded-json",
  5109. [&](const Request &req, Response &res) {
  5110. auto json = req.get_param_value("json");
  5111. ASSERT_EQ(JSON_DATA, json);
  5112. res.set_content(json, "appliation/json");
  5113. res.status = StatusCode::OK_200;
  5114. })
  5115. .Get("/streamed-chunked",
  5116. [&](const Request & /*req*/, Response &res) {
  5117. res.set_chunked_content_provider(
  5118. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5119. sink.os << "123";
  5120. sink.os << "456";
  5121. sink.os << "789";
  5122. sink.done();
  5123. return true;
  5124. });
  5125. })
  5126. .Get("/streamed-chunked-with-prohibited-trailer",
  5127. [&](const Request & /*req*/, Response &res) {
  5128. auto i = new int(0);
  5129. // Declare both a prohibited trailer (Content-Length) and an
  5130. // allowed one
  5131. res.set_header("Trailer", "Content-Length, X-Allowed");
  5132. res.set_chunked_content_provider(
  5133. "text/plain",
  5134. [i](size_t /*offset*/, DataSink &sink) {
  5135. switch (*i) {
  5136. case 0: sink.os << "123"; break;
  5137. case 1: sink.os << "456"; break;
  5138. case 2: sink.os << "789"; break;
  5139. case 3: {
  5140. sink.done_with_trailer(
  5141. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5142. } break;
  5143. }
  5144. (*i)++;
  5145. return true;
  5146. },
  5147. [i](bool success) {
  5148. EXPECT_TRUE(success);
  5149. delete i;
  5150. });
  5151. })
  5152. .Get("/streamed-chunked2",
  5153. [&](const Request & /*req*/, Response &res) {
  5154. auto i = new int(0);
  5155. res.set_chunked_content_provider(
  5156. "text/plain",
  5157. [i](size_t /*offset*/, DataSink &sink) {
  5158. switch (*i) {
  5159. case 0: sink.os << "123"; break;
  5160. case 1: sink.os << "456"; break;
  5161. case 2: sink.os << "789"; break;
  5162. case 3: sink.done(); break;
  5163. }
  5164. (*i)++;
  5165. return true;
  5166. },
  5167. [i](bool success) {
  5168. EXPECT_TRUE(success);
  5169. delete i;
  5170. });
  5171. })
  5172. .Get("/streamed-chunked-with-trailer",
  5173. [&](const Request & /*req*/, Response &res) {
  5174. auto i = new int(0);
  5175. res.set_header("Trailer", "Dummy1, Dummy2");
  5176. res.set_chunked_content_provider(
  5177. "text/plain",
  5178. [i](size_t /*offset*/, DataSink &sink) {
  5179. switch (*i) {
  5180. case 0: sink.os << "123"; break;
  5181. case 1: sink.os << "456"; break;
  5182. case 2: sink.os << "789"; break;
  5183. case 3: {
  5184. sink.done_with_trailer(
  5185. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5186. } break;
  5187. }
  5188. (*i)++;
  5189. return true;
  5190. },
  5191. [i](bool success) {
  5192. EXPECT_TRUE(success);
  5193. delete i;
  5194. });
  5195. })
  5196. .Get("/streamed",
  5197. [&](const Request & /*req*/, Response &res) {
  5198. res.set_content_provider(
  5199. 6, "text/plain",
  5200. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5201. sink.os << (offset < 3 ? "a" : "b");
  5202. return true;
  5203. });
  5204. })
  5205. .Get("/streamed-without-length",
  5206. [&](const Request & /*req*/, Response &res) {
  5207. auto data = new std::string("abcdefg");
  5208. res.set_content_provider(
  5209. "text/plain",
  5210. [data](size_t offset, DataSink &sink) {
  5211. if (offset < data->size()) {
  5212. sink.os << data->substr(offset);
  5213. }
  5214. sink.done();
  5215. return true;
  5216. },
  5217. [data](bool success) {
  5218. EXPECT_TRUE(success);
  5219. delete data;
  5220. });
  5221. })
  5222. .Get("/streamed-with-range",
  5223. [&](const Request &req, Response &res) {
  5224. auto data = new std::string("abcdefg");
  5225. // An explicit status keeps the server from picking the 206 it
  5226. // would otherwise choose for a ranged request, so the response
  5227. // is not a partial representation.
  5228. auto status = req.get_param_value("status");
  5229. if (status == "200") {
  5230. res.status = StatusCode::OK_200;
  5231. } else if (status == "403") {
  5232. res.status = StatusCode::Forbidden_403;
  5233. }
  5234. res.set_content_provider(
  5235. data->size(), "text/plain",
  5236. [data](size_t offset, size_t length, DataSink &sink) {
  5237. size_t DATA_CHUNK_SIZE = 4;
  5238. const auto &d = *data;
  5239. auto out_len =
  5240. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5241. auto ret =
  5242. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5243. EXPECT_TRUE(ret);
  5244. return true;
  5245. },
  5246. [data, &req](bool success) {
  5247. EXPECT_EQ(success, !req.has_param("error"));
  5248. delete data;
  5249. });
  5250. })
  5251. .Get("/streamed-cancel",
  5252. [&](const Request & /*req*/, Response &res) {
  5253. res.set_content_provider(
  5254. size_t(-1), "text/plain",
  5255. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5256. sink.os << "data_chunk";
  5257. return true;
  5258. });
  5259. })
  5260. .Get("/regex-with-delimiter",
  5261. [&](const Request &req, Response & /*res*/) {
  5262. ASSERT_TRUE(req.has_param("key"));
  5263. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5264. })
  5265. .Get("/with-range",
  5266. [&](const Request & /*req*/, Response &res) {
  5267. res.set_content("abcdefg", "text/plain");
  5268. })
  5269. .Get("/test-start-time",
  5270. [&](const Request &req, Response & /*res*/) {
  5271. EXPECT_NE(req.start_time_,
  5272. std::chrono::steady_clock::time_point::min());
  5273. })
  5274. .Get("/with-range-customized-response",
  5275. [&](const Request & /*req*/, Response &res) {
  5276. res.status = StatusCode::BadRequest_400;
  5277. res.set_content(JSON_DATA, "application/json");
  5278. })
  5279. .Post("/chunked",
  5280. [&](const Request &req, Response & /*res*/) {
  5281. EXPECT_EQ(req.body, "dechunked post body");
  5282. })
  5283. .Post("/large-chunked",
  5284. [&](const Request &req, Response & /*res*/) {
  5285. std::string expected(6 * 30 * 1024u, 'a');
  5286. EXPECT_EQ(req.body, expected);
  5287. })
  5288. .Post("/multipart",
  5289. [&](const Request &req, Response & /*res*/) {
  5290. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5291. req.form.get_field_count("text2") +
  5292. req.form.get_field_count("file3") +
  5293. req.form.get_field_count("file4"));
  5294. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5295. req.form.get_file_count("file2"));
  5296. ASSERT_TRUE(!req.form.has_file("???"));
  5297. ASSERT_TRUE(!req.form.has_field("???"));
  5298. ASSERT_TRUE(req.body.empty());
  5299. {
  5300. const auto &text = req.form.get_field("text1");
  5301. EXPECT_EQ("text default", text);
  5302. }
  5303. {
  5304. const auto &text = req.form.get_field("text2");
  5305. EXPECT_EQ("aωb", text);
  5306. }
  5307. {
  5308. const auto &file = req.form.get_file("file1");
  5309. EXPECT_EQ("hello.txt", file.filename);
  5310. EXPECT_EQ("text/plain", file.content_type);
  5311. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5312. }
  5313. {
  5314. const auto &file = req.form.get_file("file2");
  5315. EXPECT_EQ("world.json", file.filename);
  5316. EXPECT_EQ("application/json", file.content_type);
  5317. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5318. }
  5319. {
  5320. const auto &text = req.form.get_field("file3");
  5321. EXPECT_EQ(0u, text.size());
  5322. }
  5323. {
  5324. const auto &text = req.form.get_field("file4");
  5325. EXPECT_EQ(0u, text.size());
  5326. }
  5327. })
  5328. .Post("/multipart/multi_file_values",
  5329. [&](const Request &req, Response & /*res*/) {
  5330. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5331. req.form.get_field_count("multi_text1"));
  5332. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5333. ASSERT_TRUE(!req.form.has_file("???"));
  5334. ASSERT_TRUE(!req.form.has_field("???"));
  5335. ASSERT_TRUE(req.body.empty());
  5336. {
  5337. const auto &text = req.form.get_field("text");
  5338. EXPECT_EQ("default text", text);
  5339. }
  5340. {
  5341. const auto &text1_values = req.form.get_fields("multi_text1");
  5342. EXPECT_EQ(2u, text1_values.size());
  5343. EXPECT_EQ("aaaaa", text1_values[0]);
  5344. EXPECT_EQ("bbbbb", text1_values[1]);
  5345. }
  5346. {
  5347. const auto &file1_values = req.form.get_files("multi_file1");
  5348. EXPECT_EQ(2u, file1_values.size());
  5349. auto file1 = file1_values[0];
  5350. EXPECT_EQ(file1.filename, "hello.txt");
  5351. EXPECT_EQ(file1.content_type, "text/plain");
  5352. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5353. auto file2 = file1_values[1];
  5354. EXPECT_EQ(file2.filename, "world.json");
  5355. EXPECT_EQ(file2.content_type, "application/json");
  5356. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5357. }
  5358. })
  5359. .Post("/empty",
  5360. [&](const Request &req, Response &res) {
  5361. EXPECT_EQ(req.body, "");
  5362. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5363. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5364. res.set_content("empty", "text/plain");
  5365. })
  5366. .Post("/empty-no-content-type",
  5367. [&](const Request &req, Response &res) {
  5368. EXPECT_EQ(req.body, "");
  5369. EXPECT_FALSE(req.has_header("Content-Type"));
  5370. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5371. res.set_content("empty-no-content-type", "text/plain");
  5372. })
  5373. .Post("/path-only",
  5374. [&](const Request &req, Response &res) {
  5375. EXPECT_EQ(req.body, "");
  5376. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5377. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5378. res.set_content("path-only", "text/plain");
  5379. })
  5380. .Post("/path-headers-only",
  5381. [&](const Request &req, Response &res) {
  5382. EXPECT_EQ(req.body, "");
  5383. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5384. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5385. EXPECT_EQ("world", req.get_header_value("hello"));
  5386. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5387. res.set_content("path-headers-only", "text/plain");
  5388. })
  5389. .Post("/post-large",
  5390. [&](const Request &req, Response &res) {
  5391. EXPECT_EQ(req.body, LARGE_DATA);
  5392. res.set_content(req.body, "text/plain");
  5393. })
  5394. .Post("/post-loopback",
  5395. [&](const Request &, Response &res,
  5396. ContentReader const &content_reader) {
  5397. std::string body;
  5398. content_reader([&](const char *data, size_t data_length) {
  5399. body.append(data, data_length);
  5400. return true;
  5401. });
  5402. res.set_content(body, "text/plain");
  5403. })
  5404. .Put("/put-loopback",
  5405. [&](const Request &, Response &res,
  5406. ContentReader const &content_reader) {
  5407. std::string body;
  5408. content_reader([&](const char *data, size_t data_length) {
  5409. body.append(data, data_length);
  5410. return true;
  5411. });
  5412. res.set_content(body, "text/plain");
  5413. })
  5414. .Patch("/patch-loopback",
  5415. [&](const Request &, Response &res,
  5416. ContentReader const &content_reader) {
  5417. std::string body;
  5418. content_reader([&](const char *data, size_t data_length) {
  5419. body.append(data, data_length);
  5420. return true;
  5421. });
  5422. res.set_content(body, "text/plain");
  5423. })
  5424. .Put("/empty-no-content-type",
  5425. [&](const Request &req, Response &res) {
  5426. EXPECT_EQ(req.body, "");
  5427. EXPECT_FALSE(req.has_header("Content-Type"));
  5428. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5429. res.set_content("empty-no-content-type", "text/plain");
  5430. })
  5431. .Put("/put",
  5432. [&](const Request &req, Response &res) {
  5433. EXPECT_EQ(req.body, "PUT");
  5434. res.set_content(req.body, "text/plain");
  5435. })
  5436. .Put("/put-large",
  5437. [&](const Request &req, Response &res) {
  5438. EXPECT_EQ(req.body, LARGE_DATA);
  5439. res.set_content(req.body, "text/plain");
  5440. })
  5441. .Patch("/patch",
  5442. [&](const Request &req, Response &res) {
  5443. EXPECT_EQ(req.body, "PATCH");
  5444. res.set_content(req.body, "text/plain");
  5445. })
  5446. .Delete("/delete",
  5447. [&](const Request & /*req*/, Response &res) {
  5448. res.set_content("DELETE", "text/plain");
  5449. })
  5450. .Delete("/delete-body",
  5451. [&](const Request &req, Response &res) {
  5452. EXPECT_EQ(req.body, "content");
  5453. res.set_content(req.body, "text/plain");
  5454. })
  5455. .Options(R"(\*)",
  5456. [&](const Request & /*req*/, Response &res) {
  5457. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5458. })
  5459. .CustomRoute("PROPFIND", "/dav/:id",
  5460. [&](const Request &req, Response &res) {
  5461. res.set_header("x-body-size",
  5462. std::to_string(req.body.size()));
  5463. res.set_header("x-matched-route", req.matched_route);
  5464. res.set_header("x-dav-id", req.path_params.at("id"));
  5465. res.status = StatusCode::MultiStatus_207;
  5466. res.set_content(req.body, "application/xml");
  5467. })
  5468. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5469. [&](const Request &req, Response &res) {
  5470. res.set_header("x-dav-match", req.matches[1]);
  5471. res.status = StatusCode::MultiStatus_207;
  5472. })
  5473. .CustomRoute("MKCOL", "/dav-mkcol",
  5474. [&](const Request &req, Response &res) {
  5475. EXPECT_TRUE(req.body.empty());
  5476. res.status = StatusCode::Created_201;
  5477. })
  5478. .CustomRoute(
  5479. "REPORT", "/dav-report",
  5480. [&](const Request & /*req*/, Response &res,
  5481. const ContentReader &content_reader) {
  5482. std::string body;
  5483. content_reader([&](const char *data, size_t data_length) {
  5484. body.append(data, data_length);
  5485. return true;
  5486. });
  5487. res.set_header("x-body-size", std::to_string(body.size()));
  5488. res.status = StatusCode::MultiStatus_207;
  5489. res.set_content(body, "application/xml");
  5490. })
  5491. .Get("/request-target",
  5492. [&](const Request &req, Response & /*res*/) {
  5493. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5494. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5495. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5496. })
  5497. .Get("/long-query-value",
  5498. [&](const Request &req, Response & /*res*/) {
  5499. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5500. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5501. })
  5502. .Get("/too-long-query-value",
  5503. [&](const Request &req, Response & /*res*/) {
  5504. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5505. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5506. })
  5507. .Get("/array-param",
  5508. [&](const Request &req, Response & /*res*/) {
  5509. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5510. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5511. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5512. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5513. })
  5514. .Get("/array-param-values",
  5515. [&](const Request &req, Response & /*res*/) {
  5516. auto values = req.get_param_values("array");
  5517. EXPECT_EQ(3u, values.size());
  5518. EXPECT_EQ("value1", values[0]);
  5519. EXPECT_EQ("value2", values[1]);
  5520. EXPECT_EQ("value3", values[2]);
  5521. auto empty = req.get_param_values("nonexistent");
  5522. EXPECT_TRUE(empty.empty());
  5523. })
  5524. .Post("/validate-no-multiple-headers",
  5525. [&](const Request &req, Response & /*res*/) {
  5526. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5527. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5528. })
  5529. .Post("/content_receiver",
  5530. [&](const Request &req, Response &res,
  5531. const ContentReader &content_reader) {
  5532. if (req.is_multipart_form_data()) {
  5533. std::vector<FormData> items;
  5534. content_reader(
  5535. [&](const FormData &file) {
  5536. items.push_back(file);
  5537. return true;
  5538. },
  5539. [&](const char *data, size_t data_length) {
  5540. items.back().content.append(data, data_length);
  5541. return true;
  5542. });
  5543. EXPECT_EQ(5u, items.size());
  5544. {
  5545. const auto &file = get_file_value(items, "text1");
  5546. EXPECT_TRUE(file.filename.empty());
  5547. EXPECT_EQ("text default", file.content);
  5548. }
  5549. {
  5550. const auto &file = get_file_value(items, "text2");
  5551. EXPECT_TRUE(file.filename.empty());
  5552. EXPECT_EQ("aωb", file.content);
  5553. }
  5554. {
  5555. const auto &file = get_file_value(items, "file1");
  5556. EXPECT_EQ("hello.txt", file.filename);
  5557. EXPECT_EQ("text/plain", file.content_type);
  5558. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5559. }
  5560. {
  5561. const auto &file = get_file_value(items, "file2");
  5562. EXPECT_EQ("world.json", file.filename);
  5563. EXPECT_EQ("application/json", file.content_type);
  5564. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5565. }
  5566. {
  5567. const auto &file = get_file_value(items, "file3");
  5568. EXPECT_TRUE(file.filename.empty());
  5569. EXPECT_EQ("application/octet-stream", file.content_type);
  5570. EXPECT_EQ(0u, file.content.size());
  5571. }
  5572. } else {
  5573. std::string body;
  5574. content_reader([&](const char *data, size_t data_length) {
  5575. EXPECT_EQ(7U, data_length);
  5576. body.append(data, data_length);
  5577. return true;
  5578. });
  5579. EXPECT_EQ(body, "content");
  5580. res.set_content(body, "text/plain");
  5581. }
  5582. })
  5583. .Put("/content_receiver",
  5584. [&](const Request & /*req*/, Response &res,
  5585. const ContentReader &content_reader) {
  5586. std::string body;
  5587. content_reader([&](const char *data, size_t data_length) {
  5588. body.append(data, data_length);
  5589. return true;
  5590. });
  5591. EXPECT_EQ(body, "content");
  5592. res.set_content(body, "text/plain");
  5593. })
  5594. .Patch("/content_receiver",
  5595. [&](const Request & /*req*/, Response &res,
  5596. const ContentReader &content_reader) {
  5597. std::string body;
  5598. content_reader([&](const char *data, size_t data_length) {
  5599. body.append(data, data_length);
  5600. return true;
  5601. });
  5602. EXPECT_EQ(body, "content");
  5603. res.set_content(body, "text/plain");
  5604. })
  5605. .Post("/query-string-and-body",
  5606. [&](const Request &req, Response & /*res*/) {
  5607. ASSERT_TRUE(req.has_param("key"));
  5608. EXPECT_EQ(req.get_param_value("key"), "value");
  5609. EXPECT_EQ(req.body, "content");
  5610. })
  5611. .Get("/last-request",
  5612. [&](const Request &req, Response & /*res*/) {
  5613. EXPECT_EQ("close", req.get_header_value("Connection"));
  5614. })
  5615. .Get(R"(/redirect/(\d+))",
  5616. [&](const Request &req, Response &res) {
  5617. auto num = std::stoi(req.matches[1]) + 1;
  5618. std::string url = "/redirect/" + std::to_string(num);
  5619. res.set_redirect(url);
  5620. })
  5621. .Post("/binary",
  5622. [&](const Request &req, Response &res) {
  5623. EXPECT_EQ(4U, req.body.size());
  5624. EXPECT_EQ("application/octet-stream",
  5625. req.get_header_value("Content-Type"));
  5626. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5627. res.set_content(req.body, "application/octet-stream");
  5628. })
  5629. .Put("/binary",
  5630. [&](const Request &req, Response &res) {
  5631. EXPECT_EQ(4U, req.body.size());
  5632. EXPECT_EQ("application/octet-stream",
  5633. req.get_header_value("Content-Type"));
  5634. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5635. res.set_content(req.body, "application/octet-stream");
  5636. })
  5637. .Patch("/binary",
  5638. [&](const Request &req, Response &res) {
  5639. EXPECT_EQ(4U, req.body.size());
  5640. EXPECT_EQ("application/octet-stream",
  5641. req.get_header_value("Content-Type"));
  5642. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5643. res.set_content(req.body, "application/octet-stream");
  5644. })
  5645. .Delete("/binary",
  5646. [&](const Request &req, Response &res) {
  5647. EXPECT_EQ(4U, req.body.size());
  5648. EXPECT_EQ("application/octet-stream",
  5649. req.get_header_value("Content-Type"));
  5650. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5651. res.set_content(req.body, "application/octet-stream");
  5652. })
  5653. .Get("/issue1772",
  5654. [&](const Request & /*req*/, Response &res) {
  5655. res.status = 401;
  5656. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5657. })
  5658. .Delete("/issue609",
  5659. [](const httplib::Request &, httplib::Response &res,
  5660. const httplib::ContentReader &) {
  5661. res.set_content("ok", "text/plain");
  5662. })
  5663. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5664. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5665. .Get("/compress",
  5666. [&](const Request & /*req*/, Response &res) {
  5667. res.set_content(
  5668. "12345678901234567890123456789012345678901234567890123456789"
  5669. "01234567890123456789012345678901234567890",
  5670. "text/plain");
  5671. })
  5672. .Get("/compress-with-charset",
  5673. [&](const Request & /*req*/, Response &res) {
  5674. res.set_content(
  5675. "12345678901234567890123456789012345678901234567890123456789"
  5676. "01234567890123456789012345678901234567890",
  5677. "application/json; charset=utf-8");
  5678. })
  5679. .Get("/nocompress",
  5680. [&](const Request & /*req*/, Response &res) {
  5681. res.set_content(
  5682. "12345678901234567890123456789012345678901234567890123456789"
  5683. "01234567890123456789012345678901234567890",
  5684. "application/octet-stream");
  5685. })
  5686. .Post("/compress-multipart",
  5687. [&](const Request &req, Response & /*res*/) {
  5688. EXPECT_EQ(2u, req.form.fields.size());
  5689. ASSERT_TRUE(!req.form.has_field("???"));
  5690. {
  5691. const auto &text = req.form.get_field("key1");
  5692. EXPECT_EQ("test", text);
  5693. }
  5694. {
  5695. const auto &text = req.form.get_field("key2");
  5696. EXPECT_EQ("--abcdefg123", text);
  5697. }
  5698. })
  5699. #endif
  5700. ;
  5701. persons_["john"] = "programmer";
  5702. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5703. svr_.wait_until_ready();
  5704. }
  5705. virtual void TearDown() {
  5706. svr_.stop();
  5707. if (!request_threads_.empty()) {
  5708. std::this_thread::sleep_for(std::chrono::seconds(1));
  5709. for (auto &t : request_threads_) {
  5710. t.join();
  5711. }
  5712. }
  5713. t_.join();
  5714. }
  5715. map<string, string> persons_;
  5716. #ifdef CPPHTTPLIB_SSL_ENABLED
  5717. SSLClient cli_;
  5718. SSLServer svr_;
  5719. #else
  5720. Client cli_;
  5721. Server svr_;
  5722. #endif
  5723. thread t_;
  5724. std::vector<thread> request_threads_;
  5725. };
  5726. TEST_F(ServerTest, GetMethod200) {
  5727. auto res = cli_.Get("/hi");
  5728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5729. EXPECT_EQ("HTTP/1.1", res->version);
  5730. EXPECT_EQ(StatusCode::OK_200, res->status);
  5731. EXPECT_EQ("OK", res->reason);
  5732. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5733. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5734. EXPECT_EQ("Hello World!", res->body);
  5735. }
  5736. TEST_F(ServerTest, GetEmptyFile) {
  5737. auto res = cli_.Get("/empty_file");
  5738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5739. EXPECT_EQ(StatusCode::OK_200, res->status);
  5740. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5741. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5742. EXPECT_EQ("", res->body);
  5743. }
  5744. TEST_F(ServerTest, GetFileContent) {
  5745. auto res = cli_.Get("/file_content");
  5746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5747. EXPECT_EQ(StatusCode::OK_200, res->status);
  5748. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5749. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5750. EXPECT_EQ("test.html", res->body);
  5751. }
  5752. TEST_F(ServerTest, GetFileContentWithRange) {
  5753. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5755. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5756. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5757. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5758. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5759. EXPECT_EQ("est", res->body);
  5760. }
  5761. TEST_F(ServerTest, GetFileContentWithContentType) {
  5762. auto res = cli_.Get("/file_content_with_content_type");
  5763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5764. EXPECT_EQ(StatusCode::OK_200, res->status);
  5765. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5766. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5767. EXPECT_EQ("file\n", res->body);
  5768. }
  5769. TEST_F(ServerTest, GetInvalidFileContent) {
  5770. auto res = cli_.Get("/invalid_file_content");
  5771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5772. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5773. }
  5774. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5775. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5777. EXPECT_EQ("HTTP/1.1", res->version);
  5778. EXPECT_EQ(StatusCode::OK_200, res->status);
  5779. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5780. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5781. EXPECT_EQ("Hello World!", res->body);
  5782. }
  5783. TEST_F(ServerTest, GetMethod302) {
  5784. auto res = cli_.Get("/");
  5785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5786. EXPECT_EQ(StatusCode::Found_302, res->status);
  5787. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5788. }
  5789. TEST_F(ServerTest, GetMethod302Redirect) {
  5790. cli_.set_follow_location(true);
  5791. auto res = cli_.Get("/");
  5792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5793. EXPECT_EQ(StatusCode::OK_200, res->status);
  5794. EXPECT_EQ("Hello World!", res->body);
  5795. EXPECT_EQ("/hi", res->location);
  5796. }
  5797. TEST_F(ServerTest, GetMethod404) {
  5798. auto res = cli_.Get("/invalid");
  5799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5800. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5801. }
  5802. TEST_F(ServerTest, HeadMethod200) {
  5803. auto res = cli_.Head("/hi");
  5804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5805. EXPECT_EQ(StatusCode::OK_200, res->status);
  5806. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5807. EXPECT_TRUE(res->body.empty());
  5808. }
  5809. TEST_F(ServerTest, HeadMethod200Static) {
  5810. auto res = cli_.Head("/mount/dir/index.html");
  5811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5812. EXPECT_EQ(StatusCode::OK_200, res->status);
  5813. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5814. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5815. EXPECT_TRUE(res->body.empty());
  5816. }
  5817. TEST_F(ServerTest, HeadMethod404) {
  5818. auto res = cli_.Head("/invalid");
  5819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5821. EXPECT_TRUE(res->body.empty());
  5822. }
  5823. TEST_F(ServerTest, GetMethodPersonJohn) {
  5824. auto res = cli_.Get("/person/john");
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. EXPECT_EQ(StatusCode::OK_200, res->status);
  5827. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5828. EXPECT_EQ("programmer", res->body);
  5829. }
  5830. TEST_F(ServerTest, PostMethod1) {
  5831. auto res = cli_.Get("/person/john1");
  5832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5833. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5834. res = cli_.Post("/person", "name=john1&note=coder",
  5835. "application/x-www-form-urlencoded");
  5836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5837. ASSERT_EQ(StatusCode::OK_200, res->status);
  5838. res = cli_.Get("/person/john1");
  5839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5840. ASSERT_EQ(StatusCode::OK_200, res->status);
  5841. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5842. ASSERT_EQ("coder", res->body);
  5843. }
  5844. TEST_F(ServerTest, PostMethod2) {
  5845. auto res = cli_.Get("/person/john2");
  5846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5847. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5848. Params params;
  5849. params.emplace("name", "john2");
  5850. params.emplace("note", "coder");
  5851. res = cli_.Post("/person", params);
  5852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5853. ASSERT_EQ(StatusCode::OK_200, res->status);
  5854. res = cli_.Get("/person/john2");
  5855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5856. ASSERT_EQ(StatusCode::OK_200, res->status);
  5857. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5858. ASSERT_EQ("coder", res->body);
  5859. }
  5860. TEST_F(ServerTest, PutMethod3) {
  5861. auto res = cli_.Get("/person/john3");
  5862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5863. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5864. Params params;
  5865. params.emplace("name", "john3");
  5866. params.emplace("note", "coder");
  5867. res = cli_.Put("/person", params);
  5868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5869. ASSERT_EQ(StatusCode::OK_200, res->status);
  5870. res = cli_.Get("/person/john3");
  5871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5872. ASSERT_EQ(StatusCode::OK_200, res->status);
  5873. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5874. ASSERT_EQ("coder", res->body);
  5875. }
  5876. TEST_F(ServerTest, DeleteMethod1) {
  5877. auto res = cli_.Get("/person/john4");
  5878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5879. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5880. Params params;
  5881. params.emplace("name", "john4");
  5882. params.emplace("note", "coder");
  5883. res = cli_.Post("/person", params);
  5884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5885. ASSERT_EQ(StatusCode::OK_200, res->status);
  5886. res = cli_.Get("/person/john4");
  5887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5888. ASSERT_EQ(StatusCode::OK_200, res->status);
  5889. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5890. ASSERT_EQ("coder", res->body);
  5891. Params delete_params;
  5892. delete_params.emplace("name", "john4");
  5893. res = cli_.Delete("/person", delete_params);
  5894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5895. ASSERT_EQ(StatusCode::OK_200, res->status);
  5896. ASSERT_EQ("DELETED", res->body);
  5897. res = cli_.Get("/person/john4");
  5898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5899. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5900. }
  5901. TEST_F(ServerTest, DeleteMethod2) {
  5902. auto res = cli_.Get("/person/john5");
  5903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5904. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5905. Params params;
  5906. params.emplace("name", "john5");
  5907. params.emplace("note", "developer");
  5908. res = cli_.Post("/person", params);
  5909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5910. ASSERT_EQ(StatusCode::OK_200, res->status);
  5911. res = cli_.Get("/person/john5");
  5912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5913. ASSERT_EQ(StatusCode::OK_200, res->status);
  5914. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5915. ASSERT_EQ("developer", res->body);
  5916. Params delete_params;
  5917. delete_params.emplace("name", "john5");
  5918. Headers headers;
  5919. headers.emplace("Custom-Header", "test-value");
  5920. res = cli_.Delete("/person", headers, delete_params);
  5921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5922. ASSERT_EQ(StatusCode::OK_200, res->status);
  5923. ASSERT_EQ("DELETED", res->body);
  5924. res = cli_.Get("/person/john5");
  5925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5926. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5927. }
  5928. TEST_F(ServerTest, DeleteMethod3) {
  5929. auto res = cli_.Get("/person/john6");
  5930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5931. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5932. Params params;
  5933. params.emplace("name", "john6");
  5934. params.emplace("note", "tester");
  5935. res = cli_.Post("/person", params);
  5936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5937. ASSERT_EQ(StatusCode::OK_200, res->status);
  5938. res = cli_.Get("/person/john6");
  5939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5940. ASSERT_EQ(StatusCode::OK_200, res->status);
  5941. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5942. ASSERT_EQ("tester", res->body);
  5943. Params delete_params;
  5944. delete_params.emplace("name", "john6");
  5945. Headers headers;
  5946. headers.emplace("Custom-Header", "test-value");
  5947. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5949. ASSERT_EQ(StatusCode::OK_200, res->status);
  5950. ASSERT_EQ("DELETED", res->body);
  5951. res = cli_.Get("/person/john6");
  5952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5953. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5954. }
  5955. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5956. Params params;
  5957. params.emplace("json", JSON_DATA);
  5958. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5960. ASSERT_EQ(StatusCode::OK_200, res->status);
  5961. ASSERT_EQ(JSON_DATA, res->body);
  5962. }
  5963. TEST_F(ServerTest, PostEmptyContent) {
  5964. auto res = cli_.Post("/empty", "", "text/plain");
  5965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5966. ASSERT_EQ(StatusCode::OK_200, res->status);
  5967. ASSERT_EQ("empty", res->body);
  5968. }
  5969. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5970. auto res = cli_.Post("/empty-no-content-type");
  5971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5972. ASSERT_EQ(StatusCode::OK_200, res->status);
  5973. ASSERT_EQ("empty-no-content-type", res->body);
  5974. }
  5975. TEST_F(ServerTest, PostPathOnly) {
  5976. auto res = cli_.Post("/path-only");
  5977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5978. ASSERT_EQ(StatusCode::OK_200, res->status);
  5979. ASSERT_EQ("path-only", res->body);
  5980. }
  5981. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5982. auto res = cli_.Post("/path-headers-only",
  5983. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5985. ASSERT_EQ(StatusCode::OK_200, res->status);
  5986. ASSERT_EQ("path-headers-only", res->body);
  5987. }
  5988. TEST_F(ServerTest, PostLarge) {
  5989. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5991. ASSERT_EQ(StatusCode::OK_200, res->status);
  5992. EXPECT_EQ(LARGE_DATA, res->body);
  5993. }
  5994. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5995. auto res = cli_.Put("/empty-no-content-type");
  5996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5997. ASSERT_EQ(StatusCode::OK_200, res->status);
  5998. ASSERT_EQ("empty-no-content-type", res->body);
  5999. }
  6000. TEST_F(ServerTest, GetMethodDir) {
  6001. auto res = cli_.Get("/dir/");
  6002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6003. EXPECT_EQ(StatusCode::OK_200, res->status);
  6004. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6005. auto body = R"(<html>
  6006. <head>
  6007. </head>
  6008. <body>
  6009. <a href="/dir/test.html">Test</a>
  6010. <a href="/hi">hi</a>
  6011. </body>
  6012. </html>
  6013. )";
  6014. EXPECT_EQ(body, res->body);
  6015. }
  6016. TEST_F(ServerTest, GetMethodDirTest) {
  6017. auto res = cli_.Get("/dir/test.html");
  6018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6019. EXPECT_EQ(StatusCode::OK_200, res->status);
  6020. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6021. EXPECT_EQ("test.html", res->body);
  6022. }
  6023. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6024. auto res = cli_.Get("/dir/../dir/test.html");
  6025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6026. EXPECT_EQ(StatusCode::OK_200, res->status);
  6027. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6028. EXPECT_EQ("test.html", res->body);
  6029. }
  6030. TEST_F(ServerTest, GetMethodInvalidPath) {
  6031. auto res = cli_.Get("/dir/../test.html");
  6032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6033. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6034. }
  6035. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6036. auto res = cli_.Get("/../www/dir/test.html");
  6037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6038. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6039. }
  6040. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6041. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6043. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6044. }
  6045. TEST_F(ServerTest, GetMethodDirMountTest) {
  6046. auto res = cli_.Get("/mount/dir/test.html");
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. EXPECT_EQ(StatusCode::OK_200, res->status);
  6049. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6050. EXPECT_EQ("test.html", res->body);
  6051. }
  6052. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6053. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6055. EXPECT_EQ(StatusCode::OK_200, res->status);
  6056. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6057. EXPECT_EQ("test.html", res->body);
  6058. }
  6059. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6060. auto res = cli_.Get("/mount/dir/../test.html");
  6061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6062. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6063. }
  6064. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6065. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6067. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6068. }
  6069. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6070. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6073. }
  6074. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6075. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6078. }
  6079. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6080. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6082. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6083. }
  6084. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6085. auto res = cli_.Get("/mount/dir");
  6086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6087. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6088. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6089. }
  6090. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6091. auto res = cli_.Get("//dir");
  6092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6093. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6094. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6095. }
  6096. TEST_F(ServerTest, PostMethod303) {
  6097. auto res = cli_.Post("/1", "body", "text/plain");
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6100. EXPECT_EQ("/2", res->get_header_value("Location"));
  6101. }
  6102. TEST_F(ServerTest, PostMethod303Redirect) {
  6103. cli_.set_follow_location(true);
  6104. auto res = cli_.Post("/1", "body", "text/plain");
  6105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6106. EXPECT_EQ(StatusCode::OK_200, res->status);
  6107. EXPECT_EQ("redirected.", res->body);
  6108. EXPECT_EQ("/2", res->location);
  6109. }
  6110. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6111. auto res = cli_.Get("/dir/test.abcde");
  6112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6113. EXPECT_EQ(StatusCode::OK_200, res->status);
  6114. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6115. EXPECT_EQ("abcde", res->body);
  6116. }
  6117. TEST_F(ServerTest, StaticFileRange) {
  6118. auto res =
  6119. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6121. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6122. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6123. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6124. EXPECT_EQ(true, res->has_header("Content-Range"));
  6125. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6126. EXPECT_EQ(std::string("cd"), res->body);
  6127. }
  6128. TEST_F(ServerTest, StaticFileRanges) {
  6129. auto res = cli_.Get("/dir/test.abcde",
  6130. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6132. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6133. EXPECT_TRUE(
  6134. res->get_header_value("Content-Type")
  6135. .find(
  6136. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6137. 0);
  6138. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6139. }
  6140. TEST_F(ServerTest, StaticFileRangeHead) {
  6141. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6143. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6144. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6145. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6146. EXPECT_EQ(true, res->has_header("Content-Range"));
  6147. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6148. }
  6149. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6150. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6152. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6153. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6154. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6155. EXPECT_EQ(true, res->has_header("Content-Range"));
  6156. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6157. res->get_header_value("Content-Range"));
  6158. EXPECT_EQ("LAST\n", res->body);
  6159. }
  6160. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6161. auto res =
  6162. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6164. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6165. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6166. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6167. EXPECT_EQ(true, res->has_header("Content-Range"));
  6168. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6169. }
  6170. TEST_F(ServerTest, StaticFileBigFile) {
  6171. auto res = cli_.Get("/dir/1MB.txt");
  6172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6173. EXPECT_EQ(StatusCode::OK_200, res->status);
  6174. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6175. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6176. }
  6177. TEST_F(ServerTest, InvalidBaseDirMount) {
  6178. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6179. }
  6180. TEST_F(ServerTest, Binary) {
  6181. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6182. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6183. "application/octet-stream");
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. ASSERT_EQ(StatusCode::OK_200, res->status);
  6186. ASSERT_EQ(4U, res->body.size());
  6187. res = cli_.Put("/binary", binary.data(), binary.size(),
  6188. "application/octet-stream");
  6189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6190. ASSERT_EQ(StatusCode::OK_200, res->status);
  6191. ASSERT_EQ(4U, res->body.size());
  6192. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6193. "application/octet-stream");
  6194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6195. ASSERT_EQ(StatusCode::OK_200, res->status);
  6196. ASSERT_EQ(4U, res->body.size());
  6197. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6198. "application/octet-stream");
  6199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6200. ASSERT_EQ(StatusCode::OK_200, res->status);
  6201. ASSERT_EQ(4U, res->body.size());
  6202. }
  6203. TEST_F(ServerTest, BinaryString) {
  6204. auto binary = std::string("\x00\x01\x02\x03", 4);
  6205. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6207. ASSERT_EQ(StatusCode::OK_200, res->status);
  6208. ASSERT_EQ(4U, res->body.size());
  6209. res = cli_.Put("/binary", binary, "application/octet-stream");
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. ASSERT_EQ(StatusCode::OK_200, res->status);
  6212. ASSERT_EQ(4U, res->body.size());
  6213. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6215. ASSERT_EQ(StatusCode::OK_200, res->status);
  6216. ASSERT_EQ(4U, res->body.size());
  6217. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6219. ASSERT_EQ(StatusCode::OK_200, res->status);
  6220. ASSERT_EQ(4U, res->body.size());
  6221. }
  6222. TEST_F(ServerTest, EmptyRequest) {
  6223. auto res = cli_.Get("");
  6224. ASSERT_TRUE(!res);
  6225. EXPECT_EQ(Error::Connection, res.error());
  6226. }
  6227. TEST_F(ServerTest, LongRequest) {
  6228. std::string request;
  6229. for (size_t i = 0; i < 545; i++) {
  6230. request += "/TooLongRequest";
  6231. }
  6232. request += "OK";
  6233. auto res = cli_.Get(request.c_str());
  6234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6235. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6236. }
  6237. TEST_F(ServerTest, TooLongRequest) {
  6238. std::string request;
  6239. for (size_t i = 0; i < 546; i++) {
  6240. request += "/TooLongRequest";
  6241. }
  6242. request += "_NG";
  6243. auto start = std::chrono::high_resolution_clock::now();
  6244. cli_.set_keep_alive(true);
  6245. auto res = cli_.Get(request.c_str());
  6246. auto end = std::chrono::high_resolution_clock::now();
  6247. auto elapsed =
  6248. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6249. .count();
  6250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6251. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6252. EXPECT_LE(elapsed, 1000);
  6253. EXPECT_EQ("close", res->get_header_value("Connection"));
  6254. EXPECT_FALSE(cli_.is_socket_open());
  6255. }
  6256. TEST_F(ServerTest, AlmostTooLongRequest) {
  6257. // test for #2046 - URI length check shouldn't include other content on req
  6258. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6259. // leading /, space, HTTP/1.1)
  6260. std::string request =
  6261. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6262. auto res = cli_.Get(request.c_str());
  6263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6265. }
  6266. TEST_F(ServerTest, LongHeader) {
  6267. Request req;
  6268. req.method = "GET";
  6269. req.path = "/hi";
  6270. std::string host_and_port;
  6271. host_and_port += HOST;
  6272. host_and_port += ":";
  6273. host_and_port += std::to_string(PORT);
  6274. req.headers.emplace("Host", host_and_port.c_str());
  6275. req.headers.emplace("Accept", "*/*");
  6276. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6277. req.headers.emplace(
  6278. "Header-Name",
  6279. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6280. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6281. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6282. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6283. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6284. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6285. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6286. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6287. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6288. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6289. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6290. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6291. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6292. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6293. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6294. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6295. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6296. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6297. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6298. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6299. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6300. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6301. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6302. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6303. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6304. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6305. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6306. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6307. "@@@@@@@@@@@@@@@@");
  6308. auto res = std::make_shared<Response>();
  6309. auto error = Error::Success;
  6310. auto ret = cli_.send(req, *res, error);
  6311. ASSERT_TRUE(ret);
  6312. EXPECT_EQ(StatusCode::OK_200, res->status);
  6313. }
  6314. TEST_F(ServerTest, LongQueryValue) {
  6315. auto start = std::chrono::high_resolution_clock::now();
  6316. cli_.set_keep_alive(true);
  6317. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6318. auto end = std::chrono::high_resolution_clock::now();
  6319. auto elapsed =
  6320. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6321. .count();
  6322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6323. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6324. EXPECT_LE(elapsed, 1000);
  6325. EXPECT_EQ("close", res->get_header_value("Connection"));
  6326. EXPECT_FALSE(cli_.is_socket_open());
  6327. }
  6328. TEST_F(ServerTest, TooLongQueryValue) {
  6329. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6330. ASSERT_FALSE(res);
  6331. EXPECT_EQ(Error::Read, res.error());
  6332. }
  6333. TEST_F(ServerTest, TooLongHeader) {
  6334. Request req;
  6335. req.method = "GET";
  6336. req.path = "/hi";
  6337. std::string host_and_port;
  6338. host_and_port += HOST;
  6339. host_and_port += ":";
  6340. host_and_port += std::to_string(PORT);
  6341. req.headers.emplace("Host", host_and_port.c_str());
  6342. req.headers.emplace("Accept", "*/*");
  6343. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6344. req.headers.emplace(
  6345. "Header-Name",
  6346. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6347. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6348. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6349. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6350. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6351. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6352. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6353. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6354. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6355. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6356. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6357. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6358. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6359. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6360. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6361. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6362. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6363. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6364. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6365. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6366. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6367. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6368. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6369. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6370. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6371. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6372. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6373. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6374. "@@@@@@@@@@@@@@@@@");
  6375. auto res = std::make_shared<Response>();
  6376. auto error = Error::Success;
  6377. auto ret = cli_.send(req, *res, error);
  6378. ASSERT_TRUE(ret);
  6379. EXPECT_EQ(StatusCode::OK_200, res->status);
  6380. }
  6381. TEST_F(ServerTest, HeaderCountAtLimit) {
  6382. // Test with headers just under the 100 limit
  6383. httplib::Headers headers;
  6384. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6385. // This should keep us just under the 100 header limit
  6386. for (int i = 0; i < 95; i++) {
  6387. std::string name = "X-Test-Header-" + std::to_string(i);
  6388. std::string value = "value" + std::to_string(i);
  6389. headers.emplace(name, value);
  6390. }
  6391. // This should work fine as we're under the limit
  6392. auto res = cli_.Get("/hi", headers);
  6393. EXPECT_TRUE(res);
  6394. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6395. }
  6396. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6397. // Test with many headers to exceed the 100 limit
  6398. httplib::Headers headers;
  6399. // Add 150 headers to definitely exceed the 100 limit
  6400. for (int i = 0; i < 150; i++) {
  6401. std::string name = "X-Test-Header-" + std::to_string(i);
  6402. std::string value = "value" + std::to_string(i);
  6403. headers.emplace(name, value);
  6404. }
  6405. // This should fail due to exceeding header count limit
  6406. cli_.set_keep_alive(true);
  6407. auto res = cli_.Get("/hi", headers);
  6408. // The server should respond with 400 Bad Request
  6409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6410. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6411. EXPECT_EQ("close", res->get_header_value("Connection"));
  6412. EXPECT_FALSE(cli_.is_socket_open());
  6413. }
  6414. TEST_F(ServerTest, PercentEncoding) {
  6415. auto res = cli_.Get("/e%6edwith%");
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::OK_200, res->status);
  6418. }
  6419. TEST_F(ServerTest, PercentEncodingUnicode) {
  6420. auto res = cli_.Get("/e%u006edwith%");
  6421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6422. EXPECT_EQ(StatusCode::OK_200, res->status);
  6423. }
  6424. TEST_F(ServerTest, InvalidPercentEncoding) {
  6425. auto res = cli_.Get("/%endwith%");
  6426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6427. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6428. }
  6429. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6430. auto res = cli_.Get("/%uendwith%");
  6431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6432. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6433. }
  6434. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6435. auto res = cli_.Get("/hello?aaa=bbb%");
  6436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6437. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6438. }
  6439. TEST_F(ServerTest, PlusSignEncoding) {
  6440. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. EXPECT_EQ(StatusCode::OK_200, res->status);
  6443. EXPECT_EQ("a +b", res->body);
  6444. }
  6445. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6446. // This test simulates a potential DoS attack using many headers
  6447. // to verify our security fix prevents memory exhaustion
  6448. httplib::Headers attack_headers;
  6449. // Attempt to add many headers like an attacker would (200 headers to far
  6450. // exceed limit)
  6451. for (int i = 0; i < 200; i++) {
  6452. std::string name = "X-Attack-Header-" + std::to_string(i);
  6453. std::string value = "attack_payload_" + std::to_string(i);
  6454. attack_headers.emplace(name, value);
  6455. }
  6456. // Try to POST with excessive headers
  6457. cli_.set_keep_alive(true);
  6458. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6459. // Should either fail or return 400 Bad Request due to security limit
  6460. if (res) {
  6461. // If we get a response, it should be 400 Bad Request
  6462. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6463. EXPECT_EQ("close", res->get_header_value("Connection"));
  6464. }
  6465. EXPECT_FALSE(cli_.is_socket_open());
  6466. }
  6467. TEST_F(ServerTest, MultipartFormData) {
  6468. UploadFormDataItems items = {
  6469. {"text1", "text default", "", ""},
  6470. {"text2", "aωb", "", ""},
  6471. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6472. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6473. {"file3", "", "", "application/octet-stream"},
  6474. {"file4", "", "", " application/json tmp-string "}};
  6475. auto res = cli_.Post("/multipart", items);
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. EXPECT_EQ(StatusCode::OK_200, res->status);
  6478. }
  6479. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6480. UploadFormDataItems items = {
  6481. {"text", "default text", "", ""},
  6482. {"multi_text1", "aaaaa", "", ""},
  6483. {"multi_text1", "bbbbb", "", ""},
  6484. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6485. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6486. "application/json"},
  6487. };
  6488. auto res = cli_.Post("/multipart/multi_file_values", items);
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. EXPECT_EQ(StatusCode::OK_200, res->status);
  6491. }
  6492. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6493. auto res = cli_.Get("/hi");
  6494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6495. EXPECT_EQ(StatusCode::OK_200, res->status);
  6496. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6497. EXPECT_EQ("Hello World!", res->body);
  6498. }
  6499. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6500. Request req;
  6501. req.method = "POST";
  6502. req.path = "/chunked";
  6503. std::string host_and_port;
  6504. host_and_port += HOST;
  6505. host_and_port += ":";
  6506. host_and_port += std::to_string(PORT);
  6507. req.headers.emplace("Host", host_and_port.c_str());
  6508. req.headers.emplace("Accept", "*/*");
  6509. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6510. req.headers.emplace("Content-Type", "text/plain");
  6511. req.headers.emplace("Content-Length", "0");
  6512. req.headers.emplace(
  6513. "Transfer-Encoding",
  6514. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6515. // Client does not chunk, so make a chunked body manually.
  6516. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6517. auto res = std::make_shared<Response>();
  6518. auto error = Error::Success;
  6519. auto ret = cli_.send(req, *res, error);
  6520. ASSERT_TRUE(ret);
  6521. EXPECT_EQ(StatusCode::OK_200, res->status);
  6522. }
  6523. template <typename ClientT>
  6524. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6525. int expected_status) {
  6526. Request req;
  6527. req.method = "POST";
  6528. req.path = "/chunked";
  6529. std::string host_and_port;
  6530. host_and_port += HOST;
  6531. host_and_port += ":";
  6532. host_and_port += std::to_string(PORT);
  6533. req.headers.emplace("Host", host_and_port.c_str());
  6534. req.headers.emplace("Content-Length", "0");
  6535. req.headers.emplace("Transfer-Encoding", "chunked");
  6536. req.body = body;
  6537. auto res = std::make_shared<Response>();
  6538. auto error = Error::Success;
  6539. ASSERT_TRUE(cli.send(req, *res, error));
  6540. EXPECT_EQ(expected_status, res->status);
  6541. }
  6542. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6543. // rather than treat them as valid lengths.
  6544. template <typename ClientT>
  6545. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6546. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6547. }
  6548. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6549. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6550. }
  6551. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6552. expect_chunked_body_rejected(
  6553. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6554. }
  6555. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6556. // chunk-size line carries no CR, LF or other control character ahead of its
  6557. // terminator. Such a line must be refused rather than read as extension text.
  6558. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6559. expect_chunked_body_rejected(
  6560. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6561. }
  6562. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6563. expect_chunked_body_rejected(
  6564. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6565. }
  6566. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6567. expect_chunked_body_rejected(
  6568. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6569. }
  6570. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6571. // The literal stays split: a hex escape consumes every hex digit that
  6572. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6573. expect_chunked_body_rejected(
  6574. cli_, "4;a\x01"
  6575. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6576. }
  6577. TEST_F(ServerTest, AcceptsChunkExtension) {
  6578. expect_chunked_body_status(cli_,
  6579. "4;name=value\r\ndech\r\n"
  6580. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6581. "0;last\r\n\r\n",
  6582. StatusCode::OK_200);
  6583. }
  6584. TEST_F(ServerTest, GetStreamed2) {
  6585. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6587. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6588. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6589. EXPECT_EQ(true, res->has_header("Content-Range"));
  6590. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6591. EXPECT_EQ(std::string("ab"), res->body);
  6592. }
  6593. TEST_F(ServerTest, GetStreamed) {
  6594. auto res = cli_.Get("/streamed");
  6595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6596. EXPECT_EQ(StatusCode::OK_200, res->status);
  6597. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6598. EXPECT_EQ(std::string("aaabbb"), res->body);
  6599. }
  6600. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6601. auto res = cli_.Get("/streamed-without-length",
  6602. Headers{make_range_header({{0, -1}})});
  6603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6604. EXPECT_EQ(StatusCode::OK_200, res->status);
  6605. EXPECT_EQ(false, res->has_header("Content-Length"));
  6606. EXPECT_EQ(false, res->has_header("Content-Range"));
  6607. EXPECT_EQ(std::string("abcdefg"), res->body);
  6608. }
  6609. TEST_F(ServerTest, GetStreamedWithRange1) {
  6610. auto res =
  6611. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6613. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6614. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6615. EXPECT_EQ(true, res->has_header("Content-Range"));
  6616. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6617. EXPECT_EQ(std::string("def"), res->body);
  6618. }
  6619. TEST_F(ServerTest, GetStreamedWithRange2) {
  6620. auto res =
  6621. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6623. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6624. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6625. EXPECT_EQ(true, res->has_header("Content-Range"));
  6626. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6627. EXPECT_EQ(std::string("bcdefg"), res->body);
  6628. }
  6629. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6630. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6632. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6633. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6634. EXPECT_EQ(true, res->has_header("Content-Range"));
  6635. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6636. EXPECT_EQ(std::string("efg"), res->body);
  6637. }
  6638. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6639. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6640. // the entire representation.
  6641. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6642. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6644. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6645. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6646. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6647. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6648. }
  6649. }
  6650. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6651. auto res =
  6652. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6654. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6655. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6656. EXPECT_EQ(false, res->has_header("Content-Range"));
  6657. EXPECT_EQ(0U, res->body.size());
  6658. }
  6659. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6660. // Only a 206 is served as a partial representation. Under any other status
  6661. // `apply_ranges()` reported the full content length, so the body must match
  6662. // that header, and the content provider must never be asked for an offset
  6663. // outside the representation.
  6664. auto check = [&](int status, const char *range) {
  6665. auto path =
  6666. std::string("/streamed-with-range?status=") + std::to_string(status);
  6667. auto ctx = path + " Range: " + range;
  6668. auto res = cli_.Get(path, Headers{{"Range", range}});
  6669. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6670. EXPECT_EQ(status, res->status) << ctx;
  6671. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6672. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6673. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6674. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6675. };
  6676. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6677. check(403, "bytes=3-5");
  6678. // The offset is far past the representation.
  6679. check(403, "bytes=100000-100200");
  6680. // `first_pos` is still -1 here, and the bounds asserts in
  6681. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6682. check(403, "bytes=-3");
  6683. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6684. // multipart branch would have written one that is empty.
  6685. check(403, "bytes=1-2, 4-5");
  6686. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6687. // covers the whole representation.
  6688. check(200, "bytes=3-5");
  6689. check(200, "bytes=1-2, 4-5");
  6690. }
  6691. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6692. auto res =
  6693. cli_.Get("/streamed-with-range",
  6694. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6695. "92233720368547758079223372036854775807"}});
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6698. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6699. EXPECT_EQ(false, res->has_header("Content-Range"));
  6700. EXPECT_EQ(0U, res->body.size());
  6701. }
  6702. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6703. auto res = cli_.Get(
  6704. "/with-range",
  6705. Headers{{"Range",
  6706. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6707. {"Accept-Encoding", ""}});
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6710. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6711. EXPECT_EQ(true, res->has_header("Content-Range"));
  6712. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6713. EXPECT_EQ(std::string("abcdefg"), res->body);
  6714. }
  6715. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6716. auto res = cli_.Get("/with-range", Headers{
  6717. {"Range", "bytes=0-"},
  6718. {"Accept-Encoding", ""},
  6719. });
  6720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6721. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6722. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6723. EXPECT_EQ(true, res->has_header("Content-Range"));
  6724. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6725. EXPECT_EQ(std::string("abcdefg"), res->body);
  6726. }
  6727. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6728. auto res = cli_.Get("/streamed-with-range",
  6729. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6732. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6733. EXPECT_EQ(false, res->has_header("Content-Range"));
  6734. EXPECT_EQ(267U, res->body.size());
  6735. // Check that both range contents are present
  6736. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6737. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6738. // Check that Content-Range headers are present for both ranges
  6739. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6740. std::string::npos);
  6741. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6742. std::string::npos);
  6743. }
  6744. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6745. Ranges ranges;
  6746. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6747. ranges.emplace_back(0, -1);
  6748. }
  6749. auto res = cli_.Get("/streamed-with-range?error",
  6750. Headers{{make_range_header(ranges)}});
  6751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6752. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6753. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6754. EXPECT_EQ(false, res->has_header("Content-Range"));
  6755. EXPECT_EQ(0U, res->body.size());
  6756. }
  6757. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6758. auto res = cli_.Get("/streamed-with-range",
  6759. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6761. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6762. EXPECT_EQ(5U, res->body.size());
  6763. // Check that overlapping ranges are coalesced into a single range
  6764. EXPECT_EQ("bcdef", res->body);
  6765. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6766. // Should be single range, not multipart
  6767. EXPECT_TRUE(res->has_header("Content-Range"));
  6768. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6769. }
  6770. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6771. auto res = cli_.Get("/streamed-with-range",
  6772. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6774. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6775. EXPECT_EQ(268U, res->body.size());
  6776. // Check that both range contents are present
  6777. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6778. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6779. // Check that Content-Range headers are present for both ranges
  6780. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6781. std::string::npos);
  6782. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6783. std::string::npos);
  6784. }
  6785. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6786. auto res = cli_.Get("/streamed-with-range",
  6787. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6789. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6790. EXPECT_EQ(269U, res->body.size());
  6791. // Check that both duplicate range contents are present
  6792. size_t first_abc = res->body.find("abc\r\n");
  6793. EXPECT_TRUE(first_abc != std::string::npos);
  6794. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6795. EXPECT_TRUE(second_abc != std::string::npos);
  6796. // Check that Content-Range headers are present for both ranges
  6797. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6798. EXPECT_TRUE(first_range != std::string::npos);
  6799. size_t second_range =
  6800. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6801. EXPECT_TRUE(second_range != std::string::npos);
  6802. }
  6803. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6804. auto res =
  6805. cli_.Get("/streamed-with-range?error",
  6806. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6808. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6809. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6810. EXPECT_EQ(false, res->has_header("Content-Range"));
  6811. EXPECT_EQ(0U, res->body.size());
  6812. }
  6813. TEST_F(ServerTest, GetStreamedEndless) {
  6814. uint64_t offset = 0;
  6815. auto res = cli_.Get("/streamed-cancel",
  6816. [&](const char * /*data*/, uint64_t data_length) {
  6817. if (offset < 100) {
  6818. offset += data_length;
  6819. return true;
  6820. }
  6821. return false;
  6822. });
  6823. ASSERT_TRUE(!res);
  6824. EXPECT_EQ(Error::Canceled, res.error());
  6825. }
  6826. TEST_F(ServerTest, ClientStop) {
  6827. std::atomic_size_t count{4};
  6828. std::vector<std::thread> threads;
  6829. for (auto i = count.load(); i != 0; --i) {
  6830. threads.emplace_back([&]() {
  6831. auto res = cli_.Get("/streamed-cancel",
  6832. [&](const char *, uint64_t) { return true; });
  6833. --count;
  6834. ASSERT_TRUE(!res);
  6835. EXPECT_TRUE(res.error() == Error::Canceled ||
  6836. res.error() == Error::Read || res.error() == Error::Write);
  6837. });
  6838. }
  6839. std::this_thread::sleep_for(std::chrono::seconds(2));
  6840. while (count != 0) {
  6841. cli_.stop();
  6842. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6843. }
  6844. for (auto &t : threads) {
  6845. t.join();
  6846. }
  6847. }
  6848. TEST_F(ServerTest, GetWithRange1) {
  6849. auto res = cli_.Get("/with-range", Headers{
  6850. make_range_header({{3, 5}}),
  6851. {"Accept-Encoding", ""},
  6852. });
  6853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6854. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6855. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6856. EXPECT_EQ(true, res->has_header("Content-Range"));
  6857. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6858. EXPECT_EQ(std::string("def"), res->body);
  6859. }
  6860. TEST_F(ServerTest, GetWithRange2) {
  6861. auto res = cli_.Get("/with-range", Headers{
  6862. make_range_header({{1, -1}}),
  6863. {"Accept-Encoding", ""},
  6864. });
  6865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6866. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6867. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6868. EXPECT_EQ(true, res->has_header("Content-Range"));
  6869. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6870. EXPECT_EQ(std::string("bcdefg"), res->body);
  6871. }
  6872. TEST_F(ServerTest, GetWithRange3) {
  6873. auto res = cli_.Get("/with-range", Headers{
  6874. make_range_header({{0, 0}}),
  6875. {"Accept-Encoding", ""},
  6876. });
  6877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6878. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6879. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6880. EXPECT_EQ(true, res->has_header("Content-Range"));
  6881. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6882. EXPECT_EQ(std::string("a"), res->body);
  6883. }
  6884. TEST_F(ServerTest, GetWithRange4) {
  6885. auto res = cli_.Get("/with-range", Headers{
  6886. make_range_header({{-1, 2}}),
  6887. {"Accept-Encoding", ""},
  6888. });
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6891. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6892. EXPECT_EQ(true, res->has_header("Content-Range"));
  6893. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6894. EXPECT_EQ(std::string("fg"), res->body);
  6895. }
  6896. TEST_F(ServerTest, GetWithRange5) {
  6897. auto res = cli_.Get("/with-range", Headers{
  6898. make_range_header({{0, 5}}),
  6899. {"Accept-Encoding", ""},
  6900. });
  6901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6902. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6903. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6904. EXPECT_EQ(true, res->has_header("Content-Range"));
  6905. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6906. EXPECT_EQ(std::string("abcdef"), res->body);
  6907. }
  6908. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6909. auto res =
  6910. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6913. }
  6914. TEST_F(ServerTest, GetWithRangeMultipart) {
  6915. auto res =
  6916. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6919. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6920. EXPECT_EQ(false, res->has_header("Content-Range"));
  6921. EXPECT_EQ(267U, res->body.size());
  6922. }
  6923. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6924. auto res = cli_.Get("/with-range",
  6925. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6927. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6928. }
  6929. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6930. auto res = cli_.Get("/with-range-customized-response",
  6931. Headers{{make_range_header({{1, 2}})}});
  6932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6933. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6934. EXPECT_EQ(true, res->has_header("Content-Length"));
  6935. EXPECT_EQ(false, res->has_header("Content-Range"));
  6936. EXPECT_EQ(JSON_DATA, res->body);
  6937. }
  6938. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6939. auto res = cli_.Get("/with-range-customized-response",
  6940. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6942. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6943. EXPECT_EQ(true, res->has_header("Content-Length"));
  6944. EXPECT_EQ(false, res->has_header("Content-Range"));
  6945. EXPECT_EQ(JSON_DATA, res->body);
  6946. }
  6947. TEST_F(ServerTest, Issue1772) {
  6948. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6950. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6951. }
  6952. TEST_F(ServerTest, Issue609) {
  6953. auto res = cli_.Delete("/issue609");
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. EXPECT_EQ(StatusCode::OK_200, res->status);
  6956. EXPECT_EQ(std::string("ok"), res->body);
  6957. }
  6958. TEST_F(ServerTest, GetStreamedChunked) {
  6959. auto res = cli_.Get("/streamed-chunked");
  6960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6961. EXPECT_EQ(StatusCode::OK_200, res->status);
  6962. EXPECT_EQ(std::string("123456789"), res->body);
  6963. }
  6964. TEST_F(ServerTest, GetStreamedChunked2) {
  6965. auto res = cli_.Get("/streamed-chunked2");
  6966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6967. EXPECT_EQ(StatusCode::OK_200, res->status);
  6968. EXPECT_EQ(std::string("123456789"), res->body);
  6969. }
  6970. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6971. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6973. EXPECT_EQ(StatusCode::OK_200, res->status);
  6974. EXPECT_EQ(std::string("123456789"), res->body);
  6975. EXPECT_TRUE(res->has_header("Trailer"));
  6976. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6977. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6978. // Trailers are now stored separately from headers (security fix)
  6979. EXPECT_EQ(2U, res->trailers.size());
  6980. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6981. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6982. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6983. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6984. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6985. // Verify trailers are NOT in headers (security verification)
  6986. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6987. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6988. }
  6989. TEST_F(ServerTest, LargeChunkedPost) {
  6990. Request req;
  6991. req.method = "POST";
  6992. req.path = "/large-chunked";
  6993. std::string host_and_port;
  6994. host_and_port += HOST;
  6995. host_and_port += ":";
  6996. host_and_port += std::to_string(PORT);
  6997. req.headers.emplace("Host", host_and_port.c_str());
  6998. req.headers.emplace("Accept", "*/*");
  6999. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7000. req.headers.emplace("Content-Type", "text/plain");
  7001. req.headers.emplace("Content-Length", "0");
  7002. req.headers.emplace("Transfer-Encoding", "chunked");
  7003. std::string long_string(30 * 1024u, 'a');
  7004. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7005. // Attempt to make a large enough post to exceed OS buffers, to test that
  7006. // the server handles short reads if the full chunk data isn't available.
  7007. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7008. auto res = std::make_shared<Response>();
  7009. auto error = Error::Success;
  7010. auto ret = cli_.send(req, *res, error);
  7011. ASSERT_TRUE(ret);
  7012. EXPECT_EQ(StatusCode::OK_200, res->status);
  7013. }
  7014. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7015. auto res = cli_.Get("/remote_addr");
  7016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7017. EXPECT_EQ(StatusCode::OK_200, res->status);
  7018. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7019. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7020. }
  7021. TEST_F(ServerTest, GetMethodLocalAddr) {
  7022. auto res = cli_.Get("/local_addr");
  7023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7024. EXPECT_EQ(StatusCode::OK_200, res->status);
  7025. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7026. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7027. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7028. }
  7029. TEST_F(ServerTest, HTTPResponseSplitting) {
  7030. auto res = cli_.Get("/http_response_splitting");
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::OK_200, res->status);
  7033. }
  7034. TEST_F(ServerTest, SlowRequest) {
  7035. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7036. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7037. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7038. }
  7039. #if 0
  7040. TEST_F(ServerTest, SlowPost) {
  7041. char buffer[64 * 1024];
  7042. memset(buffer, 0x42, sizeof(buffer));
  7043. auto res = cli_.Post(
  7044. "/slowpost", 64 * 1024 * 1024,
  7045. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7046. auto ret = sink.write(buffer, sizeof(buffer));
  7047. EXPECT_TRUE(ret);
  7048. return true;
  7049. },
  7050. "text/plain");
  7051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7052. EXPECT_EQ(StatusCode::OK_200, res->status);
  7053. }
  7054. TEST_F(ServerTest, SlowPostFail) {
  7055. char buffer[64 * 1024];
  7056. memset(buffer, 0x42, sizeof(buffer));
  7057. cli_.set_write_timeout(std::chrono::seconds(0));
  7058. auto res = cli_.Post(
  7059. "/slowpost", 64 * 1024 * 1024,
  7060. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7061. sink.write(buffer, sizeof(buffer));
  7062. return true;
  7063. },
  7064. "text/plain");
  7065. ASSERT_TRUE(!res);
  7066. EXPECT_EQ(Error::Write, res.error());
  7067. }
  7068. #endif
  7069. TEST_F(ServerTest, Put) {
  7070. auto res = cli_.Put("/put", "PUT", "text/plain");
  7071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7072. EXPECT_EQ(StatusCode::OK_200, res->status);
  7073. EXPECT_EQ("PUT", res->body);
  7074. }
  7075. TEST_F(ServerTest, PutWithContentProvider) {
  7076. auto res = cli_.Put(
  7077. "/put", 3,
  7078. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7079. sink.os << "PUT";
  7080. return true;
  7081. },
  7082. "text/plain");
  7083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7084. EXPECT_EQ(StatusCode::OK_200, res->status);
  7085. EXPECT_EQ("PUT", res->body);
  7086. }
  7087. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7088. auto res = cli_.Post(
  7089. "/post", 42,
  7090. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7091. return false;
  7092. },
  7093. "text/plain");
  7094. ASSERT_TRUE(!res);
  7095. EXPECT_EQ(Error::Canceled, res.error());
  7096. }
  7097. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7098. auto res = cli_.Put(
  7099. "/put",
  7100. [](size_t /*offset*/, DataSink &sink) {
  7101. sink.os << "PUT";
  7102. sink.done();
  7103. return true;
  7104. },
  7105. "text/plain");
  7106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7107. EXPECT_EQ(StatusCode::OK_200, res->status);
  7108. EXPECT_EQ("PUT", res->body);
  7109. }
  7110. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7111. auto res = cli_.Post(
  7112. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7113. "text/plain");
  7114. ASSERT_TRUE(!res);
  7115. EXPECT_EQ(Error::Canceled, res.error());
  7116. }
  7117. TEST_F(ServerTest, PostLoopBack) {
  7118. std::string body;
  7119. auto res = cli_.Post(
  7120. "/post-loopback", 9,
  7121. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7122. EXPECT_EQ(9u, length);
  7123. sink.write("123", 3);
  7124. sink.write("456", 3);
  7125. sink.write("789", 3);
  7126. return true;
  7127. },
  7128. "text/plain",
  7129. [&body](const char *data, size_t data_length) {
  7130. body.append(data, data_length);
  7131. return true;
  7132. });
  7133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7134. EXPECT_EQ(StatusCode::OK_200, res->status);
  7135. EXPECT_EQ("123456789", body);
  7136. }
  7137. TEST_F(ServerTest, PutLoopBack) {
  7138. std::string body;
  7139. auto res = cli_.Put(
  7140. "/put-loopback", 9,
  7141. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7142. EXPECT_EQ(9u, length);
  7143. sink.write("123", 3);
  7144. sink.write("456", 3);
  7145. sink.write("789", 3);
  7146. return true;
  7147. },
  7148. "text/plain",
  7149. [&body](const char *data, size_t data_length) {
  7150. body.append(data, data_length);
  7151. return true;
  7152. });
  7153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7154. EXPECT_EQ(StatusCode::OK_200, res->status);
  7155. EXPECT_EQ("123456789", body);
  7156. }
  7157. TEST_F(ServerTest, PatchLoopBack) {
  7158. std::string body;
  7159. auto res = cli_.Patch(
  7160. "/patch-loopback", 9,
  7161. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7162. EXPECT_EQ(9u, length);
  7163. sink.write("123", 3);
  7164. sink.write("456", 3);
  7165. sink.write("789", 3);
  7166. return true;
  7167. },
  7168. "text/plain",
  7169. [&body](const char *data, size_t data_length) {
  7170. body.append(data, data_length);
  7171. return true;
  7172. });
  7173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7174. EXPECT_EQ(StatusCode::OK_200, res->status);
  7175. EXPECT_EQ("123456789", body);
  7176. }
  7177. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7178. std::string body;
  7179. auto res = cli_.Post(
  7180. "/post-loopback",
  7181. [](size_t /*offset*/, DataSink &sink) {
  7182. sink.write("123", 3);
  7183. sink.write("456", 3);
  7184. sink.write("789", 3);
  7185. sink.done();
  7186. return true;
  7187. },
  7188. "text/plain",
  7189. [&body](const char *data, size_t data_length) {
  7190. body.append(data, data_length);
  7191. return true;
  7192. });
  7193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7194. EXPECT_EQ(StatusCode::OK_200, res->status);
  7195. EXPECT_EQ("123456789", body);
  7196. }
  7197. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7198. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7199. cli_.set_compress(true);
  7200. auto res = cli_.Put(
  7201. "/put", 3,
  7202. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7203. sink.os << "PUT";
  7204. return true;
  7205. },
  7206. "text/plain");
  7207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7208. EXPECT_EQ(StatusCode::OK_200, res->status);
  7209. EXPECT_EQ("PUT", res->body);
  7210. }
  7211. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7212. cli_.set_compress(true);
  7213. auto res = cli_.Post(
  7214. "/post", 42,
  7215. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7216. return false;
  7217. },
  7218. "text/plain");
  7219. ASSERT_TRUE(!res);
  7220. EXPECT_EQ(Error::Canceled, res.error());
  7221. }
  7222. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7223. cli_.set_compress(true);
  7224. auto res = cli_.Put(
  7225. "/put",
  7226. [](size_t /*offset*/, DataSink &sink) {
  7227. sink.os << "PUT";
  7228. sink.done();
  7229. return true;
  7230. },
  7231. "text/plain");
  7232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7233. EXPECT_EQ(StatusCode::OK_200, res->status);
  7234. EXPECT_EQ("PUT", res->body);
  7235. }
  7236. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7237. cli_.set_compress(true);
  7238. auto res = cli_.Post(
  7239. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7240. "text/plain");
  7241. ASSERT_TRUE(!res);
  7242. EXPECT_EQ(Error::Canceled, res.error());
  7243. }
  7244. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7245. cli_.set_compress(true);
  7246. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7248. EXPECT_EQ(StatusCode::OK_200, res->status);
  7249. EXPECT_EQ(LARGE_DATA, res->body);
  7250. }
  7251. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7252. #ifdef CPPHTTPLIB_SSL_ENABLED
  7253. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7254. Client cli(s.c_str());
  7255. cli.enable_server_certificate_verification(false);
  7256. #else
  7257. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7258. Client cli(s.c_str());
  7259. #endif
  7260. cli.set_compress(true);
  7261. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7263. EXPECT_EQ(StatusCode::OK_200, res->status);
  7264. EXPECT_EQ(LARGE_DATA, res->body);
  7265. // The compressed size should be less than a 10th of the original. May vary
  7266. // depending on the zlib library.
  7267. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7268. static_cast<uint64_t>(10 * 1024 * 1024));
  7269. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7270. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7271. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7272. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7273. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7274. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7275. #endif
  7276. }
  7277. TEST_F(ServerTest, PutContentWithDeflate) {
  7278. cli_.set_compress(false);
  7279. Headers headers;
  7280. headers.emplace("Content-Encoding", "deflate");
  7281. // PUT in deflate format:
  7282. auto res = cli_.Put("/put", headers,
  7283. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7285. EXPECT_EQ(StatusCode::OK_200, res->status);
  7286. EXPECT_EQ("PUT", res->body);
  7287. }
  7288. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7289. Headers headers;
  7290. headers.emplace("Accept-Encoding", "gzip, deflate");
  7291. auto res = cli_.Get("/streamed-chunked", headers);
  7292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7293. EXPECT_EQ(StatusCode::OK_200, res->status);
  7294. EXPECT_EQ(std::string("123456789"), res->body);
  7295. }
  7296. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7297. Headers headers;
  7298. headers.emplace("Accept-Encoding", "gzip, deflate");
  7299. auto res = cli_.Get("/streamed-chunked2", headers);
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::OK_200, res->status);
  7302. EXPECT_EQ(std::string("123456789"), res->body);
  7303. }
  7304. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7305. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7307. EXPECT_EQ(StatusCode::OK_200, res->status);
  7308. }
  7309. TEST(GzipDecompressor, ChunkedDecompression) {
  7310. std::string data;
  7311. for (size_t i = 0; i < 32 * 1024; ++i) {
  7312. data.push_back(static_cast<char>('a' + i % 26));
  7313. }
  7314. std::string compressed_data;
  7315. {
  7316. httplib::detail::gzip_compressor compressor;
  7317. bool result = compressor.compress(
  7318. data.data(), data.size(),
  7319. /*last=*/true,
  7320. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7321. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7322. compressed_data_size);
  7323. return true;
  7324. });
  7325. ASSERT_TRUE(result);
  7326. }
  7327. std::string decompressed_data;
  7328. {
  7329. httplib::detail::gzip_decompressor decompressor;
  7330. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7331. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7332. size_t chunk_size = 130;
  7333. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7334. chunk_begin += chunk_size) {
  7335. size_t current_chunk_size =
  7336. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7337. bool result = decompressor.decompress(
  7338. compressed_data.data() + chunk_begin, current_chunk_size,
  7339. [&](const char *decompressed_data_chunk,
  7340. size_t decompressed_data_chunk_size) {
  7341. decompressed_data.insert(decompressed_data.size(),
  7342. decompressed_data_chunk,
  7343. decompressed_data_chunk_size);
  7344. return true;
  7345. });
  7346. ASSERT_TRUE(result);
  7347. }
  7348. }
  7349. ASSERT_EQ(data, decompressed_data);
  7350. }
  7351. TEST(GzipDecompressor, DeflateDecompression) {
  7352. std::string original_text = "Raw deflate without gzip";
  7353. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7354. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7355. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7356. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7357. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7358. std::string decompressed_data;
  7359. {
  7360. httplib::detail::gzip_decompressor decompressor;
  7361. bool result = decompressor.decompress(
  7362. compressed_data.data(), compressed_data.size(),
  7363. [&](const char *decompressed_data_chunk,
  7364. size_t decompressed_data_chunk_size) {
  7365. decompressed_data.insert(decompressed_data.size(),
  7366. decompressed_data_chunk,
  7367. decompressed_data_chunk_size);
  7368. return true;
  7369. });
  7370. ASSERT_TRUE(result);
  7371. }
  7372. ASSERT_EQ(original_text, decompressed_data);
  7373. }
  7374. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7375. std::string original_text = "Raw deflate without gzip";
  7376. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7377. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7378. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7379. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7380. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7381. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7382. std::string decompressed_data;
  7383. {
  7384. httplib::detail::gzip_decompressor decompressor;
  7385. bool result = decompressor.decompress(
  7386. compressed_data.data(), compressed_data.size(),
  7387. [&](const char *decompressed_data_chunk,
  7388. size_t decompressed_data_chunk_size) {
  7389. decompressed_data.insert(decompressed_data.size(),
  7390. decompressed_data_chunk,
  7391. decompressed_data_chunk_size);
  7392. return true;
  7393. });
  7394. ASSERT_TRUE(result);
  7395. }
  7396. ASSERT_EQ(original_text, decompressed_data);
  7397. }
  7398. #endif
  7399. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7400. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7401. Headers headers;
  7402. headers.emplace("Accept-Encoding", "br");
  7403. auto res = cli_.Get("/streamed-chunked", headers);
  7404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7405. EXPECT_EQ(StatusCode::OK_200, res->status);
  7406. EXPECT_EQ(std::string("123456789"), res->body);
  7407. }
  7408. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7409. Headers headers;
  7410. headers.emplace("Accept-Encoding", "br");
  7411. auto res = cli_.Get("/streamed-chunked2", headers);
  7412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7413. EXPECT_EQ(StatusCode::OK_200, res->status);
  7414. EXPECT_EQ(std::string("123456789"), res->body);
  7415. }
  7416. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7417. cli_.set_compress(true);
  7418. auto res = cli_.Put(
  7419. "/put", 3,
  7420. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7421. sink.os << "PUT";
  7422. return true;
  7423. },
  7424. "text/plain");
  7425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7426. EXPECT_EQ(StatusCode::OK_200, res->status);
  7427. EXPECT_EQ("PUT", res->body);
  7428. }
  7429. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7430. cli_.set_compress(true);
  7431. auto res = cli_.Put(
  7432. "/put",
  7433. [](size_t /*offset*/, DataSink &sink) {
  7434. sink.os << "PUT";
  7435. sink.done();
  7436. return true;
  7437. },
  7438. "text/plain");
  7439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7440. EXPECT_EQ(StatusCode::OK_200, res->status);
  7441. EXPECT_EQ("PUT", res->body);
  7442. }
  7443. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7444. cli_.set_compress(true);
  7445. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7447. EXPECT_EQ(StatusCode::OK_200, res->status);
  7448. EXPECT_EQ(LARGE_DATA, res->body);
  7449. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7450. }
  7451. #endif
  7452. TEST_F(ServerTest, Patch) {
  7453. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7455. EXPECT_EQ(StatusCode::OK_200, res->status);
  7456. EXPECT_EQ("PATCH", res->body);
  7457. }
  7458. TEST_F(ServerTest, Delete) {
  7459. auto res = cli_.Delete("/delete");
  7460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7461. EXPECT_EQ(StatusCode::OK_200, res->status);
  7462. EXPECT_EQ("DELETE", res->body);
  7463. }
  7464. TEST_F(ServerTest, DeleteContentReceiver) {
  7465. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7467. EXPECT_EQ(StatusCode::OK_200, res->status);
  7468. EXPECT_EQ("content", res->body);
  7469. }
  7470. TEST_F(ServerTest, Options) {
  7471. auto res = cli_.Options("*");
  7472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7473. EXPECT_EQ(StatusCode::OK_200, res->status);
  7474. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7475. EXPECT_TRUE(res->body.empty());
  7476. }
  7477. TEST_F(ServerTest, URL) {
  7478. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7480. EXPECT_EQ(StatusCode::OK_200, res->status);
  7481. }
  7482. TEST_F(ServerTest, ArrayParam) {
  7483. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7485. EXPECT_EQ(StatusCode::OK_200, res->status);
  7486. }
  7487. TEST_F(ServerTest, ArrayParamValues) {
  7488. auto res =
  7489. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7491. EXPECT_EQ(StatusCode::OK_200, res->status);
  7492. }
  7493. TEST_F(ServerTest, NoMultipleHeaders) {
  7494. Headers headers = {{"Content-Length", "5"}};
  7495. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7496. "text/plain");
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_EQ(StatusCode::OK_200, res->status);
  7499. }
  7500. TEST_F(ServerTest, PostContentReceiver) {
  7501. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7503. ASSERT_EQ(StatusCode::OK_200, res->status);
  7504. ASSERT_EQ("content", res->body);
  7505. }
  7506. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7507. UploadFormDataItems items = {
  7508. {"text1", "text default", "", ""},
  7509. {"text2", "aωb", "", ""},
  7510. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7511. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7512. {"file3", "", "", "application/octet-stream"},
  7513. };
  7514. auto res = cli_.Post("/content_receiver", items);
  7515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7516. EXPECT_EQ(StatusCode::OK_200, res->status);
  7517. }
  7518. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7519. UploadFormDataItems items = {
  7520. {"text1", "text default", "", ""},
  7521. {"text2", "aωb", "", ""},
  7522. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7523. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7524. {"file3", "", "", "application/octet-stream"},
  7525. };
  7526. auto boundary = std::string("+++++");
  7527. std::string body;
  7528. for (const auto &item : items) {
  7529. body += "--" + boundary + "\r\n";
  7530. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7531. if (!item.filename.empty()) {
  7532. body += "; filename=\"" + item.filename + "\"";
  7533. }
  7534. body += "\r\n";
  7535. if (!item.content_type.empty()) {
  7536. body += "Content-Type: " + item.content_type + "\r\n";
  7537. }
  7538. body += "\r\n";
  7539. body += item.content + "\r\n";
  7540. }
  7541. body += "--" + boundary + "--\r\n";
  7542. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7543. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7545. EXPECT_EQ(StatusCode::OK_200, res->status);
  7546. }
  7547. TEST(MultipartFormDataTest, FieldEscaping) {
  7548. Server svr;
  7549. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7550. const ContentReader &content_reader) {
  7551. ASSERT_TRUE(req.is_multipart_form_data());
  7552. std::vector<FormData> received;
  7553. content_reader(
  7554. [&](const FormData &file) {
  7555. received.push_back(file);
  7556. return true;
  7557. },
  7558. [&](const char *data, size_t data_length) {
  7559. received.back().content.append(data, data_length);
  7560. return true;
  7561. });
  7562. // '"', CR and LF in names and filenames are escaped following the
  7563. // WHATWG HTML standard, so each part still parses as a single part
  7564. // with no injected headers. Content types get CR/LF escaped too,
  7565. // while '"' (legal there, e.g. quoted charset) is preserved.
  7566. ASSERT_EQ(4U, received.size());
  7567. EXPECT_EQ("na%22me", received[0].name);
  7568. EXPECT_EQ("quoted name", received[0].content);
  7569. EXPECT_EQ("file", received[1].name);
  7570. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7571. received[1].filename);
  7572. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7573. EXPECT_EQ("injected", received[1].content);
  7574. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7575. EXPECT_EQ("my%22file.txt", received[2].filename);
  7576. EXPECT_EQ("cr lf name", received[2].content);
  7577. EXPECT_EQ("typed", received[3].name);
  7578. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7579. received[3].content_type);
  7580. EXPECT_EQ("typed content", received[3].content);
  7581. });
  7582. auto port = svr.bind_to_any_port("localhost");
  7583. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7584. auto se = detail::scope_exit([&] {
  7585. svr.stop();
  7586. t.join();
  7587. ASSERT_FALSE(svr.is_running());
  7588. });
  7589. svr.wait_until_ready();
  7590. Client cli("localhost", port);
  7591. UploadFormDataItems items = {
  7592. {"na\"me", "quoted name", "", ""},
  7593. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7594. "application/octet-stream"},
  7595. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7596. {"typed", "typed content", "",
  7597. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7598. };
  7599. auto res = cli.Post("/post", items);
  7600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7601. EXPECT_EQ(StatusCode::OK_200, res->status);
  7602. }
  7603. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7604. const UploadFormDataItems items = {
  7605. {"name1", "Content 1", "", ""},
  7606. {"name2", "Content 2", "file2.txt", "text/plain"},
  7607. };
  7608. Server svr;
  7609. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7610. const ContentReader &content_reader) {
  7611. ASSERT_TRUE(req.is_multipart_form_data());
  7612. std::vector<FormData> received;
  7613. content_reader(
  7614. [&](const FormData &file) {
  7615. received.push_back(file);
  7616. return true;
  7617. },
  7618. [&](const char *data, size_t data_length) {
  7619. received.back().content.append(data, data_length);
  7620. return true;
  7621. });
  7622. ASSERT_EQ(2U, received.size());
  7623. EXPECT_EQ("name1", received[0].name);
  7624. EXPECT_EQ("Content 1", received[0].content);
  7625. EXPECT_EQ("name2", received[1].name);
  7626. EXPECT_EQ("Content 2", received[1].content);
  7627. EXPECT_EQ("file2.txt", received[1].filename);
  7628. EXPECT_EQ("text/plain", received[1].content_type);
  7629. });
  7630. auto port = svr.bind_to_any_port("localhost");
  7631. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7632. auto se = detail::scope_exit([&] {
  7633. svr.stop();
  7634. t.join();
  7635. ASSERT_FALSE(svr.is_running());
  7636. });
  7637. svr.wait_until_ready();
  7638. Client cli("localhost", port);
  7639. // Whole-body serialization with a generated boundary
  7640. {
  7641. MultipartFormDataWriter writer;
  7642. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7643. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7644. writer.content_type());
  7645. auto body = writer.serialize(items);
  7646. EXPECT_EQ(body.size(), writer.content_length(items));
  7647. auto res = cli.Post("/post", body, writer.content_type());
  7648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7649. EXPECT_EQ(StatusCode::OK_200, res->status);
  7650. }
  7651. // Per-part framing with a custom boundary via a content provider
  7652. {
  7653. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7654. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7655. MultipartFormDataWriter writer("custom-boundary_123");
  7656. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7657. std::string body;
  7658. for (const auto &item : items) {
  7659. body += writer.item_begin(item);
  7660. body += item.content;
  7661. body += MultipartFormDataWriter::item_end();
  7662. }
  7663. body += writer.finish();
  7664. EXPECT_EQ(body.size(), writer.content_length(items));
  7665. auto res = cli.Post(
  7666. "/post", body.size(),
  7667. [&](size_t offset, size_t length, DataSink &sink) {
  7668. sink.write(body.data() + offset, length);
  7669. return true;
  7670. },
  7671. writer.content_type());
  7672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7673. EXPECT_EQ(StatusCode::OK_200, res->status);
  7674. }
  7675. }
  7676. TEST_F(ServerTest, PostContentReceiverGzip) {
  7677. cli_.set_compress(true);
  7678. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7680. ASSERT_EQ(StatusCode::OK_200, res->status);
  7681. ASSERT_EQ("content", res->body);
  7682. }
  7683. TEST_F(ServerTest, PutContentReceiver) {
  7684. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7686. ASSERT_EQ(StatusCode::OK_200, res->status);
  7687. ASSERT_EQ("content", res->body);
  7688. }
  7689. TEST_F(ServerTest, PatchContentReceiver) {
  7690. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7692. ASSERT_EQ(StatusCode::OK_200, res->status);
  7693. ASSERT_EQ("content", res->body);
  7694. }
  7695. template <typename ClientType>
  7696. void TestWithHeadersAndContentReceiver(
  7697. ClientType &cli,
  7698. std::function<Result(ClientType &, const std::string &, const Headers &,
  7699. const std::string &, const std::string &,
  7700. ContentReceiver, DownloadProgress)>
  7701. request_func) {
  7702. Headers headers;
  7703. headers.emplace("X-Custom-Header", "test-value");
  7704. std::string received_body;
  7705. auto res = request_func(
  7706. cli, "/content_receiver", headers, "content", "application/json",
  7707. [&](const char *data, size_t data_length) {
  7708. received_body.append(data, data_length);
  7709. return true;
  7710. },
  7711. nullptr);
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(StatusCode::OK_200, res->status);
  7714. EXPECT_EQ("content", received_body);
  7715. }
  7716. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7717. #ifdef CPPHTTPLIB_SSL_ENABLED
  7718. using ClientT = SSLClient;
  7719. #else
  7720. using ClientT = Client;
  7721. #endif
  7722. TestWithHeadersAndContentReceiver<ClientT>(
  7723. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7724. const std::string &body, const std::string &content_type,
  7725. ContentReceiver receiver, DownloadProgress progress) {
  7726. return cli.Post(path, headers, body, content_type, receiver, progress);
  7727. });
  7728. }
  7729. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7730. #ifdef CPPHTTPLIB_SSL_ENABLED
  7731. using ClientT = SSLClient;
  7732. #else
  7733. using ClientT = Client;
  7734. #endif
  7735. TestWithHeadersAndContentReceiver<ClientT>(
  7736. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7737. const std::string &body, const std::string &content_type,
  7738. ContentReceiver receiver, DownloadProgress progress) {
  7739. return cli.Put(path, headers, body, content_type, receiver, progress);
  7740. });
  7741. }
  7742. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7743. #ifdef CPPHTTPLIB_SSL_ENABLED
  7744. using ClientT = SSLClient;
  7745. #else
  7746. using ClientT = Client;
  7747. #endif
  7748. TestWithHeadersAndContentReceiver<ClientT>(
  7749. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7750. const std::string &body, const std::string &content_type,
  7751. ContentReceiver receiver, DownloadProgress progress) {
  7752. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7753. });
  7754. }
  7755. template <typename ClientType>
  7756. void TestWithHeadersAndContentReceiverWithProgress(
  7757. ClientType &cli,
  7758. std::function<Result(ClientType &, const std::string &, const Headers &,
  7759. const std::string &, const std::string &,
  7760. ContentReceiver, DownloadProgress)>
  7761. request_func) {
  7762. Headers headers;
  7763. headers.emplace("X-Test-Header", "progress-test");
  7764. std::string received_body;
  7765. auto progress_called = false;
  7766. auto res = request_func(
  7767. cli, "/content_receiver", headers, "content", "text/plain",
  7768. [&](const char *data, size_t data_length) {
  7769. received_body.append(data, data_length);
  7770. return true;
  7771. },
  7772. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7773. progress_called = true;
  7774. return true;
  7775. });
  7776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7777. EXPECT_EQ(StatusCode::OK_200, res->status);
  7778. EXPECT_EQ("content", received_body);
  7779. EXPECT_TRUE(progress_called);
  7780. }
  7781. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7782. #ifdef CPPHTTPLIB_SSL_ENABLED
  7783. using ClientT = SSLClient;
  7784. #else
  7785. using ClientT = Client;
  7786. #endif
  7787. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7788. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7789. const std::string &body, const std::string &content_type,
  7790. ContentReceiver receiver, DownloadProgress progress) {
  7791. return cli.Post(path, headers, body, content_type, receiver, progress);
  7792. });
  7793. }
  7794. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7795. #ifdef CPPHTTPLIB_SSL_ENABLED
  7796. using ClientT = SSLClient;
  7797. #else
  7798. using ClientT = Client;
  7799. #endif
  7800. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7801. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7802. const std::string &body, const std::string &content_type,
  7803. ContentReceiver receiver, DownloadProgress progress) {
  7804. return cli.Put(path, headers, body, content_type, receiver, progress);
  7805. });
  7806. }
  7807. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7808. #ifdef CPPHTTPLIB_SSL_ENABLED
  7809. using ClientT = SSLClient;
  7810. #else
  7811. using ClientT = Client;
  7812. #endif
  7813. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7814. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7815. const std::string &body, const std::string &content_type,
  7816. ContentReceiver receiver, DownloadProgress progress) {
  7817. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7818. });
  7819. }
  7820. template <typename ClientType>
  7821. void TestWithHeadersAndContentReceiverError(
  7822. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7823. const Headers &, const std::string &,
  7824. const std::string &, ContentReceiver)>
  7825. request_func) {
  7826. Headers headers;
  7827. headers.emplace("X-Error-Test", "true");
  7828. std::string received_body;
  7829. auto receiver_failed = false;
  7830. auto res =
  7831. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7832. [&](const char *data, size_t data_length) {
  7833. received_body.append(data, data_length);
  7834. receiver_failed = true;
  7835. return false;
  7836. });
  7837. ASSERT_FALSE(res);
  7838. EXPECT_TRUE(receiver_failed);
  7839. }
  7840. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7841. #ifdef CPPHTTPLIB_SSL_ENABLED
  7842. using ClientT = SSLClient;
  7843. #else
  7844. using ClientT = Client;
  7845. #endif
  7846. TestWithHeadersAndContentReceiverError<ClientT>(
  7847. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7848. const std::string &body, const std::string &content_type,
  7849. ContentReceiver receiver) {
  7850. return cli.Post(path, headers, body, content_type, receiver);
  7851. });
  7852. }
  7853. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7854. #ifdef CPPHTTPLIB_SSL_ENABLED
  7855. using ClientT = SSLClient;
  7856. #else
  7857. using ClientT = Client;
  7858. #endif
  7859. TestWithHeadersAndContentReceiverError<ClientT>(
  7860. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7861. const std::string &body, const std::string &content_type,
  7862. ContentReceiver receiver) {
  7863. return cli.Put(path, headers, body, content_type, receiver);
  7864. });
  7865. }
  7866. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7867. #ifdef CPPHTTPLIB_SSL_ENABLED
  7868. using ClientT = SSLClient;
  7869. #else
  7870. using ClientT = Client;
  7871. #endif
  7872. TestWithHeadersAndContentReceiverError<ClientT>(
  7873. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7874. const std::string &body, const std::string &content_type,
  7875. ContentReceiver receiver) {
  7876. return cli.Patch(path, headers, body, content_type, receiver);
  7877. });
  7878. }
  7879. TEST_F(ServerTest, PostQueryStringAndBody) {
  7880. auto res =
  7881. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7883. ASSERT_EQ(StatusCode::OK_200, res->status);
  7884. }
  7885. TEST_F(ServerTest, HTTP2Magic) {
  7886. Request req;
  7887. req.method = "PRI";
  7888. req.path = "*";
  7889. req.body = "SM";
  7890. auto res = std::make_shared<Response>();
  7891. auto error = Error::Success;
  7892. auto ret = cli_.send(req, *res, error);
  7893. ASSERT_TRUE(ret);
  7894. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7895. }
  7896. TEST_F(ServerTest, KeepAlive) {
  7897. auto res = cli_.Get("/hi");
  7898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7901. EXPECT_EQ("Hello World!", res->body);
  7902. res = cli_.Get("/hi");
  7903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7904. EXPECT_EQ(StatusCode::OK_200, res->status);
  7905. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7906. EXPECT_EQ("Hello World!", res->body);
  7907. res = cli_.Get("/hi");
  7908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7909. EXPECT_EQ(StatusCode::OK_200, res->status);
  7910. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7911. EXPECT_EQ("Hello World!", res->body);
  7912. res = cli_.Get("/not-exist");
  7913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7914. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7915. res = cli_.Post("/empty", "", "text/plain");
  7916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7917. EXPECT_EQ(StatusCode::OK_200, res->status);
  7918. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7919. EXPECT_EQ("empty", res->body);
  7920. EXPECT_EQ("close", res->get_header_value("Connection"));
  7921. res = cli_.Post(
  7922. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7923. "text/plain");
  7924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7925. EXPECT_EQ(StatusCode::OK_200, res->status);
  7926. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7927. EXPECT_EQ("empty", res->body);
  7928. cli_.set_keep_alive(false);
  7929. res = cli_.Get("/last-request");
  7930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7931. EXPECT_EQ(StatusCode::OK_200, res->status);
  7932. EXPECT_EQ("close", res->get_header_value("Connection"));
  7933. }
  7934. TEST_F(ServerTest, TooManyRedirect) {
  7935. cli_.set_follow_location(true);
  7936. auto res = cli_.Get("/redirect/0");
  7937. ASSERT_TRUE(!res);
  7938. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7939. }
  7940. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7941. Request req;
  7942. req.method = "FOOBAR";
  7943. req.path = "/hi";
  7944. cli_.set_keep_alive(true);
  7945. auto res = cli_.send(req);
  7946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7947. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7948. EXPECT_EQ("close", res->get_header_value("Connection"));
  7949. EXPECT_FALSE(cli_.is_socket_open());
  7950. }
  7951. TEST_F(ServerTest, CustomRouteReadsBody) {
  7952. const std::string xml =
  7953. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7954. Request req;
  7955. req.method = "PROPFIND";
  7956. req.path = "/dav/dir";
  7957. req.set_header("Depth", "1");
  7958. req.body = xml;
  7959. auto res = cli_.send(req);
  7960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7961. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7962. EXPECT_EQ(xml, res->body);
  7963. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7964. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7965. }
  7966. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7967. Request req;
  7968. req.method = "PROPFIND";
  7969. req.path = "/dav/42";
  7970. auto res = cli_.send(req);
  7971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7972. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7973. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7974. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7975. }
  7976. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7977. Request req;
  7978. req.method = "PROPFIND";
  7979. req.path = "/dav-re/123";
  7980. auto res = cli_.send(req);
  7981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7982. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7983. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7984. }
  7985. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7986. Request req;
  7987. req.method = "MKCOL";
  7988. req.path = "/dav-mkcol";
  7989. auto res = cli_.send(req);
  7990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7991. EXPECT_EQ(StatusCode::Created_201, res->status);
  7992. }
  7993. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7994. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7995. Request req;
  7996. req.method = "REPORT";
  7997. req.path = "/dav-report";
  7998. req.body = xml;
  7999. auto res = cli_.send(req);
  8000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8001. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8002. EXPECT_EQ(xml, res->body);
  8003. }
  8004. // A content reader route must fire even when the request carries no body,
  8005. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8006. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8007. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8008. Request req;
  8009. req.method = "REPORT";
  8010. req.path = "/dav-report";
  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("0", res->get_header_value("x-body-size"));
  8015. }
  8016. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8017. Request req;
  8018. req.method = "PROPFIND";
  8019. req.path = "/not-dav";
  8020. auto res = cli_.send(req);
  8021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8022. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8023. }
  8024. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8025. Request req;
  8026. req.method = "UNLOCK";
  8027. req.path = "/dav/dir";
  8028. cli_.set_keep_alive(true);
  8029. auto res = cli_.send(req);
  8030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8031. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8032. EXPECT_EQ("close", res->get_header_value("Connection"));
  8033. EXPECT_FALSE(cli_.is_socket_open());
  8034. }
  8035. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8036. // The mount point serves this path, but only for GET and HEAD.
  8037. auto get_res = cli_.Get("/dir/index.html");
  8038. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8039. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8040. Request req;
  8041. req.method = "PROPFIND";
  8042. req.path = "/dir/index.html";
  8043. auto res = cli_.send(req);
  8044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8045. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8046. }
  8047. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8048. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8049. cli_.set_keep_alive(true);
  8050. for (auto i = 0; i < 2; i++) {
  8051. Request req;
  8052. req.method = "PROPFIND";
  8053. req.path = "/dav/dir";
  8054. req.body = xml;
  8055. auto res = cli_.send(req);
  8056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8057. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8058. EXPECT_EQ(xml, res->body);
  8059. EXPECT_TRUE(cli_.is_socket_open());
  8060. }
  8061. // A built-in method must still be served on the same connection.
  8062. cli_.set_keep_alive(false);
  8063. auto res = cli_.Get("/hi");
  8064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8065. EXPECT_EQ(StatusCode::OK_200, res->status);
  8066. EXPECT_EQ("close", res->get_header_value("Connection"));
  8067. }
  8068. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8069. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8070. Request req;
  8071. req.method = "PROPFIND";
  8072. req.path = "/dav/dir";
  8073. req.set_header("Expect", "100-continue");
  8074. req.body = xml;
  8075. auto res = cli_.send(req);
  8076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8077. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8078. EXPECT_EQ(xml, res->body);
  8079. }
  8080. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8081. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8082. TEST_F(ServerTest, Gzip) {
  8083. Headers headers;
  8084. headers.emplace("Accept-Encoding", "gzip, deflate");
  8085. auto res = cli_.Get("/compress", headers);
  8086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8087. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8088. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8089. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8090. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8091. "7890123456789012345678901234567890",
  8092. res->body);
  8093. EXPECT_EQ(StatusCode::OK_200, res->status);
  8094. }
  8095. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8096. Headers headers;
  8097. headers.emplace("Accept-Encoding", "gzip, deflate");
  8098. auto res = cli_.Get("/compress-with-charset", headers);
  8099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8100. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8101. EXPECT_EQ("application/json; charset=utf-8",
  8102. res->get_header_value("Content-Type"));
  8103. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8104. "7890123456789012345678901234567890",
  8105. res->body);
  8106. EXPECT_EQ(StatusCode::OK_200, res->status);
  8107. }
  8108. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8109. Headers headers;
  8110. headers.emplace("Accept-Encoding", "");
  8111. auto res = cli_.Get("/compress", headers);
  8112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8113. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8114. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8115. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8116. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8117. "7890123456789012345678901234567890",
  8118. res->body);
  8119. EXPECT_EQ(StatusCode::OK_200, res->status);
  8120. }
  8121. TEST_F(ServerTest, GzipWithContentReceiver) {
  8122. Headers headers;
  8123. headers.emplace("Accept-Encoding", "gzip, deflate");
  8124. std::string body;
  8125. auto res = cli_.Get("/compress", headers,
  8126. [&](const char *data, uint64_t data_length) {
  8127. EXPECT_EQ(100U, data_length);
  8128. body.append(data, data_length);
  8129. return true;
  8130. });
  8131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8132. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8133. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8134. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8135. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8136. "7890123456789012345678901234567890",
  8137. body);
  8138. EXPECT_EQ(StatusCode::OK_200, res->status);
  8139. }
  8140. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8141. Headers headers;
  8142. headers.emplace("Accept-Encoding", "gzip, deflate");
  8143. cli_.set_decompress(false);
  8144. auto res = cli_.Get("/compress", headers);
  8145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8146. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8147. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8148. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8149. EXPECT_EQ(33U, res->body.size());
  8150. EXPECT_EQ(StatusCode::OK_200, res->status);
  8151. }
  8152. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8153. Headers headers;
  8154. headers.emplace("Accept-Encoding", "");
  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_TRUE(res->get_header_value("Content-Encoding").empty());
  8164. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8165. EXPECT_EQ("100", 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, NoGzip) {
  8172. Headers headers;
  8173. headers.emplace("Accept-Encoding", "gzip, deflate");
  8174. auto res = cli_.Get("/nocompress", headers);
  8175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8176. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8177. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8178. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8179. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8180. "7890123456789012345678901234567890",
  8181. res->body);
  8182. EXPECT_EQ(StatusCode::OK_200, res->status);
  8183. }
  8184. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8185. Headers headers;
  8186. headers.emplace("Accept-Encoding", "gzip, deflate");
  8187. std::string body;
  8188. auto res = cli_.Get("/nocompress", headers,
  8189. [&](const char *data, uint64_t data_length) {
  8190. EXPECT_EQ(100U, data_length);
  8191. body.append(data, data_length);
  8192. return true;
  8193. });
  8194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8195. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8196. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8197. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8198. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8199. "7890123456789012345678901234567890",
  8200. body);
  8201. EXPECT_EQ(StatusCode::OK_200, res->status);
  8202. }
  8203. TEST_F(ServerTest, MultipartFormDataGzip) {
  8204. UploadFormDataItems items = {
  8205. {"key1", "test", "", ""},
  8206. {"key2", "--abcdefg123", "", ""},
  8207. };
  8208. cli_.set_compress(true);
  8209. auto res = cli_.Post("/compress-multipart", items);
  8210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8211. EXPECT_EQ(StatusCode::OK_200, res->status);
  8212. }
  8213. #endif
  8214. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8215. // Static file compression is opt-in, so these run their own server rather than
  8216. // flipping it on for the shared ServerTest fixture, which would silently
  8217. // rewrite what every other static file test is asserting.
  8218. class StaticFileCompressionTest : public ::testing::Test {
  8219. protected:
  8220. void TearDown() override {
  8221. if (t_.joinable()) {
  8222. svr_.stop();
  8223. t_.join();
  8224. }
  8225. }
  8226. int start(const std::function<void(Server &)> &configure = nullptr) {
  8227. // Serves the same tree as a directory of build-time compressed assets
  8228. // would be served: the mount point names the coding the files are already
  8229. // stored in. Registered before "/" so it is the one that matches.
  8230. svr_.set_mount_point("/pre-encoded", "./www",
  8231. {{"Content-Encoding", "gzip"}});
  8232. svr_.set_mount_point("/", "./www");
  8233. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8234. res.set_file_content("./www/dir/index.html", "text/html");
  8235. });
  8236. svr_.Get("/pre-encoded-file-content",
  8237. [](const Request & /*req*/, Response &res) {
  8238. res.set_header("Content-Encoding", "gzip");
  8239. res.set_file_content("./www/dir/index.html", "text/html");
  8240. });
  8241. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8242. res.set_content_provider(
  8243. 6, "text/plain",
  8244. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8245. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8246. return true;
  8247. });
  8248. });
  8249. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8250. res.set_content_provider(
  8251. 1000, "text/plain",
  8252. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8253. if (offset < 100) {
  8254. std::string data(100, 'A');
  8255. sink.write(data.data(), data.size());
  8256. return true;
  8257. }
  8258. std::this_thread::sleep_for(std::chrono::seconds(2));
  8259. std::string data(900, 'B');
  8260. sink.write(data.data(), data.size());
  8261. return true;
  8262. });
  8263. });
  8264. if (configure) { configure(svr_); }
  8265. auto port = svr_.bind_to_any_port(HOST);
  8266. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8267. svr_.wait_until_ready();
  8268. return port;
  8269. }
  8270. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8271. // Every file under ./www except 1MB.txt is smaller than the default
  8272. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8273. // it out of the way.
  8274. static void enable_without_floor(Server &svr) {
  8275. svr.set_static_file_compression(true);
  8276. svr.set_static_file_compression_min_length(0);
  8277. }
  8278. Server svr_;
  8279. std::thread t_;
  8280. };
  8281. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8282. auto port = start();
  8283. Client cli(HOST, port);
  8284. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8286. EXPECT_EQ(StatusCode::OK_200, res->status);
  8287. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8288. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8289. EXPECT_EQ(1048576U, res->body.size());
  8290. }
  8291. TEST_F(StaticFileCompressionTest, MountPoint) {
  8292. auto port = start(enable);
  8293. Client cli(HOST, port);
  8294. cli.set_decompress(false);
  8295. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8297. EXPECT_EQ(StatusCode::OK_200, res->status);
  8298. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8299. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8300. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8301. // The response stays self-delimiting: a length, not a chunked body.
  8302. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8303. EXPECT_EQ(std::to_string(res->body.size()),
  8304. res->get_header_value("Content-Length"));
  8305. EXPECT_LT(res->body.size(), 1048576U);
  8306. EXPECT_FALSE(res->body.empty());
  8307. }
  8308. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8309. auto port = start(enable);
  8310. Client cli(HOST, port);
  8311. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8313. EXPECT_EQ(StatusCode::OK_200, res->status);
  8314. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8315. EXPECT_EQ(1048576U, res->body.size());
  8316. }
  8317. TEST_F(StaticFileCompressionTest, FileContent) {
  8318. auto port = start(enable_without_floor);
  8319. Client cli(HOST, port);
  8320. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8322. EXPECT_EQ(StatusCode::OK_200, res->status);
  8323. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8324. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8325. EXPECT_EQ(104U, res->body.size());
  8326. }
  8327. // A handler that serves an already-encoded file names the coding itself. The
  8328. // file-backed path decided its coding from Accept-Encoding and the content
  8329. // type alone, so it compressed the stored bytes a second time and appended a
  8330. // second Content-Encoding field line.
  8331. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8332. auto port = start(enable_without_floor);
  8333. Client cli(HOST, port);
  8334. cli.set_decompress(false);
  8335. auto res = cli.Get("/pre-encoded-file-content",
  8336. Headers{{"Accept-Encoding", "gzip"}});
  8337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8338. EXPECT_EQ(StatusCode::OK_200, res->status);
  8339. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8340. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8341. // Vary belongs to a coding the server chose, and it chose none here.
  8342. EXPECT_FALSE(res->has_header("Vary"));
  8343. // The file travels exactly as it is stored on disk.
  8344. EXPECT_EQ(104U, res->body.size());
  8345. }
  8346. // The 1MB file clears the default floor, so this one runs the configuration a
  8347. // deployment would actually have.
  8348. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8349. auto port = start(enable);
  8350. Client cli(HOST, port);
  8351. cli.set_decompress(false);
  8352. auto res =
  8353. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8355. EXPECT_EQ(StatusCode::OK_200, res->status);
  8356. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8357. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8358. EXPECT_FALSE(res->has_header("Vary"));
  8359. EXPECT_EQ(1048576U, res->body.size());
  8360. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8361. }
  8362. TEST_F(StaticFileCompressionTest, Head) {
  8363. auto port = start(enable);
  8364. Client cli(HOST, port);
  8365. cli.set_decompress(false);
  8366. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8367. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8368. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8370. EXPECT_EQ(StatusCode::OK_200, res->status);
  8371. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8372. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8373. // HEAD still reports the size a GET would return.
  8374. EXPECT_EQ(get->get_header_value("Content-Length"),
  8375. res->get_header_value("Content-Length"));
  8376. EXPECT_TRUE(res->body.empty());
  8377. }
  8378. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8379. auto port = start(enable);
  8380. Client cli(HOST, port);
  8381. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8382. {"Accept-Encoding", "gzip"}});
  8383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8384. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8385. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8386. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8387. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8388. EXPECT_EQ("cd", res->body);
  8389. }
  8390. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8391. auto port = start(enable);
  8392. Client cli(HOST, port);
  8393. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8395. EXPECT_EQ(StatusCode::OK_200, res->status);
  8396. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8397. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8398. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8399. }
  8400. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8401. auto port = start(enable);
  8402. Client cli(HOST, port);
  8403. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8405. EXPECT_EQ(StatusCode::OK_200, res->status);
  8406. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8407. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8408. EXPECT_TRUE(res->body.empty());
  8409. }
  8410. TEST_F(StaticFileCompressionTest, MinLength) {
  8411. auto port = start(enable);
  8412. Client cli(HOST, port);
  8413. // 104 bytes, well under the default floor. Compressing it would add the
  8414. // gzip header and trailer to a body that already fits in one packet.
  8415. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8417. EXPECT_EQ(StatusCode::OK_200, res->status);
  8418. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8419. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8420. }
  8421. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8422. auto port = start([](Server &svr) {
  8423. svr.set_static_file_compression(true);
  8424. svr.set_static_file_compression_min_length(1);
  8425. });
  8426. Client cli(HOST, port);
  8427. cli.set_decompress(false);
  8428. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8430. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8431. // A 9-byte file comes back larger than it went in, because gzip's header and
  8432. // trailer outweigh anything deflate can save. That is the end of the range
  8433. // the floor exists to keep out.
  8434. EXPECT_GT(res->body.size(), 9U);
  8435. }
  8436. TEST_F(StaticFileCompressionTest, MaxLength) {
  8437. auto port = start([](Server &svr) {
  8438. svr.set_static_file_compression(true);
  8439. svr.set_static_file_compression_min_length(0);
  8440. svr.set_static_file_compression_max_length(1024);
  8441. });
  8442. Client cli(HOST, port);
  8443. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8444. // defines `small` as a macro on Windows.
  8445. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8446. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8447. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8448. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8449. // Under it: compressed.
  8450. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8451. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8452. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8453. }
  8454. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8455. auto port = start(enable_without_floor);
  8456. Client cli(HOST, port);
  8457. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8458. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8459. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8460. auto identity_etag = identity->get_header_value("ETag");
  8461. ASSERT_FALSE(identity_etag.empty());
  8462. auto gzipped =
  8463. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8464. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8465. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8466. auto gzip_etag = gzipped->get_header_value("ETag");
  8467. ASSERT_FALSE(gzip_etag.empty());
  8468. // Two representations, two validators.
  8469. EXPECT_NE(identity_etag, gzip_etag);
  8470. // Each one revalidates against the request that would produce it...
  8471. auto fresh =
  8472. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8473. {"If-None-Match", gzip_etag}});
  8474. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8475. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8476. auto fresh_identity =
  8477. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8478. {"If-None-Match", identity_etag}});
  8479. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8480. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8481. // ...and not against the other representation.
  8482. auto crossed =
  8483. cli.Get("/dir/index.html",
  8484. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8485. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8486. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8487. }
  8488. // The opt-in covers responses the server reads off disk itself. A caller's own
  8489. // known-length provider keeps its Content-Length and, more importantly, keeps
  8490. // delivering incrementally: routing it through a compressor would hold every
  8491. // write back until zlib's window filled.
  8492. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8493. auto port = start(enable);
  8494. Client cli(HOST, port);
  8495. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8497. EXPECT_EQ(StatusCode::OK_200, res->status);
  8498. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8499. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8500. EXPECT_EQ("aaabbb", res->body);
  8501. }
  8502. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8503. auto port = start(enable);
  8504. Client cli(HOST, port);
  8505. cli.set_read_timeout(1, 0);
  8506. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8507. Headers{{"Accept-Encoding", "gzip"}});
  8508. ASSERT_TRUE(handle.is_valid());
  8509. // The provider writes 100 bytes and then stalls for longer than the read
  8510. // timeout. Those first bytes have to arrive anyway: run the response through
  8511. // a compressor and zlib holds them until its window fills, so the read would
  8512. // come back empty instead.
  8513. char buf[256];
  8514. auto n = handle.read(buf, sizeof(buf));
  8515. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8516. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8517. }
  8518. #endif
  8519. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8520. TEST_F(ServerTest, Brotli) {
  8521. Headers headers;
  8522. headers.emplace("Accept-Encoding", "br");
  8523. auto res = cli_.Get("/compress", headers);
  8524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8525. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8526. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8527. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8528. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8529. "7890123456789012345678901234567890",
  8530. res->body);
  8531. EXPECT_EQ(StatusCode::OK_200, res->status);
  8532. }
  8533. #endif
  8534. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8535. TEST_F(ServerTest, Zstd) {
  8536. Headers headers;
  8537. headers.emplace("Accept-Encoding", "zstd");
  8538. auto res = cli_.Get("/compress", headers);
  8539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8540. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8541. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8542. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8543. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8544. "7890123456789012345678901234567890",
  8545. res->body);
  8546. EXPECT_EQ(StatusCode::OK_200, res->status);
  8547. }
  8548. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8549. Headers headers;
  8550. headers.emplace("Accept-Encoding", "");
  8551. auto res = cli_.Get("/compress", headers);
  8552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8553. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8554. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8555. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8556. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8557. "7890123456789012345678901234567890",
  8558. res->body);
  8559. EXPECT_EQ(StatusCode::OK_200, res->status);
  8560. }
  8561. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8562. Headers headers;
  8563. headers.emplace("Accept-Encoding", "zstd");
  8564. std::string body;
  8565. auto res = cli_.Get("/compress", headers,
  8566. [&](const char *data, uint64_t data_length) {
  8567. EXPECT_EQ(100U, data_length);
  8568. body.append(data, data_length);
  8569. return true;
  8570. });
  8571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8572. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8573. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8574. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8575. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8576. "7890123456789012345678901234567890",
  8577. body);
  8578. EXPECT_EQ(StatusCode::OK_200, res->status);
  8579. }
  8580. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8581. Headers headers;
  8582. headers.emplace("Accept-Encoding", "zstd");
  8583. cli_.set_decompress(false);
  8584. auto res = cli_.Get("/compress", headers);
  8585. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8586. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8587. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8588. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8590. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8591. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8592. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8593. EXPECT_EQ(StatusCode::OK_200, res->status);
  8594. ASSERT_EQ(26U, res->body.size());
  8595. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8596. 0);
  8597. }
  8598. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8599. Headers headers;
  8600. headers.emplace("Accept-Encoding", "");
  8601. std::string body;
  8602. auto res = cli_.Get("/compress", headers,
  8603. [&](const char *data, uint64_t data_length) {
  8604. EXPECT_EQ(100U, data_length);
  8605. body.append(data, data_length);
  8606. return true;
  8607. });
  8608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8609. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8610. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8611. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8612. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8613. "7890123456789012345678901234567890",
  8614. body);
  8615. EXPECT_EQ(StatusCode::OK_200, res->status);
  8616. }
  8617. TEST_F(ServerTest, NoZstd) {
  8618. Headers headers;
  8619. headers.emplace("Accept-Encoding", "zstd");
  8620. auto res = cli_.Get("/nocompress", headers);
  8621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8622. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8623. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8624. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8625. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8626. "7890123456789012345678901234567890",
  8627. res->body);
  8628. EXPECT_EQ(StatusCode::OK_200, res->status);
  8629. }
  8630. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8631. Headers headers;
  8632. headers.emplace("Accept-Encoding", "zstd");
  8633. std::string body;
  8634. auto res = cli_.Get("/nocompress", headers,
  8635. [&](const char *data, uint64_t data_length) {
  8636. EXPECT_EQ(100U, data_length);
  8637. body.append(data, data_length);
  8638. return true;
  8639. });
  8640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8641. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8642. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8643. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8644. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8645. "7890123456789012345678901234567890",
  8646. body);
  8647. EXPECT_EQ(StatusCode::OK_200, res->status);
  8648. }
  8649. // TODO: How to enable zstd ??
  8650. TEST_F(ServerTest, MultipartFormDataZstd) {
  8651. UploadFormDataItems items = {
  8652. {"key1", "test", "", ""},
  8653. {"key2", "--abcdefg123", "", ""},
  8654. };
  8655. Headers headers;
  8656. headers.emplace("Accept-Encoding", "zstd");
  8657. cli_.set_compress(true);
  8658. auto res = cli_.Post("/compress-multipart", headers, items);
  8659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8660. EXPECT_EQ(StatusCode::OK_200, res->status);
  8661. }
  8662. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8663. Headers headers;
  8664. headers.emplace("Accept-Encoding", "zstd");
  8665. cli_.set_compress(true);
  8666. auto res = cli_.Put(
  8667. "/put", headers, 3,
  8668. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8669. sink.os << "PUT";
  8670. return true;
  8671. },
  8672. "text/plain");
  8673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8674. EXPECT_EQ(StatusCode::OK_200, res->status);
  8675. EXPECT_EQ("PUT", res->body);
  8676. }
  8677. // Pre-compression logging tests
  8678. TEST_F(ServerTest, PreCompressionLogging) {
  8679. // Test data for compression (matches the actual /compress endpoint content)
  8680. const std::string test_content =
  8681. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8682. "3456789012345678901234567890";
  8683. // Variables to capture logging data
  8684. std::string pre_compression_body;
  8685. std::string pre_compression_content_type;
  8686. std::string pre_compression_content_encoding;
  8687. std::string post_compression_body;
  8688. std::string post_compression_content_type;
  8689. std::string post_compression_content_encoding;
  8690. // Set up pre-compression logger
  8691. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8692. const Response &res) {
  8693. pre_compression_body = res.body;
  8694. pre_compression_content_type = res.get_header_value("Content-Type");
  8695. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8696. });
  8697. // Set up post-compression logger
  8698. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8699. post_compression_body = res.body;
  8700. post_compression_content_type = res.get_header_value("Content-Type");
  8701. post_compression_content_encoding =
  8702. res.get_header_value("Content-Encoding");
  8703. });
  8704. // Test with gzip compression
  8705. Headers headers;
  8706. headers.emplace("Accept-Encoding", "gzip");
  8707. auto res = cli_.Get("/compress", headers);
  8708. // Verify response was compressed
  8709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8710. EXPECT_EQ(StatusCode::OK_200, res->status);
  8711. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8712. // Verify pre-compression logger captured uncompressed content
  8713. EXPECT_EQ(test_content, pre_compression_body);
  8714. EXPECT_EQ("text/plain", pre_compression_content_type);
  8715. EXPECT_TRUE(pre_compression_content_encoding
  8716. .empty()); // No encoding header before compression
  8717. // Verify post-compression logger captured compressed content
  8718. EXPECT_NE(test_content,
  8719. post_compression_body); // Should be different after compression
  8720. EXPECT_EQ("text/plain", post_compression_content_type);
  8721. EXPECT_EQ("gzip", post_compression_content_encoding);
  8722. // Verify compressed content is smaller
  8723. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8724. }
  8725. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8726. const std::string test_content =
  8727. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8728. "3456789012345678901234567890";
  8729. std::string pre_compression_body;
  8730. std::string post_compression_body;
  8731. svr_.set_pre_compression_logger(
  8732. [&](const Request & /*req*/, const Response &res) {
  8733. pre_compression_body = res.body;
  8734. });
  8735. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8736. post_compression_body = res.body;
  8737. });
  8738. Headers headers;
  8739. headers.emplace("Accept-Encoding", "br");
  8740. auto res = cli_.Get("/compress", headers);
  8741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8742. EXPECT_EQ(StatusCode::OK_200, res->status);
  8743. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8744. // Verify pre-compression content is uncompressed
  8745. EXPECT_EQ(test_content, pre_compression_body);
  8746. // Verify post-compression content is compressed
  8747. EXPECT_NE(test_content, post_compression_body);
  8748. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8749. }
  8750. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8751. const std::string test_content =
  8752. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8753. "3456789012345678901234567890";
  8754. std::string pre_compression_body;
  8755. std::string post_compression_body;
  8756. svr_.set_pre_compression_logger(
  8757. [&](const Request & /*req*/, const Response &res) {
  8758. pre_compression_body = res.body;
  8759. });
  8760. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8761. post_compression_body = res.body;
  8762. });
  8763. // Request without compression (use /nocompress endpoint)
  8764. Headers headers;
  8765. auto res = cli_.Get("/nocompress", headers);
  8766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8767. EXPECT_EQ(StatusCode::OK_200, res->status);
  8768. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8769. // Pre-compression logger should not be called when no compression is applied
  8770. EXPECT_TRUE(
  8771. pre_compression_body.empty()); // Pre-compression logger not called
  8772. EXPECT_EQ(
  8773. test_content,
  8774. post_compression_body); // Post-compression logger captures final content
  8775. }
  8776. TEST_F(ServerTest, LoggerSeesContentLength) {
  8777. size_t logged_content_length = 0;
  8778. std::string logged_content_length_header;
  8779. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8780. logged_content_length = res.content_length_;
  8781. logged_content_length_header = res.get_header_value("Content-Length");
  8782. });
  8783. auto res = cli_.Get("/nocompress");
  8784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8785. EXPECT_EQ(StatusCode::OK_200, res->status);
  8786. EXPECT_EQ(res->body.size(), logged_content_length);
  8787. EXPECT_EQ(std::to_string(logged_content_length),
  8788. logged_content_length_header);
  8789. }
  8790. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8791. const std::string test_content =
  8792. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8793. "3456789012345678901234567890";
  8794. std::string pre_compression_body;
  8795. bool pre_logger_called = false;
  8796. // Set only pre-compression logger
  8797. svr_.set_pre_compression_logger(
  8798. [&](const Request & /*req*/, const Response &res) {
  8799. pre_compression_body = res.body;
  8800. pre_logger_called = true;
  8801. });
  8802. Headers headers;
  8803. headers.emplace("Accept-Encoding", "gzip");
  8804. auto res = cli_.Get("/compress", headers);
  8805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8806. EXPECT_EQ(StatusCode::OK_200, res->status);
  8807. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8808. // Verify pre-compression logger was called
  8809. EXPECT_TRUE(pre_logger_called);
  8810. EXPECT_EQ(test_content, pre_compression_body);
  8811. }
  8812. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8813. {
  8814. // Test with Expect: 100-continue header - success case
  8815. // Server returns 100 Continue, client sends body, server returns 200 OK
  8816. Request req;
  8817. req.method = "POST";
  8818. req.path = "/post-large";
  8819. req.set_header("Expect", "100-continue");
  8820. req.body = LARGE_DATA;
  8821. Response res;
  8822. auto error = Error::Success;
  8823. cli_.set_keep_alive(true);
  8824. auto ret = cli_.send(req, res, error);
  8825. EXPECT_TRUE(ret);
  8826. EXPECT_EQ(StatusCode::OK_200, res.status);
  8827. EXPECT_EQ(LARGE_DATA, res.body);
  8828. }
  8829. {
  8830. // Test with Expect: 100-continue header - error case
  8831. // Client should not send the body when server returns an error
  8832. Request req;
  8833. req.method = "POST";
  8834. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8835. req.set_header("Expect", "100-continue");
  8836. req.body = LARGE_DATA;
  8837. Response res;
  8838. auto error = Error::Success;
  8839. auto start = std::chrono::high_resolution_clock::now();
  8840. cli_.set_keep_alive(true);
  8841. auto ret = cli_.send(req, res, error);
  8842. auto end = std::chrono::high_resolution_clock::now();
  8843. auto elapsed =
  8844. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8845. .count();
  8846. // With Expect: 100-continue, request completes successfully but with error
  8847. EXPECT_TRUE(ret);
  8848. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8849. EXPECT_EQ("close", res.get_header_value("Connection"));
  8850. EXPECT_FALSE(cli_.is_socket_open());
  8851. EXPECT_LE(elapsed, 2000);
  8852. }
  8853. {
  8854. // Send an extra GET request to ensure error recovery without hanging
  8855. Request req;
  8856. req.method = "GET";
  8857. req.path = "/hi";
  8858. auto start = std::chrono::high_resolution_clock::now();
  8859. auto res = cli_.send(req);
  8860. auto end = std::chrono::high_resolution_clock::now();
  8861. auto elapsed =
  8862. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8863. .count();
  8864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8865. EXPECT_EQ(StatusCode::OK_200, res->status);
  8866. EXPECT_EQ("Hello World!", res->body);
  8867. EXPECT_LE(elapsed, 500);
  8868. }
  8869. }
  8870. TEST(ZstdDecompressor, ChunkedDecompression) {
  8871. std::string data;
  8872. for (size_t i = 0; i < 32 * 1024; ++i) {
  8873. data.push_back(static_cast<char>('a' + i % 26));
  8874. }
  8875. std::string compressed_data;
  8876. {
  8877. httplib::detail::zstd_compressor compressor;
  8878. bool result = compressor.compress(
  8879. data.data(), data.size(),
  8880. /*last=*/true,
  8881. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8882. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8883. compressed_data_size);
  8884. return true;
  8885. });
  8886. ASSERT_TRUE(result);
  8887. }
  8888. std::string decompressed_data;
  8889. {
  8890. httplib::detail::zstd_decompressor decompressor;
  8891. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8892. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8893. size_t chunk_size = 130;
  8894. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8895. chunk_begin += chunk_size) {
  8896. size_t current_chunk_size =
  8897. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8898. bool result = decompressor.decompress(
  8899. compressed_data.data() + chunk_begin, current_chunk_size,
  8900. [&](const char *decompressed_data_chunk,
  8901. size_t decompressed_data_chunk_size) {
  8902. decompressed_data.insert(decompressed_data.size(),
  8903. decompressed_data_chunk,
  8904. decompressed_data_chunk_size);
  8905. return true;
  8906. });
  8907. ASSERT_TRUE(result);
  8908. }
  8909. }
  8910. ASSERT_EQ(data, decompressed_data);
  8911. }
  8912. TEST(ZstdDecompressor, Decompress) {
  8913. std::string original_text = "Compressed with ZSTD";
  8914. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8915. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8916. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8917. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8918. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8919. std::string decompressed_data;
  8920. {
  8921. httplib::detail::zstd_decompressor decompressor;
  8922. bool result = decompressor.decompress(
  8923. compressed_data.data(), compressed_data.size(),
  8924. [&](const char *decompressed_data_chunk,
  8925. size_t decompressed_data_chunk_size) {
  8926. decompressed_data.insert(decompressed_data.size(),
  8927. decompressed_data_chunk,
  8928. decompressed_data_chunk_size);
  8929. return true;
  8930. });
  8931. ASSERT_TRUE(result);
  8932. }
  8933. ASSERT_EQ(original_text, decompressed_data);
  8934. }
  8935. #endif
  8936. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8937. // separate chunks so that the server sees each part in its own read(). Used to
  8938. // place a read boundary at a specific offset of a request body.
  8939. static bool send_request_in_parts(time_t read_timeout_sec,
  8940. const std::vector<std::string> &parts,
  8941. std::string *resp = nullptr,
  8942. int port = PORT) {
  8943. auto error = Error::Success;
  8944. auto client_sock = detail::create_client_socket(
  8945. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8946. /*connection_timeout_sec=*/5, 0,
  8947. /*read_timeout_sec=*/5, 0,
  8948. /*write_timeout_sec=*/5, 0, std::string(), error);
  8949. if (client_sock == INVALID_SOCKET) { return false; }
  8950. auto ret = detail::process_client_socket(
  8951. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8952. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8953. for (size_t i = 0; i < parts.size(); i++) {
  8954. const auto &part = parts[i];
  8955. if (part.size() !=
  8956. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8957. return false;
  8958. }
  8959. if (i + 1 < parts.size()) {
  8960. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8961. }
  8962. }
  8963. char buf[512];
  8964. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8965. while (line_reader.getline()) {
  8966. if (resp) { *resp += line_reader.ptr(); }
  8967. }
  8968. return true;
  8969. });
  8970. detail::close_socket(client_sock);
  8971. return ret;
  8972. }
  8973. // Sends a raw request to a server listening at HOST:PORT.
  8974. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8975. std::string *resp = nullptr, int port = PORT) {
  8976. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8977. }
  8978. #ifdef CPPHTTPLIB_SSL_ENABLED
  8979. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8980. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8981. ASSERT_TRUE(svr.is_valid());
  8982. svr.set_read_timeout(1, 0);
  8983. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8984. auto se = detail::scope_exit([&] {
  8985. svr.stop();
  8986. t.join();
  8987. ASSERT_FALSE(svr.is_running());
  8988. });
  8989. svr.wait_until_ready();
  8990. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8991. // keeps each wait well within the read timeout. The server gives up a
  8992. // second in, so the bytes sent after that fail.
  8993. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8994. parts.resize(26, std::string(1, '\0'));
  8995. EXPECT_FALSE(send_request_in_parts(5, parts));
  8996. }
  8997. #endif
  8998. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8999. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9000. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9001. const std::vector<std::string> &parts,
  9002. std::string *resp = nullptr,
  9003. int port = PORT) {
  9004. auto error = Error::Success;
  9005. auto sock = detail::create_client_socket(
  9006. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9007. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9008. /*write_timeout_sec=*/5, 0, std::string(), error);
  9009. if (sock == INVALID_SOCKET) { return false; }
  9010. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9011. auto ctx = SSL_CTX_new(TLS_client_method());
  9012. auto ssl = SSL_new(ctx);
  9013. auto ssl_se = detail::scope_exit([&] {
  9014. SSL_free(ssl);
  9015. SSL_CTX_free(ctx);
  9016. });
  9017. SSL_set_fd(ssl, static_cast<int>(sock));
  9018. if (SSL_connect(ssl) != 1) { return false; }
  9019. for (size_t i = 0; i < parts.size(); i++) {
  9020. const auto &part = parts[i];
  9021. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9022. static_cast<int>(part.size())) {
  9023. return false;
  9024. }
  9025. if (i + 1 < parts.size()) {
  9026. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9027. }
  9028. }
  9029. char buf[512];
  9030. int n;
  9031. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9032. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9033. }
  9034. return true;
  9035. }
  9036. #endif
  9037. // The request line, then a header value a byte at a time.
  9038. static std::vector<std::string> slow_request_head_parts() {
  9039. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9040. parts.resize(26, "a");
  9041. parts.emplace_back("\r\n\r\n");
  9042. return parts;
  9043. }
  9044. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9045. // within the one-second read timeout. The server gives up a second in, before
  9046. // the head is complete.
  9047. static void
  9048. expect_slow_request_head_dropped(Server &svr,
  9049. const std::function<std::string()> &send) {
  9050. std::atomic<bool> handled(false);
  9051. svr.Get("/", [&](const Request &, Response &res) {
  9052. handled = true;
  9053. res.set_content("ok", "text/plain");
  9054. });
  9055. svr.set_read_timeout(1, 0);
  9056. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9057. auto se = detail::scope_exit([&] {
  9058. svr.stop();
  9059. t.join();
  9060. ASSERT_FALSE(svr.is_running());
  9061. });
  9062. svr.wait_until_ready();
  9063. auto resp = send();
  9064. EXPECT_FALSE(handled);
  9065. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9066. }
  9067. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9068. Server svr;
  9069. expect_slow_request_head_dropped(svr, [] {
  9070. std::string resp;
  9071. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9072. return resp;
  9073. });
  9074. }
  9075. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9076. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9078. ASSERT_TRUE(svr.is_valid());
  9079. expect_slow_request_head_dropped(svr, [] {
  9080. std::string resp;
  9081. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9082. return resp;
  9083. });
  9084. }
  9085. #endif
  9086. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9087. Server svr;
  9088. std::string header_value;
  9089. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9090. header_value = req.get_header_value("foo");
  9091. res.set_content("ok", "text/plain");
  9092. });
  9093. thread t = thread([&] { svr.listen(HOST, PORT); });
  9094. auto se = detail::scope_exit([&] {
  9095. svr.stop();
  9096. t.join();
  9097. ASSERT_FALSE(svr.is_running());
  9098. });
  9099. svr.wait_until_ready();
  9100. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9101. // like characters are not treated the same - use vertical tab and escape.
  9102. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9103. "foo: \t \v bar \x1B\t \r\n"
  9104. "Connection: close\r\n"
  9105. "\r\n";
  9106. std::string res;
  9107. ASSERT_TRUE(send_request(5, req, &res));
  9108. EXPECT_EQ(header_value, "");
  9109. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9110. }
  9111. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9112. Server svr;
  9113. std::string received;
  9114. svr.Get("/order", [&](const Request &req, Response &res) {
  9115. received = entries_to_string(req.headers);
  9116. res.set_content("ok", "text/plain");
  9117. });
  9118. auto port = svr.bind_to_any_port(HOST);
  9119. thread t = thread([&] { svr.listen_after_bind(); });
  9120. auto se = detail::scope_exit([&] {
  9121. svr.stop();
  9122. t.join();
  9123. ASSERT_FALSE(svr.is_running());
  9124. });
  9125. svr.wait_until_ready();
  9126. const std::string req = "GET /order HTTP/1.1\r\n"
  9127. "Host: localhost\r\n"
  9128. "X-First: 1\r\n"
  9129. "X-Dup: a\r\n"
  9130. "X-Second: 2\r\n"
  9131. "X-Dup: b\r\n"
  9132. "Connection: close\r\n"
  9133. "\r\n";
  9134. std::string res;
  9135. ASSERT_TRUE(send_request(5, req, &res, port));
  9136. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9137. EXPECT_EQ(
  9138. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9139. received);
  9140. }
  9141. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9142. Server svr;
  9143. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9144. res.set_header("Set-Cookie", "first=1");
  9145. res.set_header("X-Between", "y");
  9146. res.set_header("Set-Cookie", "second=2");
  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. Client cli(HOST, port);
  9158. auto res = cli.Get("/cookies");
  9159. ASSERT_TRUE(res);
  9160. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9161. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9162. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9163. }
  9164. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9165. Server svr;
  9166. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9167. auto i = new int(0);
  9168. res.set_header("Trailer", "X-Safe, X-Reflected");
  9169. res.set_chunked_content_provider(
  9170. "text/plain",
  9171. [i](size_t /*offset*/, DataSink &sink) {
  9172. if (*i == 0) {
  9173. sink.os << "body";
  9174. } else {
  9175. Headers trailer;
  9176. // A valid trailer that must survive.
  9177. trailer.emplace("X-Safe", "safe");
  9178. // Attacker-controlled value carrying CR/LF (response splitting).
  9179. trailer.emplace("X-Reflected",
  9180. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9181. // Attacker-controlled name carrying CR/LF.
  9182. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9183. sink.done_with_trailer(trailer);
  9184. }
  9185. (*i)++;
  9186. return true;
  9187. },
  9188. [i](bool /*success*/) { delete i; });
  9189. });
  9190. thread t = thread([&] { svr.listen(HOST, PORT); });
  9191. auto se = detail::scope_exit([&] {
  9192. svr.stop();
  9193. t.join();
  9194. ASSERT_FALSE(svr.is_running());
  9195. });
  9196. svr.wait_until_ready();
  9197. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9198. "Host: " + HOST +
  9199. "\r\n"
  9200. "Connection: close\r\n"
  9201. "\r\n";
  9202. std::string res;
  9203. ASSERT_TRUE(send_request(5, req, &res));
  9204. // The injected fields must not appear anywhere in the raw response.
  9205. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9206. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9207. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9208. // Invalid trailers are dropped entirely, matching set_header().
  9209. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9210. // The valid trailer still passes through.
  9211. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9212. }
  9213. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9214. Server svr;
  9215. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9216. // res.headers is a public field an application can populate directly,
  9217. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9218. // A valid header that must survive.
  9219. res.headers.emplace("X-Safe", "safe");
  9220. // Attacker-controlled value carrying CR/LF (response splitting).
  9221. res.headers.emplace("X-Reflected",
  9222. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9223. // Attacker-controlled name carrying CR/LF.
  9224. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9225. res.set_content("body", "text/plain");
  9226. });
  9227. thread t = thread([&] { svr.listen(HOST, PORT); });
  9228. auto se = detail::scope_exit([&] {
  9229. svr.stop();
  9230. t.join();
  9231. ASSERT_FALSE(svr.is_running());
  9232. });
  9233. svr.wait_until_ready();
  9234. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9235. "Host: " + HOST +
  9236. "\r\n"
  9237. "Connection: close\r\n"
  9238. "\r\n";
  9239. std::string res;
  9240. ASSERT_TRUE(send_request(5, req, &res));
  9241. // The injected fields must not appear anywhere in the raw response.
  9242. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9243. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9244. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9245. // Invalid headers are dropped entirely, matching set_header().
  9246. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9247. // The valid header still passes through.
  9248. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9249. }
  9250. // Forward declaration: in split builds split.py strips `inline` and moves the
  9251. // definition into httplib.cc, so detail::write_request_line is not visible from
  9252. // the public httplib.h. Re-declaring it here lets the tests link against the
  9253. // symbol in both header-only and split builds.
  9254. namespace httplib {
  9255. namespace detail {
  9256. ssize_t write_request_line(Stream &strm, const std::string &method,
  9257. const std::string &path);
  9258. } // namespace detail
  9259. } // namespace httplib
  9260. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9261. // A well-formed target is written verbatim.
  9262. {
  9263. detail::BufferStream strm;
  9264. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9265. EXPECT_GT(n, 0);
  9266. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9267. }
  9268. // A target carrying CR/LF, SP or other control octets must be rejected
  9269. // before anything reaches the wire, otherwise it splits the request line and
  9270. // injects a header or a whole request.
  9271. const std::string evil_targets[] = {
  9272. "/a\r\nInjected: pwned",
  9273. "/a\rInjected",
  9274. "/a\nInjected",
  9275. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9276. "/a b",
  9277. "/a\tb",
  9278. "/a\x7f",
  9279. };
  9280. for (const auto &evil : evil_targets) {
  9281. detail::BufferStream strm;
  9282. auto n = detail::write_request_line(strm, "GET", evil);
  9283. EXPECT_LT(n, 0);
  9284. EXPECT_TRUE(strm.get_buffer().empty());
  9285. }
  9286. }
  9287. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9288. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9289. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9290. // target reaches write_request. The client must fail cleanly with
  9291. // Error::Write instead of putting a request-line-less, header-injecting
  9292. // request on the wire.
  9293. Server svr;
  9294. svr.Get("/a", [](const Request &, Response &res) {
  9295. res.set_content("ok", "text/plain");
  9296. });
  9297. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9298. auto se = detail::scope_exit([&] {
  9299. svr.stop();
  9300. thread.join();
  9301. ASSERT_FALSE(svr.is_running());
  9302. });
  9303. svr.wait_until_ready();
  9304. {
  9305. Client cli(HOST, PORT);
  9306. cli.set_path_encode(false);
  9307. // The request is rejected before anything is written, so the connection
  9308. // stays silent and the subsequent response read would otherwise block for
  9309. // the full default read timeout. Shorten it -- the assertion is on the
  9310. // error, not the timeout.
  9311. cli.set_read_timeout(1, 0);
  9312. auto res = cli.Get("/a\r\nInjected: pwned");
  9313. EXPECT_FALSE(res);
  9314. EXPECT_EQ(Error::Write, res.error());
  9315. }
  9316. }
  9317. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9318. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9319. // including extension methods.
  9320. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9321. for (const auto &method : good_methods) {
  9322. detail::BufferStream strm;
  9323. auto n = detail::write_request_line(strm, method, "/");
  9324. EXPECT_GT(n, 0);
  9325. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9326. }
  9327. // A method carrying CR/LF would split the request line and smuggle a whole
  9328. // request ahead of the real one. A space or an empty method corrupts the
  9329. // request line. All must be rejected before anything reaches the wire.
  9330. const std::string evil_methods[] = {
  9331. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9332. "GET\r\nInjected: pwned",
  9333. "GET\r",
  9334. "GET\n",
  9335. "GE T",
  9336. "",
  9337. };
  9338. for (const auto &evil : evil_methods) {
  9339. detail::BufferStream strm;
  9340. auto n = detail::write_request_line(strm, evil, "/");
  9341. EXPECT_LT(n, 0);
  9342. EXPECT_TRUE(strm.get_buffer().empty());
  9343. }
  9344. }
  9345. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9346. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9347. // through Client::send must fail with Error::Write and no request, neither
  9348. // the smuggled one nor the real one, may reach the server.
  9349. Server svr;
  9350. std::atomic<int> request_count(0);
  9351. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9352. request_count++;
  9353. res.status = StatusCode::OK_200;
  9354. return Server::HandlerResponse::Handled;
  9355. });
  9356. auto port = svr.bind_to_any_port(HOST);
  9357. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9358. auto se = detail::scope_exit([&] {
  9359. svr.stop();
  9360. thread.join();
  9361. ASSERT_FALSE(svr.is_running());
  9362. });
  9363. svr.wait_until_ready();
  9364. {
  9365. Client cli(HOST, port);
  9366. const std::string evil_methods[] = {
  9367. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9368. "GE T",
  9369. "",
  9370. };
  9371. for (const auto &evil : evil_methods) {
  9372. Request req;
  9373. req.method = evil;
  9374. req.path = "/";
  9375. auto res = cli.send(req);
  9376. EXPECT_FALSE(res);
  9377. EXPECT_EQ(Error::Write, res.error());
  9378. }
  9379. auto handle =
  9380. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9381. EXPECT_FALSE(handle.is_valid());
  9382. EXPECT_EQ(Error::Write, handle.error);
  9383. // A valid request on the same client still goes through.
  9384. auto res = cli.Get("/");
  9385. ASSERT_TRUE(res);
  9386. EXPECT_EQ(StatusCode::OK_200, res->status);
  9387. }
  9388. EXPECT_EQ(1, request_count.load());
  9389. }
  9390. // Sends a raw request and verifies that there isn't a crash or exception.
  9391. static void test_raw_request(const std::string &req,
  9392. std::string *out = nullptr) {
  9393. Server svr;
  9394. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9395. res.set_content("ok", "text/plain");
  9396. });
  9397. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9398. res.set_content("ok", "text/plain");
  9399. });
  9400. svr.Get("/header_field_value_check",
  9401. [&](const Request & /*req*/, Response &res) {
  9402. res.set_content("ok", "text/plain");
  9403. });
  9404. svr.CustomRoute("PROPFIND", "/dav",
  9405. [&](const Request & /*req*/, Response &res) {
  9406. res.status = StatusCode::MultiStatus_207;
  9407. });
  9408. // Server read timeout must be longer than the client read timeout for the
  9409. // bug to reproduce, probably to force the server to process a request
  9410. // without a trailing blank line.
  9411. const time_t client_read_timeout_sec = 1;
  9412. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9413. bool listen_thread_ok = false;
  9414. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9415. auto se = detail::scope_exit([&] {
  9416. svr.stop();
  9417. t.join();
  9418. ASSERT_FALSE(svr.is_running());
  9419. EXPECT_TRUE(listen_thread_ok);
  9420. });
  9421. svr.wait_until_ready();
  9422. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9423. }
  9424. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9425. // A certain header line causes an exception if the header property is parsed
  9426. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9427. test_raw_request(
  9428. "GET /hi HTTP/1.1\r\n"
  9429. " : "
  9430. " "
  9431. " ");
  9432. }
  9433. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9434. // A certain header line causes an exception if the header property *name* is
  9435. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9436. // greedy matcher and requires backtracking when there are a lot of ":"
  9437. // characters.
  9438. // This occurs with libc++ but not libstdc++.
  9439. test_raw_request(
  9440. "GET /hi HTTP/1.1\r\n"
  9441. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9442. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9443. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9444. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9445. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9446. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9447. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9448. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9449. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9450. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9451. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9452. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9453. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9454. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9455. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9456. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9457. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9458. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9459. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9460. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9461. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9462. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9463. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9464. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9465. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9466. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9467. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9468. "&&&%%%");
  9469. }
  9470. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9471. // Make sure this doesn't crash the server.
  9472. // In a previous version of the header line regex, the "\r" rendered the line
  9473. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9474. // a new position where the leading white space ended and the field value
  9475. // began.
  9476. // The crash occurs with libc++ but not libstdc++.
  9477. test_raw_request("GET /hi HTTP/1.1\r\n"
  9478. "a:" +
  9479. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9480. "\r\n"
  9481. "\r\n");
  9482. }
  9483. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9484. const char *rejected[] = {
  9485. // RFC 9112 §3: one SP between the parts, and nothing else
  9486. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9487. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9488. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9489. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9490. // A request-target has no fragment
  9491. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9492. // An HTTP/1.1 request needs a Host
  9493. "GET /hi HTTP/1.1\r\n\r\n",
  9494. };
  9495. for (auto request : rejected) {
  9496. std::string out;
  9497. test_raw_request(request, &out);
  9498. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9499. }
  9500. std::string out;
  9501. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9502. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9503. }
  9504. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9505. // RFC 9112 §6.1
  9506. const char *requests[] = {
  9507. "PUT /put_hi HTTP/1.1\r\n"
  9508. "Host: localhost\r\n"
  9509. "Content-Length: 0\r\n"
  9510. "Transfer-Encoding: chunked\r\n"
  9511. "\r\n"
  9512. "0\r\n\r\n",
  9513. "PUT /put_hi HTTP/1.0\r\n"
  9514. "Connection: keep-alive\r\n"
  9515. "Transfer-Encoding: chunked\r\n"
  9516. "\r\n"
  9517. "0\r\n\r\n",
  9518. };
  9519. for (auto request : requests) {
  9520. std::string out;
  9521. test_raw_request(request, &out);
  9522. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9523. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9524. }
  9525. }
  9526. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9527. std::string out;
  9528. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9529. "Content-Type: text/plain\r\n"
  9530. "Transfer-Encoding: chunked\r\n"
  9531. "\r\n"
  9532. "nothex\r\n",
  9533. &out);
  9534. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9535. }
  9536. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9537. std::string out;
  9538. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9539. "Content-Type: text/plain\r\n"
  9540. "Transfer-Encoding: chunked\r\n"
  9541. "\r\n"
  9542. "3\r\n"
  9543. "xyz\r\n"
  9544. "NaN\r\n",
  9545. &out);
  9546. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9547. }
  9548. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9549. std::string out;
  9550. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9551. "Content-Type: text/plain\r\n"
  9552. "Transfer-Encoding: chunked\r\n"
  9553. "\r\n"
  9554. // Length is too large for 64 bits.
  9555. "1ffffffffffffffff\r\n"
  9556. "xyz\r\n",
  9557. &out);
  9558. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9559. }
  9560. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9561. test_raw_request("GET /hi HTTP/1.1\r\n"
  9562. "Content-Type: text/plain\r\n\r");
  9563. }
  9564. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9565. std::string out;
  9566. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9567. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9568. }
  9569. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9570. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9571. std::string out;
  9572. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9573. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9574. }
  9575. }
  9576. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9577. std::string out;
  9578. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9579. "Host: localhost\r\n"
  9580. "Connection: close\r\n\r\n",
  9581. &out);
  9582. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9583. }
  9584. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9585. Server svr;
  9586. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9587. EXPECT_TRUE(!req.remote_addr.empty());
  9588. });
  9589. thread t = thread([&] { svr.listen(HOST, PORT); });
  9590. auto se = detail::scope_exit([&] {
  9591. svr.stop();
  9592. t.join();
  9593. ASSERT_FALSE(svr.is_running());
  9594. });
  9595. svr.wait_until_ready();
  9596. // Send an invalid request line to trigger Bad Request
  9597. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9598. std::string out;
  9599. ASSERT_TRUE(send_request(5, bad_req, &out));
  9600. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9601. }
  9602. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9603. // answered right away rather than blocking on a read that waits for EOF.
  9604. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9605. std::string out;
  9606. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9607. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9608. }
  9609. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9610. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9611. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9612. for (const auto *method : methods) {
  9613. Server svr;
  9614. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9615. EXPECT_FALSE(svr.is_valid()) << method;
  9616. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9617. }
  9618. }
  9619. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9620. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9621. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9622. for (const auto *method : methods) {
  9623. Server svr;
  9624. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9625. EXPECT_FALSE(svr.is_valid()) << method;
  9626. }
  9627. }
  9628. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9629. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9630. "COPY", "MOVE", "LOCK",
  9631. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9632. Server svr;
  9633. for (const auto *method : methods) {
  9634. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9635. }
  9636. EXPECT_TRUE(svr.is_valid());
  9637. }
  9638. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9639. Server svr;
  9640. svr.CustomRoute("POST", "/x",
  9641. [](const Request &, Response &, const ContentReader &) {});
  9642. EXPECT_FALSE(svr.is_valid());
  9643. }
  9644. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9645. Server svr;
  9646. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9647. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9648. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9649. EXPECT_FALSE(svr.is_valid());
  9650. }
  9651. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9652. Server svr;
  9653. auto captured = Error::Success;
  9654. svr.set_error_logger(
  9655. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9656. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9657. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9658. }
  9659. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9660. std::string out;
  9661. std::string request(
  9662. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9663. test_raw_request(request, &out);
  9664. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9665. }
  9666. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9667. std::string out;
  9668. std::string request(
  9669. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9670. test_raw_request(request, &out);
  9671. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9672. }
  9673. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9674. std::string out;
  9675. std::string request(
  9676. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9677. test_raw_request(request, &out);
  9678. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9679. }
  9680. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9681. std::string out;
  9682. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9683. "Host: localhost\r\n"
  9684. "Test: \r\n\r\n",
  9685. &out);
  9686. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9687. }
  9688. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9689. Server svr;
  9690. std::string x_custom;
  9691. std::string cookie;
  9692. std::string xff;
  9693. std::string x_unicode;
  9694. std::string x_iis;
  9695. svr.Get("/check", [&](const Request &req, Response &res) {
  9696. x_custom = req.get_header_value("X-Custom");
  9697. cookie = req.get_header_value("Cookie");
  9698. xff = req.get_header_value("X-Forwarded-For");
  9699. x_unicode = req.get_header_value("X-Unicode");
  9700. x_iis = req.get_header_value("X-IIS");
  9701. res.set_content("ok", "text/plain");
  9702. });
  9703. thread t = thread([&] { svr.listen(HOST, PORT); });
  9704. auto se = detail::scope_exit([&] {
  9705. svr.stop();
  9706. t.join();
  9707. ASSERT_FALSE(svr.is_running());
  9708. });
  9709. svr.wait_until_ready();
  9710. const std::string req = "GET /check HTTP/1.1\r\n"
  9711. "Host: localhost\r\n"
  9712. "X-Custom: a%0D%0AInjected: b\r\n"
  9713. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9714. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9715. "X-Unicode: %E3%81%82\r\n"
  9716. "X-IIS: %u00E9\r\n"
  9717. "Connection: close\r\n"
  9718. "\r\n";
  9719. std::string res;
  9720. ASSERT_TRUE(send_request(5, req, &res));
  9721. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9722. // Every value must be returned verbatim (wire form), with no decoding.
  9723. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9724. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9725. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9726. EXPECT_EQ("%E3%81%82", x_unicode);
  9727. EXPECT_EQ("%u00E9", x_iis);
  9728. }
  9729. // Applications that previously relied on automatic percent-decoding can
  9730. // reproduce the old behavior by explicitly calling decode_path_component()
  9731. // or, for RFC 3986 conformance, decode_uri_component().
  9732. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9733. Server svr;
  9734. std::string decoded;
  9735. svr.Get("/check", [&](const Request &req, Response &res) {
  9736. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9737. res.set_content("ok", "text/plain");
  9738. });
  9739. thread t = thread([&] { svr.listen(HOST, PORT); });
  9740. auto se = detail::scope_exit([&] {
  9741. svr.stop();
  9742. t.join();
  9743. ASSERT_FALSE(svr.is_running());
  9744. });
  9745. svr.wait_until_ready();
  9746. const std::string req = "GET /check HTTP/1.1\r\n"
  9747. "Host: localhost\r\n"
  9748. "X-Custom: hello%20world\r\n"
  9749. "Connection: close\r\n"
  9750. "\r\n";
  9751. std::string res;
  9752. ASSERT_TRUE(send_request(5, req, &res));
  9753. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9754. EXPECT_EQ("hello world", decoded);
  9755. }
  9756. // Regression test for #2033. Browsers send Referer values that include
  9757. // percent-encoded characters such as %0A inside the URL. Decoding the
  9758. // header value would either trip the post-decode CR/LF/NUL guard (the
  9759. // original bug, returning 400) or, after that guard was relaxed, silently
  9760. // store a literal LF — both unacceptable. The wire form must round-trip.
  9761. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9762. Server svr;
  9763. std::string referer;
  9764. svr.Get("/check", [&](const Request &req, Response &res) {
  9765. referer = req.get_header_value("Referer");
  9766. res.set_content("ok", "text/plain");
  9767. });
  9768. thread t = thread([&] { svr.listen(HOST, PORT); });
  9769. auto se = detail::scope_exit([&] {
  9770. svr.stop();
  9771. t.join();
  9772. ASSERT_FALSE(svr.is_running());
  9773. });
  9774. svr.wait_until_ready();
  9775. const std::string req = "GET /check HTTP/1.1\r\n"
  9776. "Host: localhost\r\n"
  9777. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9778. "Connection: close\r\n"
  9779. "\r\n";
  9780. std::string res;
  9781. ASSERT_TRUE(send_request(5, req, &res));
  9782. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9783. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9784. }
  9785. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9786. Server svr;
  9787. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9788. res.set_header("Cache-Control", "no-cache");
  9789. res.set_chunked_content_provider(
  9790. "text/event-stream", [](size_t offset, DataSink &sink) {
  9791. std::string s = "data:";
  9792. s += std::to_string(offset);
  9793. s += "\n\n";
  9794. auto ret = sink.write(s.data(), s.size());
  9795. EXPECT_TRUE(ret);
  9796. std::this_thread::sleep_for(std::chrono::seconds(1));
  9797. return true;
  9798. });
  9799. });
  9800. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9801. svr.wait_until_ready();
  9802. Client client(HOST, PORT);
  9803. const Headers headers = {{"Accept", "text/event-stream"}};
  9804. auto get_thread = std::thread([&client, &headers]() {
  9805. auto res = client.Get(
  9806. "/events", headers,
  9807. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9808. });
  9809. auto se = detail::scope_exit([&] {
  9810. svr.stop();
  9811. get_thread.join();
  9812. listen_thread.join();
  9813. ASSERT_FALSE(svr.is_running());
  9814. });
  9815. // Give GET time to get a few messages.
  9816. std::this_thread::sleep_for(std::chrono::seconds(2));
  9817. }
  9818. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9819. httplib::Server svr;
  9820. svr.Post("/hi",
  9821. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9822. res.status = StatusCode::OK_200;
  9823. });
  9824. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9825. svr.wait_until_ready();
  9826. Client cli(HOST, PORT);
  9827. auto res = cli.Post("/hi", "data", "text/plain");
  9828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9829. EXPECT_EQ(StatusCode::OK_200, res->status);
  9830. svr.stop();
  9831. thread.join();
  9832. ASSERT_FALSE(svr.is_running());
  9833. res = cli.Post("/hi", "data", "text/plain");
  9834. ASSERT_FALSE(res);
  9835. }
  9836. TEST(ServerStopTest, ListenFailure) {
  9837. Server svr;
  9838. auto t = thread([&]() {
  9839. auto ret = svr.listen("????", PORT);
  9840. EXPECT_FALSE(ret);
  9841. });
  9842. svr.wait_until_ready();
  9843. svr.stop();
  9844. t.join();
  9845. }
  9846. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9847. TEST(ServerStopTest, Decommision) {
  9848. Server svr;
  9849. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9850. for (int i = 0; i < 4; i++) {
  9851. auto is_even = !(i % 2);
  9852. std::thread t{[&] {
  9853. try {
  9854. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9855. if (is_even) {
  9856. throw std::runtime_error("Some thing that happens to go wrong.");
  9857. }
  9858. svr.listen(HOST, PORT);
  9859. } catch (...) { svr.decommission(); }
  9860. }};
  9861. svr.wait_until_ready();
  9862. // Server is up
  9863. {
  9864. Client cli(HOST, PORT);
  9865. auto res = cli.Get("/hi");
  9866. if (is_even) {
  9867. EXPECT_FALSE(res);
  9868. } else {
  9869. EXPECT_TRUE(res);
  9870. EXPECT_EQ("hi...", res->body);
  9871. }
  9872. }
  9873. svr.stop();
  9874. t.join();
  9875. // Server is down...
  9876. {
  9877. Client cli(HOST, PORT);
  9878. auto res = cli.Get("/hi");
  9879. EXPECT_FALSE(res);
  9880. }
  9881. }
  9882. }
  9883. #endif
  9884. // Helper function for string body upload progress tests
  9885. template <typename SetupHandler, typename ClientCall>
  9886. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9887. ClientCall &&client_call,
  9888. const string &body) {
  9889. Server svr;
  9890. setup_handler(svr);
  9891. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9892. auto se = detail::scope_exit([&] {
  9893. svr.stop();
  9894. t.join();
  9895. });
  9896. svr.wait_until_ready();
  9897. Client cli(HOST, PORT);
  9898. vector<uint64_t> progress_values;
  9899. bool progress_called = false;
  9900. auto res =
  9901. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9902. progress_values.push_back(current);
  9903. progress_called = true;
  9904. return true;
  9905. });
  9906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9907. EXPECT_EQ(200, res->status);
  9908. EXPECT_TRUE(progress_called);
  9909. }
  9910. TEST(UploadProgressTest, PostStringBodyBasic) {
  9911. TestStringBodyUploadProgress(
  9912. [](Server &svr) {
  9913. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9914. res.set_content("received", "text/plain");
  9915. });
  9916. },
  9917. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9918. return cli.Post("/test", body, "text/plain", progress_callback);
  9919. },
  9920. "test data for upload progress");
  9921. }
  9922. TEST(UploadProgressTest, PutStringBodyBasic) {
  9923. TestStringBodyUploadProgress(
  9924. [](Server &svr) {
  9925. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9926. res.set_content("put received", "text/plain");
  9927. });
  9928. },
  9929. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9930. return cli.Put("/test", body, "text/plain", progress_callback);
  9931. },
  9932. "put test data for upload progress");
  9933. }
  9934. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9935. TestStringBodyUploadProgress(
  9936. [](Server &svr) {
  9937. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9938. res.set_content("patch received", "text/plain");
  9939. });
  9940. },
  9941. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9942. return cli.Patch("/test", body, "text/plain", progress_callback);
  9943. },
  9944. "patch test data for upload progress");
  9945. }
  9946. // Helper function for content provider upload progress tests
  9947. template <typename SetupHandler, typename ClientCall>
  9948. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9949. ClientCall &&client_call) {
  9950. Server svr;
  9951. setup_handler(svr);
  9952. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9953. auto se = detail::scope_exit([&] {
  9954. svr.stop();
  9955. t.join();
  9956. });
  9957. svr.wait_until_ready();
  9958. Client cli(HOST, PORT);
  9959. vector<uint64_t> progress_values;
  9960. auto res =
  9961. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9962. progress_values.push_back(current);
  9963. return true;
  9964. });
  9965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9966. EXPECT_EQ(200, res->status);
  9967. EXPECT_FALSE(progress_values.empty());
  9968. }
  9969. TEST(UploadProgressTest, PostContentProviderProgress) {
  9970. TestContentProviderUploadProgress(
  9971. [](Server &svr) {
  9972. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9973. res.set_content("provider received", "text/plain");
  9974. });
  9975. },
  9976. [](Client &cli, UploadProgress progress_callback) {
  9977. return cli.Post(
  9978. "/test", 9,
  9979. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9980. sink.os << "test data";
  9981. return true;
  9982. },
  9983. "text/plain", progress_callback);
  9984. });
  9985. }
  9986. // Helper function for multipart upload progress tests
  9987. template <typename SetupHandler, typename ClientCall>
  9988. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9989. ClientCall &&client_call,
  9990. const string &endpoint) {
  9991. Server svr;
  9992. setup_handler(svr);
  9993. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9994. auto se = detail::scope_exit([&] {
  9995. svr.stop();
  9996. t.join();
  9997. });
  9998. svr.wait_until_ready();
  9999. Client cli(HOST, PORT);
  10000. vector<uint64_t> progress_values;
  10001. UploadFormDataItems items = {
  10002. {"field1", "value1", "", ""},
  10003. {"field2", "longer value for progress tracking test", "", ""},
  10004. {"file1", "file content data for upload progress", "test.txt",
  10005. "text/plain"}};
  10006. auto res = client_call(cli, endpoint, items,
  10007. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10008. progress_values.push_back(current);
  10009. return true;
  10010. });
  10011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10012. EXPECT_EQ(200, res->status);
  10013. EXPECT_FALSE(progress_values.empty());
  10014. }
  10015. TEST(UploadProgressTest, PostMultipartProgress) {
  10016. TestMultipartUploadProgress(
  10017. [](Server &svr) {
  10018. svr.Post("/multipart", [](const Request &req, Response &res) {
  10019. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10020. res.set_content("multipart received", "text/plain");
  10021. });
  10022. },
  10023. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10024. UploadProgress progress_callback) {
  10025. return cli.Post(endpoint, items, progress_callback);
  10026. },
  10027. "/multipart");
  10028. }
  10029. // Helper function for basic download progress tests
  10030. template <typename SetupHandler, typename ClientCall>
  10031. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10032. ClientCall &&client_call, const string &endpoint,
  10033. size_t expected_content_size) {
  10034. Server svr;
  10035. setup_handler(svr);
  10036. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10037. auto se = detail::scope_exit([&] {
  10038. svr.stop();
  10039. t.join();
  10040. });
  10041. svr.wait_until_ready();
  10042. Client cli(HOST, PORT);
  10043. vector<uint64_t> progress_values;
  10044. auto res = client_call(cli, endpoint,
  10045. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10046. progress_values.push_back(current);
  10047. return true;
  10048. });
  10049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10050. EXPECT_EQ(200, res->status);
  10051. EXPECT_FALSE(progress_values.empty());
  10052. EXPECT_EQ(expected_content_size, res->body.size());
  10053. }
  10054. TEST(DownloadProgressTest, GetBasic) {
  10055. TestBasicDownloadProgress(
  10056. [](Server &svr) {
  10057. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10058. string content(1000, 'D');
  10059. res.set_content(content, "text/plain");
  10060. });
  10061. },
  10062. [](Client &cli, const string &endpoint,
  10063. DownloadProgress progress_callback) {
  10064. return cli.Get(endpoint, progress_callback);
  10065. },
  10066. "/download", 1000u);
  10067. }
  10068. // Helper function for content receiver download progress tests
  10069. template <typename SetupHandler, typename ClientCall>
  10070. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10071. ClientCall &&client_call,
  10072. const string &endpoint,
  10073. size_t expected_content_size) {
  10074. Server svr;
  10075. setup_handler(svr);
  10076. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10077. auto se = detail::scope_exit([&] {
  10078. svr.stop();
  10079. t.join();
  10080. });
  10081. svr.wait_until_ready();
  10082. Client cli(HOST, PORT);
  10083. vector<uint64_t> progress_values;
  10084. string received_body;
  10085. auto res = client_call(
  10086. cli, endpoint,
  10087. [&](const char *data, size_t data_length) -> bool {
  10088. received_body.append(data, data_length);
  10089. return true;
  10090. },
  10091. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10092. progress_values.push_back(current);
  10093. return true;
  10094. });
  10095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10096. EXPECT_EQ(200, res->status);
  10097. EXPECT_FALSE(progress_values.empty());
  10098. EXPECT_EQ(expected_content_size, received_body.size());
  10099. EXPECT_TRUE(res->body.empty());
  10100. }
  10101. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10102. TestContentReceiverDownloadProgress(
  10103. [](Server &svr) {
  10104. svr.Get("/download-receiver",
  10105. [](const Request & /*req*/, Response &res) {
  10106. string content(2000, 'R');
  10107. res.set_content(content, "text/plain");
  10108. });
  10109. },
  10110. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10111. DownloadProgress progress_callback) {
  10112. return cli.Get(endpoint, content_receiver, progress_callback);
  10113. },
  10114. "/download-receiver", 2000u);
  10115. }
  10116. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10117. // A provider reaching a pass with nothing to hand over - an empty buffer
  10118. // popped off a queue, say - must not be taken to mean the body is finished.
  10119. // It used to end the loop with the terminating chunk unwritten while the
  10120. // server still considered the response complete, so the peer waited for an
  10121. // end that never arrived.
  10122. Server svr;
  10123. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10124. auto step = std::make_shared<int>(0);
  10125. res.set_chunked_content_provider("text/plain",
  10126. [step](size_t /*offset*/, DataSink &sink) {
  10127. switch ((*step)++) {
  10128. case 0: sink.write("", 0); break;
  10129. case 1: sink.write("hello", 5); break;
  10130. default: sink.done(); break;
  10131. }
  10132. return true;
  10133. });
  10134. });
  10135. auto port = svr.bind_to_any_port(HOST);
  10136. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10137. auto listen_se = detail::scope_exit([&] {
  10138. svr.stop();
  10139. listen_thread.join();
  10140. ASSERT_FALSE(svr.is_running());
  10141. });
  10142. svr.wait_until_ready();
  10143. Client cli(HOST, port);
  10144. // Without the fix the body is never terminated, so bound the wait rather
  10145. // than letting the test hang on the default read timeout.
  10146. cli.set_read_timeout(5, 0);
  10147. auto res = cli.Get("/stream");
  10148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10149. EXPECT_EQ(StatusCode::OK_200, res->status);
  10150. EXPECT_EQ("hello", res->body);
  10151. }
  10152. TEST(StreamingTest, NoContentLengthStreaming) {
  10153. Server svr;
  10154. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10155. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10156. if (offset < 6) {
  10157. sink.os << (offset < 3 ? "a" : "b");
  10158. } else {
  10159. sink.done();
  10160. }
  10161. return true;
  10162. });
  10163. });
  10164. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10165. auto listen_se = detail::scope_exit([&] {
  10166. svr.stop();
  10167. listen_thread.join();
  10168. ASSERT_FALSE(svr.is_running());
  10169. });
  10170. svr.wait_until_ready();
  10171. Client client(HOST, PORT);
  10172. auto get_thread = std::thread([&client]() {
  10173. std::string s;
  10174. auto res =
  10175. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10176. s += std::string(data, len);
  10177. return true;
  10178. });
  10179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10180. EXPECT_EQ(StatusCode::OK_200, res->status);
  10181. EXPECT_EQ("aaabbb", s);
  10182. });
  10183. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10184. // Give GET time to get a few messages.
  10185. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10186. }
  10187. TEST(MountTest, Unmount) {
  10188. Server svr;
  10189. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10190. auto se = detail::scope_exit([&] {
  10191. svr.stop();
  10192. listen_thread.join();
  10193. ASSERT_FALSE(svr.is_running());
  10194. });
  10195. svr.wait_until_ready();
  10196. Client cli("localhost", PORT);
  10197. svr.set_mount_point("/mount2", "./www2");
  10198. auto res = cli.Get("/");
  10199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10200. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10201. res = cli.Get("/mount2/dir/test.html");
  10202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10203. EXPECT_EQ(StatusCode::OK_200, res->status);
  10204. svr.set_mount_point("/", "./www");
  10205. res = cli.Get("/dir/");
  10206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10207. EXPECT_EQ(StatusCode::OK_200, res->status);
  10208. svr.remove_mount_point("/");
  10209. res = cli.Get("/dir/");
  10210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10211. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10212. svr.remove_mount_point("/mount2");
  10213. res = cli.Get("/mount2/dir/test.html");
  10214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10215. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10216. }
  10217. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10218. Server svr;
  10219. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10220. svr.Get("/api/hello", [](const Request &, Response &res) {
  10221. res.set_content("api", "text/plain");
  10222. });
  10223. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10224. auto se = detail::scope_exit([&] {
  10225. svr.stop();
  10226. listen_thread.join();
  10227. ASSERT_FALSE(svr.is_running());
  10228. });
  10229. svr.wait_until_ready();
  10230. Client cli(HOST, PORT);
  10231. auto res = cli.Get("/dir/test.html");
  10232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10233. EXPECT_EQ(StatusCode::OK_200, res->status);
  10234. res = cli.Get("/api/hello");
  10235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10236. EXPECT_EQ(StatusCode::OK_200, res->status);
  10237. EXPECT_EQ("api", res->body);
  10238. }
  10239. TEST(MountTest, PathSegmentBoundary) {
  10240. Server svr;
  10241. svr.set_mount_point("/mount2", "./www2");
  10242. svr.set_mount_point("/", "./www");
  10243. auto port = svr.bind_to_any_port(HOST);
  10244. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10245. auto se = detail::scope_exit([&] {
  10246. svr.stop();
  10247. listen_thread.join();
  10248. ASSERT_FALSE(svr.is_running());
  10249. });
  10250. svr.wait_until_ready();
  10251. Client cli(HOST, port);
  10252. auto res = cli.Get("/mount2/dir/test.html");
  10253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10254. EXPECT_EQ(StatusCode::OK_200, res->status);
  10255. // "/mount2" must not match part-way through a path segment.
  10256. res = cli.Get("/mount2dir/test.html");
  10257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10258. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10259. // A mount point ending in '/' keeps matching every path below it.
  10260. res = cli.Get("/dir/test.html");
  10261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10262. EXPECT_EQ(StatusCode::OK_200, res->status);
  10263. }
  10264. TEST(MountTest, Redicect) {
  10265. Server svr;
  10266. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10267. auto se = detail::scope_exit([&] {
  10268. svr.stop();
  10269. listen_thread.join();
  10270. ASSERT_FALSE(svr.is_running());
  10271. });
  10272. svr.set_mount_point("/", "./www");
  10273. svr.wait_until_ready();
  10274. Client cli("localhost", PORT);
  10275. auto res = cli.Get("/dir/");
  10276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10277. EXPECT_EQ(StatusCode::OK_200, res->status);
  10278. res = cli.Get("/dir");
  10279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10280. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10281. res = cli.Get("/file");
  10282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10283. EXPECT_EQ(StatusCode::OK_200, res->status);
  10284. res = cli.Get("/file/");
  10285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10286. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10287. cli.set_follow_location(true);
  10288. res = cli.Get("/dir");
  10289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10290. EXPECT_EQ(StatusCode::OK_200, res->status);
  10291. }
  10292. TEST(MountTest, MultibytesPathName) {
  10293. Server svr;
  10294. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10295. auto se = detail::scope_exit([&] {
  10296. svr.stop();
  10297. listen_thread.join();
  10298. ASSERT_FALSE(svr.is_running());
  10299. });
  10300. svr.set_mount_point("/", "./www");
  10301. svr.wait_until_ready();
  10302. Client cli("localhost", PORT);
  10303. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10305. EXPECT_EQ(StatusCode::OK_200, res->status);
  10306. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10307. }
  10308. #ifdef _WIN32
  10309. // Issue #2435: mmap::open() must succeed even when another handle holds
  10310. // the file open for writing (e.g. an active log file).
  10311. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10312. const char *path = "mmap_concurrent_writer_test.txt";
  10313. const char *content = "hello";
  10314. {
  10315. std::ofstream f(path, std::ios::binary);
  10316. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10317. }
  10318. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10319. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10320. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10321. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10322. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10323. detail::mmap m(path);
  10324. ASSERT_TRUE(m.is_open());
  10325. EXPECT_EQ(strlen(content), m.size());
  10326. char buf[8];
  10327. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10328. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10329. }
  10330. #endif
  10331. #ifndef _WIN32
  10332. // A directory or a device has no size to serve.
  10333. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10334. const char *path = "./mmap_not_regular_test_dir";
  10335. ASSERT_EQ(0, ::mkdir(path, 0755));
  10336. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10337. for (auto p : {path, "/dev/null"}) {
  10338. detail::mmap m(p);
  10339. EXPECT_FALSE(m.is_open()) << p;
  10340. EXPECT_EQ(0U, m.size()) << p;
  10341. }
  10342. Server svr;
  10343. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10344. res.set_file_content("/dev/null");
  10345. });
  10346. auto port = svr.bind_to_any_port(HOST);
  10347. thread t = thread([&] { svr.listen_after_bind(); });
  10348. auto se = detail::scope_exit([&] {
  10349. svr.stop();
  10350. t.join();
  10351. });
  10352. svr.wait_until_ready();
  10353. auto res = Client(HOST, port).Get("/null");
  10354. ASSERT_TRUE(res);
  10355. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10356. }
  10357. #endif
  10358. #ifdef __linux__
  10359. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10360. TEST(MmapTest, FileIsNotMapped) {
  10361. const char *path = "mmap_not_mapped_test.txt";
  10362. {
  10363. std::ofstream f(path, std::ios::binary);
  10364. f << "hello";
  10365. }
  10366. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10367. detail::mmap m(path);
  10368. ASSERT_TRUE(m.is_open());
  10369. std::ifstream maps("/proc/self/maps");
  10370. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10371. std::istreambuf_iterator<char>());
  10372. EXPECT_EQ(std::string::npos, mappings.find(path));
  10373. }
  10374. #endif
  10375. TEST(KeepAliveTest, ReadTimeout) {
  10376. Server svr;
  10377. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10378. std::this_thread::sleep_for(std::chrono::seconds(2));
  10379. res.set_content("a", "text/plain");
  10380. });
  10381. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10382. res.set_content("b", "text/plain");
  10383. });
  10384. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10385. auto se = detail::scope_exit([&] {
  10386. svr.stop();
  10387. listen_thread.join();
  10388. ASSERT_FALSE(svr.is_running());
  10389. });
  10390. svr.wait_until_ready();
  10391. Client cli("localhost", PORT);
  10392. cli.set_keep_alive(true);
  10393. cli.set_read_timeout(std::chrono::seconds(1));
  10394. auto resa = cli.Get("/a");
  10395. ASSERT_FALSE(resa);
  10396. EXPECT_EQ(Error::Read, resa.error());
  10397. auto resb = cli.Get("/b");
  10398. ASSERT_TRUE(resb);
  10399. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10400. EXPECT_EQ("b", resb->body);
  10401. }
  10402. TEST(KeepAliveTest, MaxCount) {
  10403. size_t keep_alive_max_count = 3;
  10404. Server svr;
  10405. svr.set_keep_alive_max_count(keep_alive_max_count);
  10406. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10407. res.set_content("Hello World!", "text/plain");
  10408. });
  10409. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10410. auto se = detail::scope_exit([&] {
  10411. svr.stop();
  10412. listen_thread.join();
  10413. ASSERT_FALSE(svr.is_running());
  10414. });
  10415. svr.wait_until_ready();
  10416. Client cli(HOST, PORT);
  10417. cli.set_keep_alive(true);
  10418. for (size_t i = 0; i < 5; i++) {
  10419. auto result = cli.Get("/hi");
  10420. ASSERT_TRUE(result);
  10421. EXPECT_EQ(StatusCode::OK_200, result->status);
  10422. if (i == keep_alive_max_count - 1) {
  10423. EXPECT_EQ("close", result->get_header_value("Connection"));
  10424. } else {
  10425. EXPECT_FALSE(result->has_header("Connection"));
  10426. }
  10427. }
  10428. }
  10429. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10430. // can pull the next one into the server's buffer. The server must serve it
  10431. // without waiting for the socket to become readable again. The keep-alive
  10432. // timeout outlasts the client's read timeout, so a request left waiting for it
  10433. // shows up as a missing response.
  10434. static void serve_pipelining_routes(Server &svr,
  10435. const std::function<void(int)> &client) {
  10436. svr.set_keep_alive_timeout(5);
  10437. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10438. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10439. });
  10440. svr.Post("/echo", [](const Request &req, Response &res) {
  10441. res.set_content("echo " + req.body, "text/plain");
  10442. });
  10443. auto port = svr.bind_to_any_port(HOST);
  10444. thread t = thread([&] { svr.listen_after_bind(); });
  10445. auto se = detail::scope_exit([&] {
  10446. svr.stop();
  10447. t.join();
  10448. });
  10449. svr.wait_until_ready();
  10450. client(port);
  10451. }
  10452. static std::string
  10453. send_pipelined_requests(const std::vector<std::string> &parts) {
  10454. Server svr;
  10455. std::string res;
  10456. serve_pipelining_routes(svr, [&](int port) {
  10457. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10458. });
  10459. return res;
  10460. }
  10461. static void expect_in_order(const std::string &res,
  10462. const std::vector<std::string> &bodies) {
  10463. size_t pos = 0;
  10464. for (const auto &body : bodies) {
  10465. pos = res.find(body, pos);
  10466. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10467. pos += body.size();
  10468. }
  10469. }
  10470. TEST(KeepAliveTest, PipelinedRequests) {
  10471. auto res = send_pipelined_requests(
  10472. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10473. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10474. "Content-Length: 4\r\n\r\nbody"
  10475. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10476. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10477. }
  10478. // The second request starts in the server's buffer and ends on the socket.
  10479. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10480. auto res =
  10481. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10482. "GET /hi/2 HTTP/1.1\r\nHo",
  10483. "st: localhost\r\nConnection: close\r\n\r\n"});
  10484. expect_in_order(res, {"hi 1", "hi 2"});
  10485. }
  10486. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10487. // CRLF after a body does not turn into a 400 for the next request.
  10488. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10489. auto res = send_pipelined_requests(
  10490. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10491. "Content-Length: 4\r\n\r\nbody\r\n"
  10492. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10493. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10494. expect_in_order(res, {"echo body", "hi 2"});
  10495. }
  10496. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10497. // must not be served as the next request.
  10498. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10499. auto res = send_pipelined_requests(
  10500. {"INVALID REQUEST LINE\r\n\r\n"
  10501. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10502. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10503. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10504. }
  10505. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10506. // Over TLS, the next request is held by the TLS library as already decrypted
  10507. // data rather than on the socket.
  10508. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10509. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10510. std::string res;
  10511. serve_pipelining_routes(svr, [&](int port) {
  10512. // One part, so all three requests arrive in one TLS record
  10513. EXPECT_TRUE(send_ssl_request_in_parts(
  10514. 2,
  10515. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10516. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10517. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10518. &res, port));
  10519. });
  10520. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10521. }
  10522. #endif
  10523. TEST(KeepAliveTest, Issue1041) {
  10524. Server svr;
  10525. svr.set_keep_alive_timeout(3);
  10526. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10527. res.set_content("Hello World!", "text/plain");
  10528. });
  10529. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10530. auto se = detail::scope_exit([&] {
  10531. svr.stop();
  10532. listen_thread.join();
  10533. ASSERT_FALSE(svr.is_running());
  10534. });
  10535. svr.wait_until_ready();
  10536. Client cli(HOST, PORT);
  10537. cli.set_keep_alive(true);
  10538. auto result = cli.Get("/hi");
  10539. ASSERT_TRUE(result);
  10540. EXPECT_EQ(StatusCode::OK_200, result->status);
  10541. std::this_thread::sleep_for(std::chrono::seconds(5));
  10542. result = cli.Get("/hi");
  10543. ASSERT_TRUE(result);
  10544. EXPECT_EQ(StatusCode::OK_200, result->status);
  10545. }
  10546. TEST(KeepAliveTest, Issue1959) {
  10547. Server svr;
  10548. svr.set_keep_alive_timeout(5);
  10549. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10550. res.set_content("a", "text/plain");
  10551. });
  10552. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10553. auto se = detail::scope_exit([&] {
  10554. if (!svr.is_running()) return;
  10555. svr.stop();
  10556. listen_thread.join();
  10557. ASSERT_FALSE(svr.is_running());
  10558. });
  10559. svr.wait_until_ready();
  10560. Client cli("localhost", PORT);
  10561. cli.set_keep_alive(true);
  10562. using namespace std::chrono;
  10563. auto start = steady_clock::now();
  10564. cli.Get("/a");
  10565. svr.stop();
  10566. listen_thread.join();
  10567. auto end = steady_clock::now();
  10568. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10569. EXPECT_LT(elapsed, 5000);
  10570. }
  10571. #ifdef CPPHTTPLIB_SSL_ENABLED
  10572. TEST(KeepAliveTest, SSLClientReconnection) {
  10573. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10574. ASSERT_TRUE(svr.is_valid());
  10575. svr.set_keep_alive_timeout(1);
  10576. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10577. res.set_content("Hello World!", "text/plain");
  10578. });
  10579. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10580. auto se = detail::scope_exit([&] {
  10581. svr.stop();
  10582. listen_thread.join();
  10583. ASSERT_FALSE(svr.is_running());
  10584. });
  10585. svr.wait_until_ready();
  10586. SSLClient cli(HOST, PORT);
  10587. cli.enable_server_certificate_verification(false);
  10588. cli.set_keep_alive(true);
  10589. auto result = cli.Get("/hi");
  10590. ASSERT_TRUE(result);
  10591. EXPECT_EQ(StatusCode::OK_200, result->status);
  10592. result = cli.Get("/hi");
  10593. ASSERT_TRUE(result);
  10594. EXPECT_EQ(StatusCode::OK_200, result->status);
  10595. std::this_thread::sleep_for(std::chrono::seconds(2));
  10596. // Recoonect
  10597. result = cli.Get("/hi");
  10598. ASSERT_TRUE(result);
  10599. EXPECT_EQ(StatusCode::OK_200, result->status);
  10600. result = cli.Get("/hi");
  10601. ASSERT_TRUE(result);
  10602. EXPECT_EQ(StatusCode::OK_200, result->status);
  10603. }
  10604. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10605. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10606. ASSERT_TRUE(svr.is_valid());
  10607. svr.set_keep_alive_timeout(1);
  10608. std::string content = "reconnect";
  10609. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10610. res.set_content("Hello World!", "text/plain");
  10611. });
  10612. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10613. auto se = detail::scope_exit([&] {
  10614. svr.stop();
  10615. listen_thread.join();
  10616. ASSERT_FALSE(svr.is_running());
  10617. });
  10618. svr.wait_until_ready();
  10619. SSLClient cli(HOST, PORT);
  10620. cli.enable_server_certificate_verification(false);
  10621. cli.set_keep_alive(true);
  10622. auto result = cli.Post(
  10623. "/hi", content.size(),
  10624. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10625. sink.write(content.c_str(), content.size());
  10626. return true;
  10627. },
  10628. "text/plain");
  10629. ASSERT_TRUE(result);
  10630. EXPECT_EQ(200, result->status);
  10631. std::this_thread::sleep_for(std::chrono::seconds(2));
  10632. // Recoonect
  10633. result = cli.Post(
  10634. "/hi", content.size(),
  10635. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10636. sink.write(content.c_str(), content.size());
  10637. return true;
  10638. },
  10639. "text/plain");
  10640. ASSERT_TRUE(result);
  10641. EXPECT_EQ(200, result->status);
  10642. result = cli.Post(
  10643. "/hi", content.size(),
  10644. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10645. sink.write(content.c_str(), content.size());
  10646. return true;
  10647. },
  10648. "text/plain");
  10649. ASSERT_TRUE(result);
  10650. EXPECT_EQ(200, result->status);
  10651. }
  10652. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10653. using namespace httplib::tls;
  10654. {
  10655. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10656. ASSERT_TRUE(svr.is_valid());
  10657. svr.Get("/sni", [&](const Request &req, Response &res) {
  10658. std::string expected = req.sni();
  10659. EXPECT_EQ(expected, req.get_param_value("expected"));
  10660. res.set_content("ok", "text/plain");
  10661. });
  10662. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10663. auto se = detail::scope_exit([&] {
  10664. svr.stop();
  10665. listen_thread.join();
  10666. ASSERT_FALSE(svr.is_running());
  10667. });
  10668. svr.wait_until_ready();
  10669. {
  10670. SSLClient cli("localhost", PORT);
  10671. cli.enable_server_certificate_verification(false);
  10672. auto res = cli.Get("/sni?expected=localhost");
  10673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10674. }
  10675. {
  10676. SSLClient cli("::1", PORT);
  10677. cli.enable_server_certificate_verification(false);
  10678. auto res = cli.Get("/sni?expected=");
  10679. // NOTE: This may fail if the server is listening on IPv4 only
  10680. // (e.g., when localhost resolves to 127.0.0.1 only)
  10681. if (res) {
  10682. EXPECT_EQ(StatusCode::OK_200, res->status);
  10683. } else {
  10684. EXPECT_EQ(Error::Connection, res.error());
  10685. }
  10686. }
  10687. }
  10688. }
  10689. #endif
  10690. TEST(ClientProblemDetectionTest, ContentProvider) {
  10691. Server svr;
  10692. size_t content_length = 1024 * 1024;
  10693. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10694. res.set_content_provider(
  10695. content_length, "text/plain",
  10696. [&](size_t offset, size_t length, DataSink &sink) {
  10697. auto out_len = std::min(length, static_cast<size_t>(1024));
  10698. std::string out(out_len, '@');
  10699. sink.write(out.data(), out_len);
  10700. return offset < 4096;
  10701. },
  10702. [](bool success) { ASSERT_FALSE(success); });
  10703. });
  10704. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10705. res.set_content_provider(
  10706. 0, "text/plain",
  10707. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10708. EXPECT_TRUE(false);
  10709. return true;
  10710. },
  10711. [](bool success) { ASSERT_FALSE(success); });
  10712. });
  10713. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10714. auto se = detail::scope_exit([&] {
  10715. svr.stop();
  10716. listen_thread.join();
  10717. ASSERT_FALSE(svr.is_running());
  10718. });
  10719. svr.wait_until_ready();
  10720. Client cli("localhost", PORT);
  10721. {
  10722. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10723. size_t /*data_length*/) { return false; });
  10724. ASSERT_FALSE(res);
  10725. }
  10726. {
  10727. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10728. size_t /*data_length*/) { return false; });
  10729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10730. }
  10731. }
  10732. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10733. // A provider that reports success without writing anything and without
  10734. // calling done() used to be handed the same offset and length again on every
  10735. // pass, so it spun for as long as the peer stayed connected.
  10736. Server svr;
  10737. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10738. res.set_content("ok", "text/plain");
  10739. });
  10740. auto port = svr.bind_to_any_port(HOST);
  10741. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10742. auto se = detail::scope_exit([&] {
  10743. svr.stop();
  10744. listen_thread.join();
  10745. ASSERT_FALSE(svr.is_running());
  10746. });
  10747. svr.wait_until_ready();
  10748. std::atomic<int> call_count{0};
  10749. Client cli(HOST, port);
  10750. auto res = cli.Post(
  10751. "/", 1024,
  10752. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10753. // Give up after enough passes to show the spin, so that losing the
  10754. // check below fails this test instead of hanging it.
  10755. return ++call_count < 100;
  10756. },
  10757. "text/plain");
  10758. ASSERT_FALSE(res);
  10759. EXPECT_EQ(Error::Write, res.error());
  10760. EXPECT_EQ(1, call_count.load());
  10761. }
  10762. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10763. // A writer only has to assign `write`. The other three used to be left as
  10764. // empty std::functions, so a provider calling one threw
  10765. // std::bad_function_call out of the thread running it and took the whole
  10766. // process down.
  10767. DataSink sink;
  10768. std::string written;
  10769. sink.write = [&](const char *data, size_t data_len) {
  10770. written.append(data, data_len);
  10771. return true;
  10772. };
  10773. EXPECT_TRUE(sink.is_writable());
  10774. sink.done();
  10775. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10776. EXPECT_TRUE(written.empty());
  10777. }
  10778. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10779. // A sink that cannot carry trailers still has to finish.
  10780. DataSink sink;
  10781. auto done_count = 0;
  10782. sink.done = [&]() { done_count++; };
  10783. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10784. EXPECT_EQ(1, done_count);
  10785. }
  10786. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10787. Server svr;
  10788. const std::string body(4096, 'x');
  10789. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10790. res.set_content_provider(body.size(), "text/plain",
  10791. [&](size_t offset, size_t length, DataSink &sink) {
  10792. sink.write(body.data() + offset, length);
  10793. sink.done();
  10794. return true;
  10795. });
  10796. });
  10797. auto port = svr.bind_to_any_port(HOST);
  10798. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10799. auto se = detail::scope_exit([&] {
  10800. svr.stop();
  10801. listen_thread.join();
  10802. ASSERT_FALSE(svr.is_running());
  10803. });
  10804. svr.wait_until_ready();
  10805. Client cli(HOST, port);
  10806. auto res = cli.Get("/");
  10807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10808. EXPECT_EQ(StatusCode::OK_200, res->status);
  10809. EXPECT_EQ(body, res->body);
  10810. }
  10811. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10812. Server svr;
  10813. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10814. res.set_content_provider(
  10815. 1024, "text/plain",
  10816. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10817. sink.write("hello", 5);
  10818. sink.done(); // short of the 1024 bytes the response promised
  10819. return true;
  10820. });
  10821. });
  10822. auto port = svr.bind_to_any_port(HOST);
  10823. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10824. auto se = detail::scope_exit([&] {
  10825. svr.stop();
  10826. listen_thread.join();
  10827. ASSERT_FALSE(svr.is_running());
  10828. });
  10829. svr.wait_until_ready();
  10830. Client cli(HOST, port);
  10831. cli.set_read_timeout(5, 0);
  10832. // The response is short of its Content-Length, so the client cannot read a
  10833. // complete body. What matters is that this returns at all: a no-op done()
  10834. // would leave the writer looping over a provider that never makes progress.
  10835. auto res = cli.Get("/");
  10836. EXPECT_FALSE(res);
  10837. }
  10838. // Read as the next response by a peer that sees it after a framed body.
  10839. static const std::string smuggled_response =
  10840. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  10841. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  10842. Server svr;
  10843. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10844. res.set_content_provider(
  10845. 5, "text/plain",
  10846. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10847. auto data = "AAAAA" + smuggled_response;
  10848. sink.write(data.data(), data.size());
  10849. return true;
  10850. });
  10851. });
  10852. thread t = thread([&] { svr.listen(HOST, PORT); });
  10853. auto se = detail::scope_exit([&] {
  10854. svr.stop();
  10855. t.join();
  10856. ASSERT_FALSE(svr.is_running());
  10857. });
  10858. svr.wait_until_ready();
  10859. std::string resp;
  10860. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  10861. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  10862. resp.clear();
  10863. ASSERT_TRUE(send_request(
  10864. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  10865. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  10866. }
  10867. TEST(NoContentTest, BodyIsNotSent) {
  10868. Server svr;
  10869. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  10870. res.status = StatusCode::NoContent_204;
  10871. res.set_content(smuggled_response, "text/plain");
  10872. });
  10873. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  10874. res.status = StatusCode::NotModified_304;
  10875. res.set_chunked_content_provider(
  10876. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  10877. sink.write(smuggled_response.data(), smuggled_response.size());
  10878. sink.done();
  10879. return true;
  10880. });
  10881. });
  10882. thread t = thread([&] { svr.listen(HOST, PORT); });
  10883. auto se = detail::scope_exit([&] {
  10884. svr.stop();
  10885. t.join();
  10886. ASSERT_FALSE(svr.is_running());
  10887. });
  10888. svr.wait_until_ready();
  10889. for (auto path : {"/204", "/304"}) {
  10890. std::string resp;
  10891. ASSERT_TRUE(send_request(
  10892. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  10893. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  10894. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  10895. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  10896. }
  10897. }
  10898. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  10899. Server svr;
  10900. std::atomic<bool> smuggled(false);
  10901. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10902. res.set_content("ok", "text/plain");
  10903. });
  10904. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  10905. smuggled = true;
  10906. });
  10907. auto port = svr.bind_to_any_port(HOST);
  10908. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10909. auto se = detail::scope_exit([&] {
  10910. svr.stop();
  10911. listen_thread.join();
  10912. ASSERT_FALSE(svr.is_running());
  10913. });
  10914. svr.wait_until_ready();
  10915. // What follows the body would be read as the next request.
  10916. Client cli(HOST, port);
  10917. auto res = cli.Post(
  10918. "/", 5,
  10919. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10920. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  10921. sink.write(data.data(), data.size());
  10922. return true;
  10923. },
  10924. "text/plain");
  10925. ASSERT_FALSE(res);
  10926. EXPECT_EQ(Error::Write, res.error());
  10927. EXPECT_FALSE(smuggled);
  10928. }
  10929. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10930. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10931. // The compressed path builds the whole body before connecting, so this
  10932. // fails client-side and never reaches a server.
  10933. Client cli(HOST, PORT);
  10934. cli.set_compress(true);
  10935. auto res = cli.Post(
  10936. "/", 1024,
  10937. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10938. sink.write("hello", 5);
  10939. sink.done(); // short of the 1024 bytes the request announced
  10940. return true;
  10941. },
  10942. "text/plain");
  10943. ASSERT_FALSE(res);
  10944. EXPECT_EQ(Error::Write, res.error());
  10945. }
  10946. #endif
  10947. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10948. Server svr;
  10949. svr.set_error_handler([](Request const &, Response &res) -> void {
  10950. res.set_chunked_content_provider(
  10951. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10952. sink.os << "hello";
  10953. sink.os << "world";
  10954. sink.done();
  10955. return true;
  10956. });
  10957. });
  10958. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10959. auto se = detail::scope_exit([&] {
  10960. svr.stop();
  10961. listen_thread.join();
  10962. ASSERT_FALSE(svr.is_running());
  10963. });
  10964. svr.wait_until_ready();
  10965. Client cli("localhost", PORT);
  10966. auto res = cli.Get("/");
  10967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10968. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10969. EXPECT_EQ("helloworld", res->body);
  10970. }
  10971. // A body set after a content provider must replace it, not be sent through it.
  10972. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10973. Server svr;
  10974. svr.set_mount_point("/", "./www");
  10975. svr.set_file_request_handler([](const Request &req, Response &res) {
  10976. if (req.path == "/dir/test.html") {
  10977. res.status = StatusCode::Forbidden_403;
  10978. res.set_content(std::string(5000, 'D'), "text/plain");
  10979. } else if (req.path == "/file") {
  10980. res.status = StatusCode::Forbidden_403;
  10981. res.body = "Denied";
  10982. }
  10983. });
  10984. auto port = svr.bind_to_any_port(HOST);
  10985. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10986. auto se = detail::scope_exit([&] {
  10987. svr.stop();
  10988. t.join();
  10989. ASSERT_FALSE(svr.is_running());
  10990. });
  10991. svr.wait_until_ready();
  10992. Client cli(HOST, port);
  10993. {
  10994. auto res = cli.Get("/dir/test.html");
  10995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10996. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10997. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10998. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10999. }
  11000. {
  11001. auto res = cli.Get("/file");
  11002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11003. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11004. EXPECT_EQ("Denied", res->body);
  11005. }
  11006. {
  11007. auto res = cli.Get("/dir/index.html");
  11008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11009. EXPECT_EQ(StatusCode::OK_200, res->status);
  11010. EXPECT_EQ(0U, res->body.find("<html>"));
  11011. }
  11012. }
  11013. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11014. Server svr;
  11015. std::vector<bool> released;
  11016. std::mutex released_mutex;
  11017. auto releaser = [&](bool success) {
  11018. std::lock_guard<std::mutex> guard(released_mutex);
  11019. released.push_back(success);
  11020. };
  11021. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11022. return sink.write(&"hello"[offset], length);
  11023. };
  11024. svr.Get("/sized", [&](const Request &, Response &res) {
  11025. res.status = StatusCode::NotFound_404;
  11026. res.set_content_provider(5, "text/plain", provider, releaser);
  11027. });
  11028. svr.Get("/chunked", [&](const Request &, Response &res) {
  11029. res.status = StatusCode::ServiceUnavailable_503;
  11030. res.set_chunked_content_provider(
  11031. "text/plain",
  11032. [](size_t, DataSink &sink) {
  11033. sink.os << "chunk";
  11034. sink.done();
  11035. return true;
  11036. },
  11037. releaser);
  11038. });
  11039. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11040. res.set_content_provider(5, "text/plain", provider, releaser);
  11041. throw std::runtime_error("after the provider");
  11042. });
  11043. svr.set_error_handler([](const Request &req, Response &res) {
  11044. // Leave the exception handler's content to it.
  11045. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11046. res.set_content(std::string(1000, 'E'), "text/html");
  11047. return Server::HandlerResponse::Handled;
  11048. });
  11049. svr.set_exception_handler(
  11050. [](const Request &, Response &res, std::exception_ptr) {
  11051. res.status = StatusCode::InternalServerError_500;
  11052. res.set_content(std::string(1000, 'X'), "text/html");
  11053. });
  11054. auto port = svr.bind_to_any_port(HOST);
  11055. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11056. auto se = detail::scope_exit([&] {
  11057. svr.stop();
  11058. t.join();
  11059. ASSERT_FALSE(svr.is_running());
  11060. });
  11061. svr.wait_until_ready();
  11062. Client cli(HOST, port);
  11063. {
  11064. auto res = cli.Get("/sized");
  11065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11066. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11067. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11068. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11069. }
  11070. {
  11071. auto res = cli.Get("/chunked");
  11072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11073. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11074. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11075. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11076. }
  11077. {
  11078. auto res = cli.Get("/throw");
  11079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11080. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11081. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11082. }
  11083. std::lock_guard<std::mutex> guard(released_mutex);
  11084. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11085. }
  11086. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11087. Server svr;
  11088. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11089. return sink.write(&"abc"[offset], length);
  11090. };
  11091. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11092. res.set_file_content("./www/dir/test.html");
  11093. res.set_content("body", "text/plain");
  11094. });
  11095. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11096. res.set_content(std::string(100, 'B'), "text/plain");
  11097. res.set_file_content("./www/dir/test.html");
  11098. });
  11099. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11100. res.set_content(std::string(100, 'B'), "text/plain");
  11101. res.set_content_provider(3, "text/plain", abc);
  11102. });
  11103. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11104. res.set_content_provider(3, "text/plain", abc);
  11105. res.set_content(std::string(100, 'B'), "text/plain");
  11106. });
  11107. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11108. res.set_content_provider(3, "text/plain", abc);
  11109. res.body = "direct";
  11110. });
  11111. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11112. res.set_file_content("./www/dir/test.html");
  11113. res.body = "direct";
  11114. });
  11115. auto port = svr.bind_to_any_port(HOST);
  11116. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11117. auto se = detail::scope_exit([&] {
  11118. svr.stop();
  11119. t.join();
  11120. ASSERT_FALSE(svr.is_running());
  11121. });
  11122. svr.wait_until_ready();
  11123. Client cli(HOST, port);
  11124. auto expect_body = [&](const char *path, const std::string &body) {
  11125. // Uncompressed, so Content-Length can be compared with the body.
  11126. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11127. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11128. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11129. EXPECT_EQ(body, res->body) << path;
  11130. EXPECT_EQ(std::to_string(body.size()),
  11131. res->get_header_value("Content-Length"))
  11132. << path;
  11133. };
  11134. expect_body("/file-then-body", "body");
  11135. expect_body("/body-then-file", "test.html");
  11136. expect_body("/body-then-provider", "abc");
  11137. expect_body("/provider-then-body", std::string(100, 'B'));
  11138. expect_body("/provider-then-direct-body", "direct");
  11139. expect_body("/file-then-direct-body", "direct");
  11140. // Ranges are checked against the body, not the dropped provider.
  11141. {
  11142. auto res = cli.Get("/provider-then-direct-body",
  11143. Headers{{make_range_header({{1, 2}})}});
  11144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11145. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11146. EXPECT_EQ("ir", res->body);
  11147. }
  11148. {
  11149. auto res = cli.Get("/file-then-direct-body",
  11150. Headers{{make_range_header({{7, 8}})}});
  11151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11152. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11153. }
  11154. }
  11155. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11156. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11157. const char *path = "./truncated_while_served.txt";
  11158. const size_t size = 32 * 1024 * 1024;
  11159. {
  11160. std::ofstream f(path, std::ios::binary);
  11161. f << std::string(size, 'x');
  11162. }
  11163. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11164. // Over TLS, where the bytes are encrypted in this process rather than
  11165. // copied by send().
  11166. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11167. svr.Get("/file", [&](const Request &, Response &res) {
  11168. res.set_file_content(path, "text/plain");
  11169. });
  11170. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11171. auto se = detail::scope_exit([&] {
  11172. svr.stop();
  11173. thread.join();
  11174. ASSERT_FALSE(svr.is_running());
  11175. });
  11176. svr.wait_until_ready();
  11177. // The file shrinks once the first bytes are in, as a rewrite in place
  11178. // would, and reading the mapping past its new end used to raise SIGBUS.
  11179. SSLClient cli(HOST, PORT);
  11180. cli.enable_server_certificate_verification(false);
  11181. size_t received = 0;
  11182. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11183. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11184. received += len;
  11185. return true;
  11186. });
  11187. EXPECT_FALSE(res);
  11188. EXPECT_LT(received, size);
  11189. }
  11190. #endif
  11191. // Forward declaration (see the base64_encode note).
  11192. namespace httplib {
  11193. namespace detail {
  11194. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11195. const std::string &content_type,
  11196. EncodingType encoding);
  11197. } // namespace detail
  11198. } // namespace httplib
  11199. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11200. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11201. ASSERT_TRUE(mm->is_open());
  11202. Response res;
  11203. detail::set_file_content_provider(res, mm, "text/html",
  11204. detail::EncodingType::None);
  11205. std::string out;
  11206. DataSink sink;
  11207. sink.write = [&](const char *d, size_t l) {
  11208. out.append(d, l);
  11209. return true;
  11210. };
  11211. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11212. EXPECT_EQ("test.html", out);
  11213. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11214. EXPECT_EQ("test.html", out);
  11215. }
  11216. TEST(LongPollingTest, ClientCloseDetection) {
  11217. Server svr;
  11218. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11219. res.set_chunked_content_provider(
  11220. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11221. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11222. sink.os << "hello";
  11223. auto count = 10;
  11224. while (count > 0 && sink.is_writable()) {
  11225. this_thread::sleep_for(chrono::milliseconds(10));
  11226. count--;
  11227. }
  11228. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11229. return true;
  11230. });
  11231. });
  11232. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11233. auto se = detail::scope_exit([&] {
  11234. svr.stop();
  11235. listen_thread.join();
  11236. ASSERT_FALSE(svr.is_running());
  11237. });
  11238. svr.wait_until_ready();
  11239. Client cli("localhost", PORT);
  11240. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11241. EXPECT_EQ("hello", string(data, data_length));
  11242. return false; // close the socket immediately.
  11243. });
  11244. ASSERT_FALSE(res);
  11245. }
  11246. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11247. Server svr;
  11248. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11249. res.set_chunked_content_provider(
  11250. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11251. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11252. sink.os << "hello";
  11253. EXPECT_TRUE(sink.os.good());
  11254. // Wait for the client to close the connection
  11255. auto count = 10;
  11256. while (count > 0 && sink.is_writable()) {
  11257. this_thread::sleep_for(chrono::milliseconds(10));
  11258. count--;
  11259. }
  11260. // After client disconnect, write repeatedly until the socket
  11261. // write actually fails (small writes may be absorbed by the
  11262. // kernel buffer)
  11263. std::string chunk(1024, 'x');
  11264. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11265. sink.os << chunk;
  11266. }
  11267. EXPECT_TRUE(sink.os.fail());
  11268. return true;
  11269. });
  11270. });
  11271. auto port = svr.bind_to_any_port("localhost");
  11272. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11273. auto se = detail::scope_exit([&] {
  11274. svr.stop();
  11275. listen_thread.join();
  11276. ASSERT_FALSE(svr.is_running());
  11277. });
  11278. svr.wait_until_ready();
  11279. Client cli("localhost", port);
  11280. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11281. EXPECT_EQ("hello", string(data, data_length));
  11282. return false; // close the socket immediately.
  11283. });
  11284. ASSERT_FALSE(res);
  11285. }
  11286. TEST(GetWithParametersTest, GetWithParameters) {
  11287. Server svr;
  11288. svr.Get("/", [&](const Request &req, Response &) {
  11289. EXPECT_EQ("world", req.get_param_value("hello"));
  11290. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11291. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11292. });
  11293. svr.Get("/params", [&](const Request &req, Response &) {
  11294. EXPECT_EQ("world", req.get_param_value("hello"));
  11295. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11296. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11297. });
  11298. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11299. EXPECT_EQ("resource-id", req.matches[1]);
  11300. EXPECT_EQ("foo", req.get_param_value("param1"));
  11301. EXPECT_EQ("bar", req.get_param_value("param2"));
  11302. });
  11303. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11304. EXPECT_EQ("user-id", req.path_params.at("id"));
  11305. EXPECT_EQ("foo", req.get_param_value("param1"));
  11306. EXPECT_EQ("bar", req.get_param_value("param2"));
  11307. });
  11308. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11309. auto se = detail::scope_exit([&] {
  11310. svr.stop();
  11311. listen_thread.join();
  11312. ASSERT_FALSE(svr.is_running());
  11313. });
  11314. svr.wait_until_ready();
  11315. {
  11316. Client cli(HOST, PORT);
  11317. Params params;
  11318. params.emplace("hello", "world");
  11319. params.emplace("hello2", "world2");
  11320. params.emplace("hello3", "world3");
  11321. auto res = cli.Get("/", params, Headers{});
  11322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11323. EXPECT_EQ(StatusCode::OK_200, res->status);
  11324. }
  11325. {
  11326. Client cli(HOST, PORT);
  11327. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11329. EXPECT_EQ(StatusCode::OK_200, res->status);
  11330. }
  11331. {
  11332. Client cli(HOST, PORT);
  11333. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11335. EXPECT_EQ(StatusCode::OK_200, res->status);
  11336. }
  11337. {
  11338. Client cli(HOST, PORT);
  11339. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11341. EXPECT_EQ(StatusCode::OK_200, res->status);
  11342. }
  11343. }
  11344. TEST(GetWithParametersTest, GetWithParameters2) {
  11345. Server svr;
  11346. svr.Get("/", [&](const Request &req, Response &res) {
  11347. auto text = req.get_param_value("hello");
  11348. res.set_content(text, "text/plain");
  11349. });
  11350. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11351. auto se = detail::scope_exit([&] {
  11352. svr.stop();
  11353. listen_thread.join();
  11354. ASSERT_FALSE(svr.is_running());
  11355. });
  11356. svr.wait_until_ready();
  11357. Client cli("localhost", PORT);
  11358. Params params;
  11359. params.emplace("hello", "world");
  11360. std::string body;
  11361. auto res = cli.Get("/", params, Headers{},
  11362. [&](const char *data, size_t data_length) {
  11363. body.append(data, data_length);
  11364. return true;
  11365. });
  11366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11367. EXPECT_EQ(StatusCode::OK_200, res->status);
  11368. EXPECT_EQ("world", body);
  11369. }
  11370. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11371. Server svr;
  11372. svr.Get("/search", [&](const Request &req, Response &res) {
  11373. auto q = req.get_param_value("q");
  11374. res.set_content(q, "text/plain");
  11375. });
  11376. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11377. auto se = detail::scope_exit([&] {
  11378. svr.stop();
  11379. listen_thread.join();
  11380. ASSERT_FALSE(svr.is_running());
  11381. });
  11382. svr.wait_until_ready();
  11383. Client cli("localhost", PORT);
  11384. // Verify that Get(path, params) works without requiring Headers argument
  11385. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11387. EXPECT_EQ(StatusCode::OK_200, res->status);
  11388. EXPECT_EQ("cpp-httplib", res->body);
  11389. }
  11390. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11391. auto host = "httpbingo.org";
  11392. auto path = std::string{"/range/32"};
  11393. #ifdef CPPHTTPLIB_SSL_ENABLED
  11394. SSLClient cli(host);
  11395. #else
  11396. Client cli(host);
  11397. #endif
  11398. cli.set_default_headers({make_range_header({{1, 10}})});
  11399. cli.set_connection_timeout(5);
  11400. {
  11401. auto res = cli.Get(path);
  11402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11403. EXPECT_EQ("bcdefghijk", res->body);
  11404. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11405. }
  11406. {
  11407. auto res = cli.Get(path);
  11408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11409. EXPECT_EQ("bcdefghijk", res->body);
  11410. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11411. }
  11412. }
  11413. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11414. Server svr;
  11415. svr.set_default_headers({{"Hello", "World"}});
  11416. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11417. res.set_content("ok", "text/plain");
  11418. });
  11419. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11420. auto se = detail::scope_exit([&] {
  11421. svr.stop();
  11422. listen_thread.join();
  11423. ASSERT_FALSE(svr.is_running());
  11424. });
  11425. svr.wait_until_ready();
  11426. Client cli("localhost", PORT);
  11427. auto res = cli.Get("/");
  11428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11429. EXPECT_EQ(StatusCode::OK_200, res->status);
  11430. EXPECT_EQ("ok", res->body);
  11431. EXPECT_EQ("World", res->get_header_value("Hello"));
  11432. }
  11433. #ifdef CPPHTTPLIB_SSL_ENABLED
  11434. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11435. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11436. ASSERT_TRUE(svr.is_valid());
  11437. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11438. std::this_thread::sleep_for(std::chrono::seconds(2));
  11439. res.set_content("a", "text/plain");
  11440. });
  11441. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11442. res.set_content("b", "text/plain");
  11443. });
  11444. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11445. auto se = detail::scope_exit([&] {
  11446. svr.stop();
  11447. listen_thread.join();
  11448. ASSERT_FALSE(svr.is_running());
  11449. });
  11450. svr.wait_until_ready();
  11451. SSLClient cli("localhost", PORT);
  11452. cli.enable_server_certificate_verification(false);
  11453. cli.set_keep_alive(true);
  11454. cli.set_read_timeout(std::chrono::seconds(1));
  11455. auto resa = cli.Get("/a");
  11456. ASSERT_TRUE(!resa);
  11457. EXPECT_EQ(Error::Read, resa.error());
  11458. auto resb = cli.Get("/b");
  11459. ASSERT_TRUE(resb);
  11460. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11461. EXPECT_EQ("b", resb->body);
  11462. }
  11463. // Closing an idle keep-alive connection sends close_notify and returns. The
  11464. // server must not wait for the client's close_notify: an idle client never
  11465. // sends one, so the worker would be held until the read timeout expires, and
  11466. // stop() would wait for it.
  11467. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11469. ASSERT_TRUE(svr.is_valid());
  11470. svr.set_keep_alive_timeout(1);
  11471. svr.set_read_timeout(10, 0);
  11472. svr.Get("/", [](const Request &, Response &res) {
  11473. res.set_content("ok", "text/plain");
  11474. });
  11475. auto port = svr.bind_to_any_port(HOST);
  11476. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11477. auto se = detail::scope_exit([&] {
  11478. if (listen_thread.joinable()) {
  11479. svr.stop();
  11480. listen_thread.join();
  11481. }
  11482. });
  11483. svr.wait_until_ready();
  11484. SSLClient cli(HOST, port);
  11485. cli.enable_server_certificate_verification(false);
  11486. cli.set_keep_alive(true);
  11487. auto res = cli.Get("/");
  11488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11489. EXPECT_EQ(StatusCode::OK_200, res->status);
  11490. // Stay idle past the keep-alive timeout so the server closes the connection.
  11491. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11492. auto start = std::chrono::steady_clock::now();
  11493. svr.stop();
  11494. listen_thread.join();
  11495. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11496. std::chrono::steady_clock::now() - start)
  11497. .count();
  11498. EXPECT_LT(elapsed, 3000);
  11499. }
  11500. #endif
  11501. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11502. protected:
  11503. ServerTestWithAI_PASSIVE()
  11504. : cli_(HOST, PORT)
  11505. #ifdef CPPHTTPLIB_SSL_ENABLED
  11506. ,
  11507. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11508. #endif
  11509. {
  11510. #ifdef CPPHTTPLIB_SSL_ENABLED
  11511. cli_.enable_server_certificate_verification(false);
  11512. #endif
  11513. }
  11514. virtual void SetUp() {
  11515. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11516. res.set_content("Hello World!", "text/plain");
  11517. });
  11518. t_ = thread(
  11519. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11520. svr_.wait_until_ready();
  11521. }
  11522. virtual void TearDown() {
  11523. svr_.stop();
  11524. t_.join();
  11525. }
  11526. #ifdef CPPHTTPLIB_SSL_ENABLED
  11527. SSLClient cli_;
  11528. SSLServer svr_;
  11529. #else
  11530. Client cli_;
  11531. Server svr_;
  11532. #endif
  11533. thread t_;
  11534. };
  11535. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11536. auto res = cli_.Get("/hi");
  11537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11538. EXPECT_EQ(StatusCode::OK_200, res->status);
  11539. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11540. EXPECT_EQ("Hello World!", res->body);
  11541. }
  11542. class ServerUpDownTest : public ::testing::Test {
  11543. protected:
  11544. ServerUpDownTest() : cli_(HOST, PORT) {}
  11545. virtual void SetUp() {
  11546. t_ = thread([&]() {
  11547. svr_.bind_to_any_port(HOST);
  11548. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11549. ASSERT_TRUE(svr_.listen_after_bind());
  11550. });
  11551. svr_.wait_until_ready();
  11552. }
  11553. virtual void TearDown() {
  11554. svr_.stop();
  11555. t_.join();
  11556. }
  11557. Client cli_;
  11558. Server svr_;
  11559. thread t_;
  11560. };
  11561. TEST_F(ServerUpDownTest, QuickStartStop) {
  11562. // Should not crash, especially when run with
  11563. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11564. }
  11565. class PayloadMaxLengthTest : public ::testing::Test {
  11566. protected:
  11567. PayloadMaxLengthTest()
  11568. : cli_(HOST, PORT)
  11569. #ifdef CPPHTTPLIB_SSL_ENABLED
  11570. ,
  11571. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11572. #endif
  11573. {
  11574. #ifdef CPPHTTPLIB_SSL_ENABLED
  11575. cli_.enable_server_certificate_verification(false);
  11576. #endif
  11577. }
  11578. virtual void SetUp() {
  11579. svr_.set_payload_max_length(8);
  11580. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11581. res.set_content("test", "text/plain");
  11582. });
  11583. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11584. svr_.wait_until_ready();
  11585. }
  11586. virtual void TearDown() {
  11587. svr_.stop();
  11588. t_.join();
  11589. }
  11590. #ifdef CPPHTTPLIB_SSL_ENABLED
  11591. SSLClient cli_;
  11592. SSLServer svr_;
  11593. #else
  11594. Client cli_;
  11595. Server svr_;
  11596. #endif
  11597. thread t_;
  11598. };
  11599. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11600. auto res = cli_.Post("/test", "123456789", "text/plain");
  11601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11602. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11603. res = cli_.Post("/test", "12345678", "text/plain");
  11604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11605. EXPECT_EQ(StatusCode::OK_200, res->status);
  11606. }
  11607. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11608. // Test chunked encoding with payload exceeding the 8-byte limit
  11609. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11610. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11612. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11613. }
  11614. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11615. // Test chunked encoding with payload within the 8-byte limit
  11616. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11617. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11619. EXPECT_EQ(StatusCode::OK_200, res->status);
  11620. }
  11621. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11622. // Test using send_request to send chunked data exceeding payload limit
  11623. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11624. "Host: " +
  11625. std::string(HOST) + ":" + std::to_string(PORT) +
  11626. "\r\n"
  11627. "Transfer-Encoding: chunked\r\n"
  11628. "Connection: close\r\n"
  11629. "\r\n"
  11630. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11631. "0123456789\r\n"
  11632. "0\r\n" // End chunk
  11633. "\r\n";
  11634. std::string response;
  11635. bool result = send_request(1, chunked_request, &response);
  11636. if (!result) {
  11637. // If send_request fails, it might be because the server closed the
  11638. // connection due to payload limit enforcement, which is acceptable
  11639. SUCCEED()
  11640. << "Server rejected oversized chunked request (connection closed)";
  11641. } else {
  11642. // If we got a response, check if it's an error response or connection was
  11643. // closed early Short response length indicates connection was closed due to
  11644. // payload limit
  11645. if (response.length() <= 10) {
  11646. SUCCEED() << "Server closed connection for oversized chunked request";
  11647. } else {
  11648. // Check for error status codes
  11649. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11650. response.find("Payload Too Large") != std::string::npos ||
  11651. response.find("400") != std::string::npos);
  11652. }
  11653. }
  11654. }
  11655. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11656. // Test request without Content-Length header exceeding payload limit
  11657. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11658. "Host: " +
  11659. std::string(HOST) + ":" +
  11660. std::to_string(PORT) +
  11661. "\r\n"
  11662. "Connection: close\r\n"
  11663. "\r\n";
  11664. // Add payload exceeding the 8-byte limit
  11665. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11666. request_without_content_length += large_payload;
  11667. std::string response;
  11668. bool result = send_request(1, request_without_content_length, &response);
  11669. if (!result) {
  11670. // If send_request fails, server likely closed connection due to payload
  11671. // limit
  11672. SUCCEED() << "Server rejected oversized request without Content-Length "
  11673. "(connection closed)";
  11674. } else {
  11675. // Check if server responded with error or closed connection early
  11676. if (response.length() <= 10) {
  11677. SUCCEED() << "Server closed connection for oversized request without "
  11678. "Content-Length";
  11679. } else {
  11680. // Check for error status codes
  11681. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11682. response.find("Payload Too Large") != std::string::npos ||
  11683. response.find("400") != std::string::npos);
  11684. }
  11685. }
  11686. }
  11687. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11688. // Test request without Content-Length header within payload limit
  11689. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11690. "Host: " +
  11691. std::string(HOST) + ":" +
  11692. std::to_string(PORT) +
  11693. "\r\n"
  11694. "Connection: close\r\n"
  11695. "\r\n";
  11696. // Add payload within the 8-byte limit
  11697. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11698. request_without_content_length += small_payload;
  11699. std::string response;
  11700. bool result = send_request(1, request_without_content_length, &response);
  11701. // For requests without Content-Length, the server may have different behavior
  11702. // The key is that it should not reject due to payload limit for small
  11703. // payloads
  11704. if (result) {
  11705. // Check for any HTTP response (success or error, but not connection closed)
  11706. if (response.length() > 10) {
  11707. SUCCEED()
  11708. << "Server processed request without Content-Length within limit";
  11709. } else {
  11710. // Short response might indicate connection closed, which is acceptable
  11711. SUCCEED() << "Server closed connection for request without "
  11712. "Content-Length (acceptable behavior)";
  11713. }
  11714. } else {
  11715. // Connection failure might be due to protocol requirements
  11716. SUCCEED() << "Connection issue with request without Content-Length "
  11717. "(environment-specific)";
  11718. }
  11719. }
  11720. class LargePayloadMaxLengthTest : public ::testing::Test {
  11721. protected:
  11722. LargePayloadMaxLengthTest()
  11723. : cli_(HOST, PORT)
  11724. #ifdef CPPHTTPLIB_SSL_ENABLED
  11725. ,
  11726. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11727. #endif
  11728. {
  11729. #ifdef CPPHTTPLIB_SSL_ENABLED
  11730. cli_.enable_server_certificate_verification(false);
  11731. #endif
  11732. }
  11733. virtual void SetUp() {
  11734. // Set 10MB payload limit
  11735. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11736. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11737. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11738. res.set_content("Large payload test", "text/plain");
  11739. });
  11740. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11741. svr_.wait_until_ready();
  11742. }
  11743. virtual void TearDown() {
  11744. svr_.stop();
  11745. t_.join();
  11746. }
  11747. #ifdef CPPHTTPLIB_SSL_ENABLED
  11748. SSLClient cli_;
  11749. SSLServer svr_;
  11750. #else
  11751. Client cli_;
  11752. Server svr_;
  11753. #endif
  11754. thread t_;
  11755. };
  11756. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11757. // Test chunked encoding with payload within 10MB limit
  11758. std::string medium_payload(5 * 1024 * 1024,
  11759. 'A'); // 5MB payload, within 10MB limit
  11760. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11762. EXPECT_EQ(StatusCode::OK_200, res->status);
  11763. }
  11764. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11765. // Test chunked encoding with payload exceeding 10MB limit
  11766. std::string large_payload(12 * 1024 * 1024,
  11767. 'B'); // 12MB payload, exceeds 10MB limit
  11768. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11769. // Server may either return 413 or close the connection
  11770. if (res) {
  11771. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11772. } else {
  11773. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11774. }
  11775. }
  11776. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11777. // Test request without Content-Length header within 10MB limit
  11778. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11779. "Host: " +
  11780. std::string(HOST) + ":" +
  11781. std::to_string(PORT) +
  11782. "\r\n"
  11783. "Connection: close\r\n"
  11784. "\r\n";
  11785. // Add 1MB payload (within 10MB limit)
  11786. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11787. request_without_content_length += medium_payload;
  11788. std::string response;
  11789. bool result = send_request(5, request_without_content_length, &response);
  11790. if (result) {
  11791. // Should get a proper HTTP response for payloads within limit
  11792. if (response.length() > 10) {
  11793. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11794. "10MB limit";
  11795. } else {
  11796. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11797. "Content-Length)";
  11798. }
  11799. } else {
  11800. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11801. }
  11802. }
  11803. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11804. // Test request without Content-Length header exceeding 10MB limit
  11805. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11806. "Host: " +
  11807. std::string(HOST) + ":" +
  11808. std::to_string(PORT) +
  11809. "\r\n"
  11810. "Connection: close\r\n"
  11811. "\r\n";
  11812. // Add 12MB payload (exceeds 10MB limit)
  11813. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11814. request_without_content_length += large_payload;
  11815. std::string response;
  11816. bool result = send_request(10, request_without_content_length, &response);
  11817. if (!result) {
  11818. // Server should close connection due to payload limit
  11819. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11820. "(connection closed)";
  11821. } else {
  11822. // Check for error response
  11823. if (response.length() <= 10) {
  11824. SUCCEED()
  11825. << "Server closed connection for 12MB request exceeding 10MB limit";
  11826. } else {
  11827. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11828. response.find("Payload Too Large") != std::string::npos ||
  11829. response.find("400") != std::string::npos);
  11830. }
  11831. }
  11832. }
  11833. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11834. Server svr;
  11835. svr.Get("/", [](const Request &, Response &res) {
  11836. // Claims far more than it sends, then drops the connection.
  11837. res.set_content_provider(size_t(1) << 41, "text/plain",
  11838. [](size_t, size_t, DataSink &sink) {
  11839. sink.write("abc", 3);
  11840. return false;
  11841. });
  11842. });
  11843. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11844. auto se = detail::scope_exit([&] {
  11845. svr.stop();
  11846. thread.join();
  11847. ASSERT_FALSE(svr.is_running());
  11848. });
  11849. svr.wait_until_ready();
  11850. Client cli(HOST, PORT);
  11851. cli.set_payload_max_length(0);
  11852. EXPECT_FALSE(cli.Get("/"));
  11853. }
  11854. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11855. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11856. // path.
  11857. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11858. Server svr;
  11859. const size_t LIMIT = 64 * 1024; // 64KB
  11860. svr.set_payload_max_length(LIMIT);
  11861. size_t total = 0;
  11862. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11863. const ContentReader &content_reader) {
  11864. content_reader([&](const char * /*data*/, size_t len) {
  11865. total += len;
  11866. return true;
  11867. });
  11868. res.status = 200;
  11869. res.set_content("stream_ok", "text/plain");
  11870. });
  11871. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11872. auto se = detail::scope_exit([&] {
  11873. svr.stop();
  11874. thread.join();
  11875. ASSERT_FALSE(svr.is_running());
  11876. });
  11877. svr.wait_until_ready();
  11878. // Prepare 256KB raw data and gzip-compress it
  11879. std::string raw(256 * 1024, 'A');
  11880. std::string gz;
  11881. {
  11882. z_stream zs{};
  11883. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11884. Z_DEFAULT_STRATEGY);
  11885. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11886. zs.avail_in = static_cast<uInt>(raw.size());
  11887. char outbuf[4096];
  11888. int ret;
  11889. do {
  11890. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11891. zs.avail_out = sizeof(outbuf);
  11892. ret = deflate(&zs, Z_FINISH);
  11893. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11894. } while (ret != Z_STREAM_END);
  11895. deflateEnd(&zs);
  11896. }
  11897. Client cli(HOST, PORT);
  11898. cli.set_connection_timeout(std::chrono::seconds(5));
  11899. Headers headers = {{"Content-Encoding", "gzip"}};
  11900. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11901. "application/octet-stream");
  11902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11903. // Server must reject oversized decompressed payloads with 413.
  11904. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11905. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11906. EXPECT_LE(total, LIMIT);
  11907. }
  11908. #ifndef CPPHTTPLIB_SSL_ENABLED
  11909. // For a request with neither Content-Length nor Transfer-Encoding, the
  11910. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11911. // compressed wire bytes straight to the ContentReader without ever routing
  11912. // them through the decompressor, so payload_max_length_ only bounded the
  11913. // compressed size on the wire, not the decompressed size.
  11914. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11915. Server svr;
  11916. const size_t LIMIT = 64 * 1024; // 64KB
  11917. svr.set_payload_max_length(LIMIT);
  11918. size_t total = 0;
  11919. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11920. const ContentReader &content_reader) {
  11921. content_reader([&](const char * /*data*/, size_t len) {
  11922. total += len;
  11923. return true;
  11924. });
  11925. res.status = 200;
  11926. res.set_content("stream_ok", "text/plain");
  11927. });
  11928. auto port = svr.bind_to_any_port(HOST);
  11929. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11930. auto se = detail::scope_exit([&] {
  11931. svr.stop();
  11932. thread.join();
  11933. ASSERT_FALSE(svr.is_running());
  11934. });
  11935. svr.wait_until_ready();
  11936. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11937. // StreamingGzipDecompression test above.
  11938. std::string raw(256 * 1024, 'A');
  11939. std::string gz;
  11940. {
  11941. httplib::detail::gzip_compressor compressor;
  11942. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11943. [&](const char *chunk, size_t len) {
  11944. gz.append(chunk, len);
  11945. return true;
  11946. });
  11947. ASSERT_TRUE(result);
  11948. }
  11949. // Send the gzip body over raw TCP with neither Content-Length nor
  11950. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11951. // kicks in.
  11952. std::string req = "POST /stream HTTP/1.1\r\n"
  11953. "Host: " +
  11954. std::string(HOST) + ":" + std::to_string(port) +
  11955. "\r\n"
  11956. "Content-Encoding: gzip\r\n"
  11957. "Connection: close\r\n"
  11958. "\r\n" +
  11959. gz;
  11960. std::string response;
  11961. ASSERT_TRUE(send_request(5, req, &response, port));
  11962. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11963. EXPECT_LE(total, LIMIT);
  11964. }
  11965. #endif
  11966. #endif
  11967. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11968. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11969. // the payload must be passed through untouched instead of being rejected.
  11970. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11971. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11972. Server svr;
  11973. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11974. res.set_content(body, "image/jpeg");
  11975. res.set_header("Content-Encoding", "UTF-8");
  11976. });
  11977. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11978. res.set_content(body, "image/jpeg");
  11979. res.set_header("Content-Encoding", "identity");
  11980. });
  11981. svr.Post("/echo", [](const Request &req, Response &res) {
  11982. res.set_content(req.body, "image/jpeg");
  11983. });
  11984. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11985. auto se = detail::scope_exit([&] {
  11986. svr.stop();
  11987. t.join();
  11988. ASSERT_FALSE(svr.is_running());
  11989. });
  11990. svr.wait_until_ready();
  11991. Client cli(HOST, PORT);
  11992. {
  11993. auto res = cli.Get("/image");
  11994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11995. EXPECT_EQ(StatusCode::OK_200, res->status);
  11996. EXPECT_EQ(body, res->body);
  11997. }
  11998. {
  11999. auto res = cli.Get("/identity");
  12000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12001. EXPECT_EQ(StatusCode::OK_200, res->status);
  12002. EXPECT_EQ(body, res->body);
  12003. }
  12004. {
  12005. // The same applies to a request body reaching the server.
  12006. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12007. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12009. EXPECT_EQ(StatusCode::OK_200, res->status);
  12010. EXPECT_EQ(body, res->body);
  12011. }
  12012. }
  12013. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12014. // gzip-encoded response even when the build has no zlib support.
  12015. static const char GZIPPED_HELLO_WORLD[] = {
  12016. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12017. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12018. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12019. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12020. // A content coding is a whole token, not something the field value merely
  12021. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12022. // as "fibre" look like Brotli, and turned a multi-coding value like
  12023. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12024. // it was never meant to see.
  12025. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12026. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12027. Server svr;
  12028. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12029. res.set_content(body, "image/jpeg");
  12030. res.set_header("Content-Encoding", "fibre");
  12031. });
  12032. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12033. res.set_content(body, "image/jpeg");
  12034. res.set_header("Content-Encoding", "gzip, br");
  12035. });
  12036. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12037. res.set_content(body, "image/jpeg");
  12038. res.set_header("Content-Encoding", "x-zstd-ish");
  12039. });
  12040. auto port = svr.bind_to_any_port(HOST);
  12041. thread t = thread([&]() { svr.listen_after_bind(); });
  12042. auto se = detail::scope_exit([&] {
  12043. svr.stop();
  12044. t.join();
  12045. ASSERT_FALSE(svr.is_running());
  12046. });
  12047. svr.wait_until_ready();
  12048. Client cli(HOST, port);
  12049. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12050. auto res = cli.Get(path);
  12051. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12052. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12053. // Not a coding we recognize, so the payload comes back untouched
  12054. EXPECT_EQ(body, res->body) << path;
  12055. }
  12056. }
  12057. // A content coding cpp-httplib recognizes but was not built with must be
  12058. // reported as such. Handing the still-compressed payload back to the caller
  12059. // would silently corrupt it.
  12060. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12061. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12062. Server svr;
  12063. // "image/jpeg" keeps the server from applying a content coding of its own,
  12064. // so the hand-crafted Content-Encoding below survives.
  12065. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12066. res.set_content(gzipped, "image/jpeg");
  12067. res.set_header("Content-Encoding", "gzip");
  12068. });
  12069. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12070. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12071. res.set_content(gzipped, "image/jpeg");
  12072. res.set_header("Content-Encoding", "GZIP");
  12073. });
  12074. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12075. auto se = detail::scope_exit([&] {
  12076. svr.stop();
  12077. t.join();
  12078. ASSERT_FALSE(svr.is_running());
  12079. });
  12080. svr.wait_until_ready();
  12081. Client cli(HOST, PORT);
  12082. {
  12083. auto res = cli.Get("/gzipped");
  12084. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12086. EXPECT_EQ("Hello World!", res->body);
  12087. #else
  12088. ASSERT_FALSE(res);
  12089. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12090. #endif
  12091. }
  12092. {
  12093. // open_stream() must behave the same way.
  12094. auto handle = cli.open_stream("GET", "/gzipped");
  12095. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12096. ASSERT_TRUE(handle.is_valid());
  12097. std::string received;
  12098. char buf[256];
  12099. ssize_t n;
  12100. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12101. received.append(buf, static_cast<size_t>(n));
  12102. }
  12103. EXPECT_EQ("Hello World!", received);
  12104. #else
  12105. EXPECT_FALSE(handle.is_valid());
  12106. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12107. #endif
  12108. }
  12109. {
  12110. // A differently-cased coding must not be mistaken for an unknown one, or
  12111. // the body would be handed back still compressed.
  12112. auto res = cli.Get("/gzipped-uppercase");
  12113. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12115. EXPECT_EQ("Hello World!", res->body);
  12116. #else
  12117. ASSERT_FALSE(res);
  12118. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12119. #endif
  12120. }
  12121. }
  12122. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12123. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12124. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12125. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12126. // body a second time and appending a second Content-Encoding field line, so
  12127. // clients that decode one coding per listed value handed back raw gzip bytes.
  12128. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12129. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12130. Server svr;
  12131. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12132. // keeps the server from applying a coding of its own.
  12133. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12134. res.set_content(gzipped, "text/plain");
  12135. res.set_header("Content-Encoding", "gzip");
  12136. });
  12137. auto port = svr.bind_to_any_port(HOST);
  12138. thread t = thread([&]() { svr.listen_after_bind(); });
  12139. auto se = detail::scope_exit([&] {
  12140. svr.stop();
  12141. t.join();
  12142. ASSERT_FALSE(svr.is_running());
  12143. });
  12144. svr.wait_until_ready();
  12145. Client cli(HOST, port);
  12146. Headers headers = {{"Accept-Encoding", "gzip"}};
  12147. auto res = cli.Get("/pre-gzipped", headers);
  12148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12149. EXPECT_EQ(StatusCode::OK_200, res->status);
  12150. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12151. EXPECT_EQ("Hello World!", res->body);
  12152. }
  12153. // A chunked provider settles its coding where the headers are written and
  12154. // reuses it at write time. Both ends of that have to hold: a handler's own
  12155. // Content-Encoding suppresses the coding, and a response without one is still
  12156. // compressed as it always was.
  12157. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12158. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12159. const std::string plain = "Hello World! Hello World! Hello World!";
  12160. Server svr;
  12161. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12162. res.set_header("Content-Encoding", "gzip");
  12163. res.set_chunked_content_provider(
  12164. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12165. sink.write(gzipped.data(), gzipped.size());
  12166. sink.done();
  12167. return true;
  12168. });
  12169. });
  12170. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12171. res.set_chunked_content_provider(
  12172. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12173. sink.write(plain.data(), plain.size());
  12174. sink.done();
  12175. return true;
  12176. });
  12177. });
  12178. auto port = svr.bind_to_any_port(HOST);
  12179. thread t = thread([&]() { svr.listen_after_bind(); });
  12180. auto se = detail::scope_exit([&] {
  12181. svr.stop();
  12182. t.join();
  12183. ASSERT_FALSE(svr.is_running());
  12184. });
  12185. svr.wait_until_ready();
  12186. Client cli(HOST, port);
  12187. Headers headers = {{"Accept-Encoding", "gzip"}};
  12188. {
  12189. auto res = cli.Get("/pre-gzipped", headers);
  12190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12191. EXPECT_EQ(StatusCode::OK_200, res->status);
  12192. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12193. EXPECT_EQ("Hello World!", res->body);
  12194. }
  12195. {
  12196. auto res = cli.Get("/negotiated", headers);
  12197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12198. EXPECT_EQ(StatusCode::OK_200, res->status);
  12199. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12200. EXPECT_EQ(plain, res->body);
  12201. }
  12202. }
  12203. #endif
  12204. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12205. // the same message as the comma-joined one, so both have to be read the same
  12206. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12207. // single gzip coding, and a body the sender says was encoded twice was handed
  12208. // back after one pass, still compressed but presented as decoded.
  12209. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12210. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12211. Server svr;
  12212. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12213. res.set_content(body, "image/jpeg");
  12214. res.headers.emplace("Content-Encoding", "gzip");
  12215. res.headers.emplace("Content-Encoding", "gzip");
  12216. });
  12217. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12218. res.set_content(body, "image/jpeg");
  12219. res.set_header("Content-Encoding", "gzip, gzip");
  12220. });
  12221. auto port = svr.bind_to_any_port(HOST);
  12222. thread t = thread([&]() { svr.listen_after_bind(); });
  12223. auto se = detail::scope_exit([&] {
  12224. svr.stop();
  12225. t.join();
  12226. ASSERT_FALSE(svr.is_running());
  12227. });
  12228. svr.wait_until_ready();
  12229. Client cli(HOST, port);
  12230. // Two codings is not something cpp-httplib decodes, so both representations
  12231. // take the pass-through path rather than one of them being gunzipped once.
  12232. for (const char *path : {"/split", "/joined"}) {
  12233. auto res = cli.Get(path);
  12234. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12235. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12236. EXPECT_EQ(body, res->body) << path;
  12237. }
  12238. }
  12239. // Regression test for DoS vulnerability: a malicious server sending a response
  12240. // without Content-Length header must not cause unbounded memory consumption on
  12241. // the client side. The client should stop reading after a reasonable limit,
  12242. // similar to the server-side set_payload_max_length protection.
  12243. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12244. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12245. #ifndef _WIN32
  12246. signal(SIGPIPE, SIG_IGN);
  12247. #endif
  12248. auto server_thread = std::thread([] {
  12249. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12250. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12251. default_socket_options(srv);
  12252. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12253. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12254. sockaddr_in addr{};
  12255. addr.sin_family = AF_INET;
  12256. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12257. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12258. int opt = 1;
  12259. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12260. #ifdef _WIN32
  12261. reinterpret_cast<const char *>(&opt),
  12262. #else
  12263. &opt,
  12264. #endif
  12265. sizeof(opt));
  12266. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12267. ::listen(srv, 1);
  12268. sockaddr_in cli_addr{};
  12269. socklen_t cli_len = sizeof(cli_addr);
  12270. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12271. if (cli != INVALID_SOCKET) {
  12272. char buf[4096];
  12273. ::recv(cli, buf, sizeof(buf), 0);
  12274. // Malicious response: no Content-Length, no chunked encoding
  12275. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12276. "Connection: close\r\n"
  12277. "\r\n";
  12278. ::send(cli,
  12279. #ifdef _WIN32
  12280. static_cast<const char *>(response_header.c_str()),
  12281. static_cast<int>(response_header.size()),
  12282. #else
  12283. response_header.c_str(), response_header.size(),
  12284. #endif
  12285. 0);
  12286. // Send 10MB of data
  12287. std::string chunk(64 * 1024, 'A');
  12288. size_t total_sent = 0;
  12289. while (total_sent < MALICIOUS_DATA_SIZE) {
  12290. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12291. auto sent = ::send(cli,
  12292. #ifdef _WIN32
  12293. static_cast<const char *>(chunk.c_str()),
  12294. static_cast<int>(to_send),
  12295. #else
  12296. chunk.c_str(), to_send,
  12297. #endif
  12298. 0);
  12299. if (sent <= 0) break;
  12300. total_sent += static_cast<size_t>(sent);
  12301. }
  12302. detail::close_socket(cli);
  12303. }
  12304. detail::close_socket(srv);
  12305. });
  12306. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12307. size_t total_read = 0;
  12308. {
  12309. Client cli("127.0.0.1", PORT + 2);
  12310. cli.set_read_timeout(5, 0);
  12311. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12312. auto stream = cli.open_stream("GET", "/malicious");
  12313. ASSERT_TRUE(stream.is_valid());
  12314. char buffer[64 * 1024];
  12315. ssize_t n;
  12316. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12317. total_read += static_cast<size_t>(n);
  12318. }
  12319. } // StreamHandle and Client destroyed here, closing the socket
  12320. server_thread.join();
  12321. // With set_payload_max_length, the client must stop reading before consuming
  12322. // all 10MB. The read loop should be cut off at or near the configured limit.
  12323. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12324. << "Client read " << total_read << " bytes, exceeding the configured "
  12325. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12326. }
  12327. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12328. // the entire response body without truncation.
  12329. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12330. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12331. #ifndef _WIN32
  12332. signal(SIGPIPE, SIG_IGN);
  12333. #endif
  12334. auto server_thread = std::thread([] {
  12335. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12336. default_socket_options(srv);
  12337. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12338. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12339. sockaddr_in addr{};
  12340. addr.sin_family = AF_INET;
  12341. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12342. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12343. int opt = 1;
  12344. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12345. #ifdef _WIN32
  12346. reinterpret_cast<const char *>(&opt),
  12347. #else
  12348. &opt,
  12349. #endif
  12350. sizeof(opt));
  12351. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12352. ::listen(srv, 1);
  12353. sockaddr_in cli_addr{};
  12354. socklen_t cli_len = sizeof(cli_addr);
  12355. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12356. if (cli != INVALID_SOCKET) {
  12357. char buf[4096];
  12358. ::recv(cli, buf, sizeof(buf), 0);
  12359. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12360. "Connection: close\r\n"
  12361. "\r\n";
  12362. ::send(cli,
  12363. #ifdef _WIN32
  12364. static_cast<const char *>(response_header.c_str()),
  12365. static_cast<int>(response_header.size()),
  12366. #else
  12367. response_header.c_str(), response_header.size(),
  12368. #endif
  12369. 0);
  12370. std::string chunk(64 * 1024, 'A');
  12371. size_t total_sent = 0;
  12372. while (total_sent < DATA_SIZE) {
  12373. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12374. auto sent = ::send(cli,
  12375. #ifdef _WIN32
  12376. static_cast<const char *>(chunk.c_str()),
  12377. static_cast<int>(to_send),
  12378. #else
  12379. chunk.c_str(), to_send,
  12380. #endif
  12381. 0);
  12382. if (sent <= 0) break;
  12383. total_sent += static_cast<size_t>(sent);
  12384. }
  12385. #ifdef _WIN32
  12386. ::shutdown(cli, SD_SEND);
  12387. #else
  12388. ::shutdown(cli, SHUT_WR);
  12389. #endif
  12390. // Drain until the client closes its end, ensuring all data is delivered
  12391. char drain[1024];
  12392. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12393. detail::close_socket(cli);
  12394. }
  12395. detail::close_socket(srv);
  12396. });
  12397. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12398. size_t total_read = 0;
  12399. {
  12400. Client cli("127.0.0.1", PORT + 2);
  12401. cli.set_read_timeout(5, 0);
  12402. cli.set_payload_max_length(0); // 0 means no limit
  12403. auto stream = cli.open_stream("GET", "/data");
  12404. ASSERT_TRUE(stream.is_valid());
  12405. char buffer[64 * 1024];
  12406. ssize_t n;
  12407. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12408. total_read += static_cast<size_t>(n);
  12409. }
  12410. }
  12411. server_thread.join();
  12412. EXPECT_EQ(total_read, DATA_SIZE)
  12413. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12414. << " bytes without truncation, but only read " << total_read << " bytes.";
  12415. }
  12416. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12417. // enormous Content-Length must not cause the client to pre-allocate a huge
  12418. // response body buffer. The reservation is capped at payload_max_length_, and
  12419. // the read itself fails when the body exceeds the limit.
  12420. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12421. #ifndef _WIN32
  12422. signal(SIGPIPE, SIG_IGN);
  12423. #endif
  12424. auto server_thread = std::thread([] {
  12425. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12426. default_socket_options(srv);
  12427. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12428. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12429. sockaddr_in addr{};
  12430. addr.sin_family = AF_INET;
  12431. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12432. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12433. int opt = 1;
  12434. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12435. #ifdef _WIN32
  12436. reinterpret_cast<const char *>(&opt),
  12437. #else
  12438. &opt,
  12439. #endif
  12440. sizeof(opt));
  12441. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12442. ::listen(srv, 1);
  12443. sockaddr_in cli_addr{};
  12444. socklen_t cli_len = sizeof(cli_addr);
  12445. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12446. if (cli != INVALID_SOCKET) {
  12447. char buf[4096];
  12448. ::recv(cli, buf, sizeof(buf), 0);
  12449. // Malicious response: claim a 20GB body but send only a tiny payload.
  12450. std::string response = "HTTP/1.1 200 OK\r\n"
  12451. "Content-Length: 20000000000\r\n"
  12452. "\r\n"
  12453. "abc";
  12454. ::send(cli,
  12455. #ifdef _WIN32
  12456. static_cast<const char *>(response.c_str()),
  12457. static_cast<int>(response.size()),
  12458. #else
  12459. response.c_str(), response.size(),
  12460. #endif
  12461. 0);
  12462. detail::close_socket(cli);
  12463. }
  12464. detail::close_socket(srv);
  12465. });
  12466. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12467. {
  12468. Client cli("127.0.0.1", PORT + 2);
  12469. cli.set_read_timeout(5, 0);
  12470. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12471. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12472. // (server claims more bytes than payload_max_length permits), but it must
  12473. // not exhaust memory before getting there.
  12474. auto res = cli.Get("/malicious");
  12475. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12476. }
  12477. server_thread.join();
  12478. }
  12479. // Verify that content_receiver bypasses the default payload_max_length,
  12480. // allowing streaming downloads larger than 100MB without requiring an explicit
  12481. // set_payload_max_length call.
  12482. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12483. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12484. #ifndef _WIN32
  12485. signal(SIGPIPE, SIG_IGN);
  12486. #endif
  12487. auto server_thread = std::thread([] {
  12488. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12489. default_socket_options(srv);
  12490. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12491. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12492. sockaddr_in addr{};
  12493. addr.sin_family = AF_INET;
  12494. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12495. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12496. int opt = 1;
  12497. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12498. #ifdef _WIN32
  12499. reinterpret_cast<const char *>(&opt),
  12500. #else
  12501. &opt,
  12502. #endif
  12503. sizeof(opt));
  12504. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12505. ::listen(srv, 1);
  12506. sockaddr_in cli_addr{};
  12507. socklen_t cli_len = sizeof(cli_addr);
  12508. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12509. if (cli != INVALID_SOCKET) {
  12510. char buf[4096];
  12511. ::recv(cli, buf, sizeof(buf), 0);
  12512. // Response with Content-Length larger than default 100MB limit
  12513. auto content_length = std::to_string(DATA_SIZE);
  12514. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12515. "Content-Length: " +
  12516. content_length +
  12517. "\r\n"
  12518. "Connection: close\r\n"
  12519. "\r\n";
  12520. ::send(cli,
  12521. #ifdef _WIN32
  12522. static_cast<const char *>(response_header.c_str()),
  12523. static_cast<int>(response_header.size()),
  12524. #else
  12525. response_header.c_str(), response_header.size(),
  12526. #endif
  12527. 0);
  12528. std::string chunk(64 * 1024, 'A');
  12529. size_t total_sent = 0;
  12530. while (total_sent < DATA_SIZE) {
  12531. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12532. auto sent = ::send(cli,
  12533. #ifdef _WIN32
  12534. static_cast<const char *>(chunk.c_str()),
  12535. static_cast<int>(to_send),
  12536. #else
  12537. chunk.c_str(), to_send,
  12538. #endif
  12539. 0);
  12540. if (sent <= 0) break;
  12541. total_sent += static_cast<size_t>(sent);
  12542. }
  12543. detail::close_socket(cli);
  12544. }
  12545. detail::close_socket(srv);
  12546. });
  12547. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12548. size_t total_received = 0;
  12549. {
  12550. Client cli("127.0.0.1", PORT + 2);
  12551. cli.set_read_timeout(10, 0);
  12552. // Do NOT call set_payload_max_length — use the default 100MB limit
  12553. auto res =
  12554. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12555. total_received += data_length;
  12556. return true;
  12557. });
  12558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12559. EXPECT_EQ(StatusCode::OK_200, res->status);
  12560. }
  12561. server_thread.join();
  12562. EXPECT_EQ(total_received, DATA_SIZE)
  12563. << "With content_receiver, the client should read all " << DATA_SIZE
  12564. << " bytes despite the default 100MB payload_max_length, but only read "
  12565. << total_received << " bytes.";
  12566. }
  12567. // Verify that an explicit set_payload_max_length smaller than the response is
  12568. // enforced even when a content_receiver is used.
  12569. TEST(ClientVulnerabilityTest,
  12570. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12571. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12572. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12573. #ifndef _WIN32
  12574. signal(SIGPIPE, SIG_IGN);
  12575. #endif
  12576. auto server_thread = std::thread([] {
  12577. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12578. default_socket_options(srv);
  12579. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12580. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12581. sockaddr_in addr{};
  12582. addr.sin_family = AF_INET;
  12583. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12584. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12585. int opt = 1;
  12586. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12587. #ifdef _WIN32
  12588. reinterpret_cast<const char *>(&opt),
  12589. #else
  12590. &opt,
  12591. #endif
  12592. sizeof(opt));
  12593. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12594. ::listen(srv, 1);
  12595. sockaddr_in cli_addr{};
  12596. socklen_t cli_len = sizeof(cli_addr);
  12597. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12598. if (cli != INVALID_SOCKET) {
  12599. char buf[4096];
  12600. ::recv(cli, buf, sizeof(buf), 0);
  12601. auto content_length = std::to_string(DATA_SIZE);
  12602. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12603. "Content-Length: " +
  12604. content_length +
  12605. "\r\n"
  12606. "Connection: close\r\n"
  12607. "\r\n";
  12608. ::send(cli,
  12609. #ifdef _WIN32
  12610. static_cast<const char *>(response_header.c_str()),
  12611. static_cast<int>(response_header.size()),
  12612. #else
  12613. response_header.c_str(), response_header.size(),
  12614. #endif
  12615. 0);
  12616. std::string chunk(64 * 1024, 'A');
  12617. size_t total_sent = 0;
  12618. while (total_sent < DATA_SIZE) {
  12619. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12620. auto sent = ::send(cli,
  12621. #ifdef _WIN32
  12622. static_cast<const char *>(chunk.c_str()),
  12623. static_cast<int>(to_send),
  12624. #else
  12625. chunk.c_str(), to_send,
  12626. #endif
  12627. 0);
  12628. if (sent <= 0) break;
  12629. total_sent += static_cast<size_t>(sent);
  12630. }
  12631. detail::close_socket(cli);
  12632. }
  12633. detail::close_socket(srv);
  12634. });
  12635. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12636. size_t total_received = 0;
  12637. {
  12638. Client cli("127.0.0.1", PORT + 2);
  12639. cli.set_read_timeout(10, 0);
  12640. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12641. auto res =
  12642. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12643. total_received += data_length;
  12644. return true;
  12645. });
  12646. // Should fail because 200MB exceeds the explicit 150MB limit
  12647. EXPECT_FALSE(res);
  12648. }
  12649. server_thread.join();
  12650. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12651. << "Client with content_receiver should respect the explicit "
  12652. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12653. << total_received << " bytes.";
  12654. }
  12655. // Verify that an explicit set_payload_max_length larger than the response
  12656. // allows the content_receiver to read all data successfully.
  12657. TEST(ClientVulnerabilityTest,
  12658. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12659. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12660. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12661. #ifndef _WIN32
  12662. signal(SIGPIPE, SIG_IGN);
  12663. #endif
  12664. auto server_thread = std::thread([] {
  12665. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12666. default_socket_options(srv);
  12667. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12668. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12669. sockaddr_in addr{};
  12670. addr.sin_family = AF_INET;
  12671. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12672. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12673. int opt = 1;
  12674. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12675. #ifdef _WIN32
  12676. reinterpret_cast<const char *>(&opt),
  12677. #else
  12678. &opt,
  12679. #endif
  12680. sizeof(opt));
  12681. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12682. ::listen(srv, 1);
  12683. sockaddr_in cli_addr{};
  12684. socklen_t cli_len = sizeof(cli_addr);
  12685. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12686. if (cli != INVALID_SOCKET) {
  12687. char buf[4096];
  12688. ::recv(cli, buf, sizeof(buf), 0);
  12689. auto content_length = std::to_string(DATA_SIZE);
  12690. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12691. "Content-Length: " +
  12692. content_length +
  12693. "\r\n"
  12694. "Connection: close\r\n"
  12695. "\r\n";
  12696. ::send(cli,
  12697. #ifdef _WIN32
  12698. static_cast<const char *>(response_header.c_str()),
  12699. static_cast<int>(response_header.size()),
  12700. #else
  12701. response_header.c_str(), response_header.size(),
  12702. #endif
  12703. 0);
  12704. std::string chunk(64 * 1024, 'A');
  12705. size_t total_sent = 0;
  12706. while (total_sent < DATA_SIZE) {
  12707. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12708. auto sent = ::send(cli,
  12709. #ifdef _WIN32
  12710. static_cast<const char *>(chunk.c_str()),
  12711. static_cast<int>(to_send),
  12712. #else
  12713. chunk.c_str(), to_send,
  12714. #endif
  12715. 0);
  12716. if (sent <= 0) break;
  12717. total_sent += static_cast<size_t>(sent);
  12718. }
  12719. #ifdef _WIN32
  12720. ::shutdown(cli, SD_SEND);
  12721. #else
  12722. ::shutdown(cli, SHUT_WR);
  12723. #endif
  12724. char drain[1024];
  12725. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12726. detail::close_socket(cli);
  12727. }
  12728. detail::close_socket(srv);
  12729. });
  12730. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12731. size_t total_received = 0;
  12732. {
  12733. Client cli("127.0.0.1", PORT + 2);
  12734. cli.set_read_timeout(10, 0);
  12735. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12736. auto res =
  12737. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12738. total_received += data_length;
  12739. return true;
  12740. });
  12741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12742. EXPECT_EQ(StatusCode::OK_200, res->status);
  12743. }
  12744. server_thread.join();
  12745. EXPECT_EQ(total_received, DATA_SIZE)
  12746. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12747. << " bytes (larger than " << DATA_SIZE
  12748. << " bytes response), content_receiver should read all data, but only "
  12749. "read "
  12750. << total_received << " bytes.";
  12751. }
  12752. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12753. // Regression test for "zip bomb" attack on the client side: a malicious server
  12754. // sends a small gzip-compressed response that decompresses to a huge payload.
  12755. // The client must enforce payload_max_length on the decompressed size.
  12756. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12757. constexpr size_t DECOMPRESSED_SIZE =
  12758. 10 * 1024 * 1024; // 10MB after decompression
  12759. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12760. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12761. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12762. std::string compressed;
  12763. {
  12764. httplib::detail::gzip_compressor compressor;
  12765. bool ok =
  12766. compressor.compress(uncompressed.data(), uncompressed.size(),
  12767. /*last=*/true, [&](const char *buf, size_t len) {
  12768. compressed.append(buf, len);
  12769. return true;
  12770. });
  12771. ASSERT_TRUE(ok);
  12772. }
  12773. // Sanity: compressed data should be much smaller than the decompressed size
  12774. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12775. #ifndef _WIN32
  12776. signal(SIGPIPE, SIG_IGN);
  12777. #endif
  12778. // Set up the listening socket in the main thread so the server is guaranteed
  12779. // to be ready before the client connects (eliminates race condition).
  12780. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12781. default_socket_options(srv);
  12782. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12783. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12784. sockaddr_in addr{};
  12785. addr.sin_family = AF_INET;
  12786. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12787. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12788. int opt = 1;
  12789. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12790. #ifdef _WIN32
  12791. reinterpret_cast<const char *>(&opt),
  12792. #else
  12793. &opt,
  12794. #endif
  12795. sizeof(opt));
  12796. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12797. ASSERT_EQ(0, ::listen(srv, 1));
  12798. auto server_thread = std::thread([&compressed, srv] {
  12799. sockaddr_in cli_addr{};
  12800. socklen_t cli_len = sizeof(cli_addr);
  12801. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12802. if (cli != INVALID_SOCKET) {
  12803. // Read the full HTTP request (until \r\n\r\n)
  12804. char buf[4096];
  12805. size_t total = 0;
  12806. while (total < sizeof(buf)) {
  12807. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12808. if (n <= 0) break;
  12809. total += static_cast<size_t>(n);
  12810. // Check for end of headers
  12811. if (total >= 4) {
  12812. std::string req(buf, total);
  12813. if (req.find("\r\n\r\n") != std::string::npos) break;
  12814. }
  12815. }
  12816. // Malicious response: gzip-compressed body, no Content-Length
  12817. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12818. "Content-Encoding: gzip\r\n"
  12819. "Connection: close\r\n"
  12820. "\r\n";
  12821. ::send(cli,
  12822. #ifdef _WIN32
  12823. static_cast<const char *>(response_header.c_str()),
  12824. static_cast<int>(response_header.size()),
  12825. #else
  12826. response_header.c_str(), response_header.size(),
  12827. #endif
  12828. 0);
  12829. // Send the compressed payload (small on the wire, huge when decompressed)
  12830. size_t total_sent = 0;
  12831. while (total_sent < compressed.size()) {
  12832. auto to_send = std::min(compressed.size() - total_sent,
  12833. static_cast<size_t>(64 * 1024));
  12834. auto sent =
  12835. ::send(cli,
  12836. #ifdef _WIN32
  12837. static_cast<const char *>(compressed.c_str() + total_sent),
  12838. static_cast<int>(to_send),
  12839. #else
  12840. compressed.c_str() + total_sent, to_send,
  12841. #endif
  12842. 0);
  12843. if (sent <= 0) break;
  12844. total_sent += static_cast<size_t>(sent);
  12845. }
  12846. detail::close_socket(cli);
  12847. }
  12848. });
  12849. auto se = detail::scope_exit([&] {
  12850. detail::close_socket(srv);
  12851. server_thread.join();
  12852. });
  12853. size_t total_decompressed = 0;
  12854. {
  12855. Client cli("127.0.0.1", PORT + 3);
  12856. cli.set_read_timeout(5, 0);
  12857. cli.set_decompress(true);
  12858. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12859. auto stream = cli.open_stream("GET", "/zipbomb");
  12860. ASSERT_TRUE(stream.is_valid());
  12861. char buffer[64 * 1024];
  12862. ssize_t n;
  12863. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12864. total_decompressed += static_cast<size_t>(n);
  12865. }
  12866. }
  12867. // The decompressed size must be capped by payload_max_length. Without
  12868. // protection, the client would decompress the full 10MB from a tiny
  12869. // compressed payload, enabling a zip bomb DoS attack.
  12870. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12871. << "Client decompressed " << total_decompressed
  12872. << " bytes from a gzip response. The decompressed size should be "
  12873. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12874. }
  12875. #endif
  12876. TEST(HostAndPortPropertiesTest, NoSSL) {
  12877. httplib::Client cli("www.google.com", 1234);
  12878. ASSERT_EQ("www.google.com", cli.host());
  12879. ASSERT_EQ(1234, cli.port());
  12880. }
  12881. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12882. httplib::Client cli("www.google.com:1234");
  12883. ASSERT_EQ("www.google.com", cli.host());
  12884. ASSERT_EQ(1234, cli.port());
  12885. }
  12886. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12887. // Port number that overflows int — should not crash, client becomes invalid
  12888. httplib::Client cli("http://www.google.com:99999999999999999999");
  12889. ASSERT_FALSE(cli.is_valid());
  12890. }
  12891. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12892. // Port 99999 exceeds valid range (1-65535) — should not crash
  12893. httplib::Client cli("http://www.google.com:99999");
  12894. ASSERT_FALSE(cli.is_valid());
  12895. auto res = cli.Get("/");
  12896. EXPECT_FALSE(res);
  12897. EXPECT_EQ(Error::Connection, res.error());
  12898. }
  12899. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  12900. httplib::Client cli("http://user:pass@localhost:1234");
  12901. ASSERT_FALSE(cli.is_valid());
  12902. EXPECT_FALSE(cli.Get("/"));
  12903. }
  12904. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12905. httplib::Client cli("http://www.google.com:80abc");
  12906. ASSERT_FALSE(cli.is_valid());
  12907. }
  12908. #ifdef CPPHTTPLIB_SSL_ENABLED
  12909. TEST(HostAndPortPropertiesTest, SSL) {
  12910. httplib::SSLClient cli("www.google.com");
  12911. ASSERT_EQ("www.google.com", cli.host());
  12912. ASSERT_EQ(443, cli.port());
  12913. }
  12914. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12915. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12916. std::string cert;
  12917. read_file(CA_CERT_FILE, cert);
  12918. httplib::SSLClient httplib_client("www.google.com");
  12919. // Load CA store first time
  12920. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12921. // Load CA store second time (update)
  12922. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12923. // Verify client is still valid and can make connections
  12924. httplib_client.enable_server_certificate_verification(true);
  12925. auto res = httplib_client.Get("/");
  12926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12927. // Google may return 200 or 301 depending on various factors
  12928. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12929. res->status == StatusCode::MovedPermanently_301);
  12930. }
  12931. TEST(SSLClientTest, ServerNameIndication_Online) {
  12932. auto host = "httpbingo.org";
  12933. auto path = std::string{"/get"};
  12934. SSLClient cli(host, 443);
  12935. auto res = cli.Get(path);
  12936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12937. ASSERT_EQ(StatusCode::OK_200, res->status);
  12938. }
  12939. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12940. // Use a site that will cause SSL verification failure due to self-signed cert
  12941. SSLClient cli("self-signed.badssl.com", 443);
  12942. cli.enable_server_certificate_verification(true);
  12943. auto res = cli.Get("/");
  12944. ASSERT_TRUE(!res);
  12945. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12946. // Verify backend error is captured for SSLServerVerification
  12947. // This occurs when certificate verification fails
  12948. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12949. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12950. EXPECT_NE(0UL, res.ssl_backend_error());
  12951. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12952. // For OpenSSL, ssl_error is 0 for verification errors
  12953. EXPECT_EQ(0, res.ssl_error());
  12954. #if !defined(_WIN32) || \
  12955. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12956. // On non-Windows or when Windows Schannel is disabled, the error comes
  12957. // from OpenSSL's verification
  12958. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12959. res.ssl_backend_error());
  12960. #endif
  12961. #endif
  12962. }
  12963. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12964. // Use a site where hostname doesn't match the certificate
  12965. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12966. SSLClient cli("wrong.host.badssl.com", 443);
  12967. cli.enable_server_certificate_verification(true);
  12968. cli.enable_server_hostname_verification(true);
  12969. auto res = cli.Get("/");
  12970. ASSERT_TRUE(!res);
  12971. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12972. // Verify backend error is captured for hostname verification failure
  12973. EXPECT_NE(0UL, res.ssl_backend_error());
  12974. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12975. // For OpenSSL, ssl_error is 0 for verification errors
  12976. EXPECT_EQ(0, res.ssl_error());
  12977. #if !defined(_WIN32) || \
  12978. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12979. // On non-Windows or when Windows Schannel is disabled, the error comes
  12980. // from OpenSSL's hostname verification
  12981. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12982. res.ssl_backend_error());
  12983. #endif
  12984. #endif
  12985. }
  12986. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12987. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12988. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12989. SSLClient cli("www.google.com", 443);
  12990. cli.enable_server_certificate_verification(true);
  12991. auto res = cli.Get("/");
  12992. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12993. }
  12994. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12995. SSLClient cli("www.google.com", 443);
  12996. cli.enable_server_certificate_verification(true);
  12997. cli.enable_windows_certificate_verification(false);
  12998. auto res = cli.Get("/");
  12999. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13000. }
  13001. // The server sends an intermediate cross-signed by a root Windows trusts,
  13002. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13003. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13004. SSLClient cli("accounts.spotify.com", 443);
  13005. auto res = cli.Get("/");
  13006. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13007. << " ssl_backend_error=" << res.ssl_backend_error();
  13008. }
  13009. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13010. // policy status, which no backend reports for a self-signed certificate.
  13011. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13012. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13013. ASSERT_TRUE(svr.is_valid());
  13014. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13015. auto se = detail::scope_exit([&] {
  13016. svr.stop();
  13017. t.join();
  13018. ASSERT_FALSE(svr.is_running());
  13019. });
  13020. svr.wait_until_ready();
  13021. SSLClient cli("127.0.0.1", PORT);
  13022. cli.set_connection_timeout(30);
  13023. auto res = cli.Get("/");
  13024. ASSERT_FALSE(res);
  13025. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13026. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13027. }
  13028. #endif
  13029. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13030. Client cli("https://google.com");
  13031. auto res = cli.Get("/");
  13032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13033. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13034. }
  13035. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13036. SSLClient cli("google.com");
  13037. cli.set_ca_cert_path(CA_CERT_FILE);
  13038. auto res = cli.Get("/");
  13039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13040. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13041. }
  13042. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13043. SSLClient cli("google.com");
  13044. cli.enable_server_certificate_verification(true);
  13045. cli.set_ca_cert_path("hello");
  13046. auto res = cli.Get("/");
  13047. ASSERT_TRUE(!res);
  13048. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13049. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13050. // should be set
  13051. EXPECT_EQ(0, res.ssl_error());
  13052. // Verify backend error is captured for SSLLoadingCerts
  13053. // This error occurs when loading CA certificates fails
  13054. EXPECT_NE(0UL, res.ssl_backend_error());
  13055. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13056. // OpenSSL specific error codes:
  13057. // > openssl errstr 0x80000002
  13058. // error:80000002:system library::No such file or directory
  13059. // > openssl errstr 0xA000126
  13060. // error:0A000126:SSL routines::unexpected eof while reading
  13061. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13062. res.ssl_backend_error() == 0xA000126);
  13063. #endif
  13064. }
  13065. TEST(SSLClientTest, ServerCertificateVerification4) {
  13066. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13067. ASSERT_TRUE(svr.is_valid());
  13068. svr.Get("/test", [&](const Request &, Response &res) {
  13069. res.set_content("test", "text/plain");
  13070. svr.stop();
  13071. ASSERT_TRUE(true);
  13072. });
  13073. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13074. auto se = detail::scope_exit([&] {
  13075. t.join();
  13076. ASSERT_FALSE(svr.is_running());
  13077. });
  13078. svr.wait_until_ready();
  13079. SSLClient cli("127.0.0.1", PORT);
  13080. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13081. cli.enable_server_certificate_verification(true);
  13082. cli.set_connection_timeout(30);
  13083. auto res = cli.Get("/test");
  13084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13085. ASSERT_EQ(StatusCode::OK_200, res->status);
  13086. }
  13087. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13088. std::string cert;
  13089. read_file(CA_CERT_FILE, cert);
  13090. SSLClient cli("google.com");
  13091. cli.load_ca_cert_store(cert.data(), cert.size());
  13092. const auto res = cli.Get("/");
  13093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13094. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13095. }
  13096. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13097. // clang-format off
  13098. static constexpr char cert[] =
  13099. "GlobalSign Root CA\n"
  13100. "==================\n"
  13101. "-----BEGIN CERTIFICATE-----\n"
  13102. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13103. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13104. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13105. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13106. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13107. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13108. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13109. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13110. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13111. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13112. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13113. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13114. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13115. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13116. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13117. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13118. "-----END CERTIFICATE-----\n";
  13119. // clang-format on
  13120. SSLClient cli("google.com");
  13121. cli.load_ca_cert_store(cert, sizeof(cert));
  13122. const auto res = cli.Get("/");
  13123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13124. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13125. }
  13126. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13127. SSLClient cli("www.youtube.com");
  13128. cli.set_ca_cert_path(CA_CERT_FILE);
  13129. cli.enable_server_certificate_verification(true);
  13130. cli.set_follow_location(true);
  13131. auto res = cli.Get("/");
  13132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13133. ASSERT_EQ(StatusCode::OK_200, res->status);
  13134. }
  13135. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13136. SSLClient cli("wWw.YouTube.Com");
  13137. cli.set_ca_cert_path(CA_CERT_FILE);
  13138. cli.enable_server_certificate_verification(true);
  13139. cli.enable_server_hostname_verification(true);
  13140. cli.set_follow_location(true);
  13141. auto res = cli.Get("/");
  13142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13143. ASSERT_EQ(StatusCode::OK_200, res->status);
  13144. }
  13145. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13146. SSLClient cli("gOoGlE.COm");
  13147. cli.enable_server_certificate_verification(true);
  13148. cli.enable_server_hostname_verification(true);
  13149. cli.set_follow_location(true);
  13150. auto res = cli.Get("/");
  13151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13152. ASSERT_EQ(StatusCode::OK_200, res->status);
  13153. }
  13154. TEST(SSLClientTest, Issue2004_Online) {
  13155. Client client("https://google.com");
  13156. client.set_follow_location(true);
  13157. auto res = client.Get("/");
  13158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13159. ASSERT_EQ(StatusCode::OK_200, res->status);
  13160. auto body = res->body;
  13161. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13162. }
  13163. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13164. // Create SSLClient with invalid cert/key to make is_valid() return false
  13165. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13166. "nonexistent_key.pem");
  13167. // is_valid() should be false due to cert loading failure
  13168. ASSERT_FALSE(cli.is_valid());
  13169. auto res = cli.Get("/");
  13170. ASSERT_FALSE(res);
  13171. EXPECT_EQ(Error::SSLConnection, res.error());
  13172. }
  13173. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13174. // Test for Issue #2251: SSL error not properly reported when client cert
  13175. // and key paths are swapped or mismatched
  13176. // This simulates the scenario where user accidentally swaps the cert and key
  13177. // files
  13178. // Using client cert file as private key and vice versa (completely wrong)
  13179. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13180. // Should fail validation due to cert/key mismatch
  13181. ASSERT_FALSE(cli.is_valid());
  13182. // Attempt to make a request should fail with proper error
  13183. auto res = cli.Get("/");
  13184. ASSERT_FALSE(res);
  13185. EXPECT_EQ(Error::SSLConnection, res.error());
  13186. // SSL error should be recorded in the Result object (this is the key fix for
  13187. // Issue #2251)
  13188. auto backend_error = res.ssl_backend_error();
  13189. EXPECT_NE(0u, backend_error);
  13190. }
  13191. // Tests cert/key mismatch detection at the TLS context level
  13192. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13193. // Test that using mismatched cert/key causes connection failure.
  13194. // We verify this at the SSLClient level rather than through internal
  13195. // TLS API functions.
  13196. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13197. cli.enable_server_certificate_verification(false);
  13198. cli.set_connection_timeout(2);
  13199. // The mismatch should cause a connection or handshake error
  13200. auto res = cli.Get("/test");
  13201. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13202. // Either way, the request should fail
  13203. EXPECT_FALSE(res);
  13204. }
  13205. #endif
  13206. #if 0
  13207. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13208. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13209. ASSERT_TRUE(cli != nullptr);
  13210. cli->set_address_family(AF_INET6);
  13211. cli->set_interface("en0");
  13212. auto res = cli->Get("/get");
  13213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13214. ASSERT_EQ(StatusCode::OK_200, res->status);
  13215. }
  13216. #endif
  13217. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  13218. #ifdef CPPHTTPLIB_SSL_ENABLED
  13219. void ClientCertPresent(
  13220. const std::string &client_cert_file,
  13221. const std::string &client_private_key_file,
  13222. const std::string &client_encrypted_private_key_pass = std::string()) {
  13223. using namespace httplib::tls;
  13224. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13225. CLIENT_CA_CERT_DIR);
  13226. ASSERT_TRUE(svr.is_valid());
  13227. svr.Get("/test", [&](const Request &req, Response &res) {
  13228. res.set_content("test", "text/plain");
  13229. auto cert = req.peer_cert();
  13230. ASSERT_TRUE(static_cast<bool>(cert));
  13231. std::string common_name = cert.subject_cn();
  13232. EXPECT_EQ("Common Name", common_name);
  13233. });
  13234. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13235. auto se = detail::scope_exit([&] {
  13236. svr.stop();
  13237. t.join();
  13238. ASSERT_FALSE(svr.is_running());
  13239. });
  13240. svr.wait_until_ready();
  13241. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13242. client_encrypted_private_key_pass);
  13243. cli.enable_server_certificate_verification(false);
  13244. cli.set_connection_timeout(30);
  13245. auto res = cli.Get("/test");
  13246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13247. ASSERT_EQ(StatusCode::OK_200, res->status);
  13248. }
  13249. TEST(SSLClientServerTest, ClientCertPresent) {
  13250. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13251. }
  13252. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13253. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13254. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13255. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13256. }
  13257. // PEM memory-based constructor tests (works with all TLS backends)
  13258. void PemMemoryClientCertPresent(
  13259. const std::string &client_cert_file,
  13260. const std::string &client_private_key_file,
  13261. const std::string &client_encrypted_private_key_pass = std::string()) {
  13262. // Read PEM files into memory
  13263. std::string server_cert_pem, server_key_pem;
  13264. std::string client_ca_pem;
  13265. std::string client_cert_pem, client_key_pem;
  13266. read_file(SERVER_CERT_FILE, server_cert_pem);
  13267. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13268. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13269. read_file(client_cert_file, client_cert_pem);
  13270. read_file(client_private_key_file, client_key_pem);
  13271. // Create server with PEM memory
  13272. SSLServer::PemMemory server_pem = {
  13273. server_cert_pem.c_str(),
  13274. server_cert_pem.size(),
  13275. server_key_pem.c_str(),
  13276. server_key_pem.size(),
  13277. client_ca_pem.c_str(),
  13278. client_ca_pem.size(),
  13279. nullptr // no password for server key
  13280. };
  13281. SSLServer svr(server_pem);
  13282. ASSERT_TRUE(svr.is_valid());
  13283. svr.Get("/test", [&](const Request &, Response &res) {
  13284. res.set_content("test", "text/plain");
  13285. });
  13286. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13287. auto se = detail::scope_exit([&] {
  13288. svr.stop();
  13289. t.join();
  13290. ASSERT_FALSE(svr.is_running());
  13291. });
  13292. svr.wait_until_ready();
  13293. // Create client with PEM memory
  13294. const char *password = client_encrypted_private_key_pass.empty()
  13295. ? nullptr
  13296. : client_encrypted_private_key_pass.c_str();
  13297. SSLClient::PemMemory client_pem = {
  13298. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13299. client_key_pem.size(), password};
  13300. SSLClient cli(HOST, PORT, client_pem);
  13301. cli.enable_server_certificate_verification(false);
  13302. cli.set_connection_timeout(30);
  13303. auto res = cli.Get("/test");
  13304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13305. ASSERT_EQ(StatusCode::OK_200, res->status);
  13306. }
  13307. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13308. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13309. }
  13310. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13311. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13312. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13313. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13314. }
  13315. TEST(SSLClientServerTest, ClientCertMissing) {
  13316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13317. CLIENT_CA_CERT_DIR);
  13318. ASSERT_TRUE(svr.is_valid());
  13319. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13320. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13321. auto se = detail::scope_exit([&] {
  13322. svr.stop();
  13323. t.join();
  13324. ASSERT_FALSE(svr.is_running());
  13325. });
  13326. svr.wait_until_ready();
  13327. SSLClient cli(HOST, PORT);
  13328. cli.set_connection_timeout(30);
  13329. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13330. // the chain check on Windows, so the result does not depend on the order.
  13331. cli.enable_server_hostname_verification(false);
  13332. auto res = cli.Get("/test");
  13333. ASSERT_TRUE(!res);
  13334. // When client cert is missing and server requires it, connection fails
  13335. // Error type depends on backend implementation
  13336. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13337. res.error() == Error::SSLConnection);
  13338. // Verify backend error is captured
  13339. // Note: This test may have different error codes depending on the exact
  13340. // verification failure
  13341. EXPECT_NE(0UL, res.ssl_backend_error());
  13342. }
  13343. TEST(SSLClientServerTest, TrustDirOptional) {
  13344. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13345. ASSERT_TRUE(svr.is_valid());
  13346. svr.Get("/test", [&](const Request &, Response &res) {
  13347. res.set_content("test", "text/plain");
  13348. });
  13349. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13350. auto se = detail::scope_exit([&] {
  13351. svr.stop();
  13352. t.join();
  13353. ASSERT_FALSE(svr.is_running());
  13354. });
  13355. svr.wait_until_ready();
  13356. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  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, SSLConnectTimeout) {
  13364. class NoListenSSLServer : public SSLServer {
  13365. public:
  13366. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13367. const char *client_ca_cert_file_path,
  13368. const char *client_ca_cert_dir_path = nullptr)
  13369. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13370. client_ca_cert_dir_path),
  13371. stop_(false) {}
  13372. std::atomic_bool stop_;
  13373. private:
  13374. bool process_and_close_socket(socket_t /*sock*/) override {
  13375. // Don't create SSL context
  13376. while (!stop_.load()) {
  13377. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13378. }
  13379. return true;
  13380. }
  13381. };
  13382. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13383. CLIENT_CA_CERT_FILE);
  13384. ASSERT_TRUE(svr.is_valid());
  13385. svr.Get("/test", [&](const Request &, Response &res) {
  13386. res.set_content("test", "text/plain");
  13387. });
  13388. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13389. auto se = detail::scope_exit([&] {
  13390. svr.stop_ = true;
  13391. svr.stop();
  13392. t.join();
  13393. ASSERT_FALSE(svr.is_running());
  13394. });
  13395. svr.wait_until_ready();
  13396. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13397. cli.enable_server_certificate_verification(false);
  13398. cli.set_connection_timeout(1);
  13399. auto res = cli.Get("/test");
  13400. ASSERT_TRUE(!res);
  13401. EXPECT_EQ(Error::SSLConnection, res.error());
  13402. // Timeout results in WantRead error code (maps to backend-specific value)
  13403. EXPECT_NE(0, res.ssl_error());
  13404. }
  13405. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13406. // Test SSLServer with client certificate verification using the standard
  13407. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13409. CLIENT_CA_CERT_DIR);
  13410. ASSERT_TRUE(svr.is_valid());
  13411. svr.Get("/test", [&](const Request &req, Response &res) {
  13412. res.set_content("test", "text/plain");
  13413. auto cert = req.peer_cert();
  13414. ASSERT_TRUE(static_cast<bool>(cert));
  13415. auto common_name = cert.subject_cn();
  13416. EXPECT_EQ("Common Name", common_name);
  13417. });
  13418. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13419. auto se = detail::scope_exit([&] {
  13420. svr.stop();
  13421. t.join();
  13422. ASSERT_FALSE(svr.is_running());
  13423. });
  13424. svr.wait_until_ready();
  13425. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13426. cli.enable_server_certificate_verification(false);
  13427. cli.set_connection_timeout(30);
  13428. auto res = cli.Get("/test");
  13429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13430. ASSERT_EQ(StatusCode::OK_200, res->status);
  13431. }
  13432. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13433. // Verifies that wildcard matching and exact matching work consistently
  13434. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13435. using namespace httplib::tls;
  13436. // We need a running server to test against
  13437. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13438. ASSERT_TRUE(svr.is_valid());
  13439. svr.Get("/test", [](const Request &, Response &res) {
  13440. res.set_content("ok", "text/plain");
  13441. });
  13442. thread t([&]() { svr.listen(HOST, PORT); });
  13443. auto se = detail::scope_exit([&] {
  13444. svr.stop();
  13445. t.join();
  13446. });
  13447. svr.wait_until_ready();
  13448. bool verify_callback_called = false;
  13449. bool verify_result_wrong = false;
  13450. SSLClient cli(HOST, PORT);
  13451. cli.enable_server_certificate_verification(true);
  13452. cli.set_ca_cert_path(CA_CERT_FILE);
  13453. cli.set_connection_timeout(5);
  13454. // Note: Test certificate has CN="Common Name", not "localhost"
  13455. bool verify_result_cn = false;
  13456. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13457. verify_callback_called = true;
  13458. if (!ctx.cert) return false;
  13459. // Test 1: "Common Name" should match (our test server cert CN)
  13460. verify_result_cn = ctx.check_hostname("Common Name");
  13461. // Test 2: wrong hostname should not match
  13462. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13463. return true; // Accept for the purpose of this test
  13464. });
  13465. auto res = cli.Get("/test");
  13466. // The request may succeed or fail depending on cert configuration
  13467. // but the callback should have been called
  13468. ASSERT_TRUE(verify_callback_called)
  13469. << "Verify callback should have been called";
  13470. // CN="Common Name" should match our test certificate
  13471. //
  13472. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13473. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13474. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13475. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13476. // <openssl/base.h>, which is included transitively when
  13477. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13478. #if defined(OPENSSL_IS_BORINGSSL)
  13479. EXPECT_FALSE(verify_result_cn)
  13480. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13481. #else
  13482. EXPECT_TRUE(verify_result_cn)
  13483. << "verify_hostname should match 'Common Name' (certificate CN)";
  13484. #endif
  13485. // Wrong hostname should not match
  13486. EXPECT_FALSE(verify_result_wrong)
  13487. << "verify_hostname should not match 'wronghost.example.com'";
  13488. }
  13489. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13490. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13491. // X509_check_ip behavior and must hold for every backend.
  13492. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13493. using namespace httplib::tls;
  13494. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13495. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13496. ASSERT_TRUE(svr.is_valid());
  13497. svr.Get("/test", [](const Request &, Response &res) {
  13498. res.set_content("ok", "text/plain");
  13499. });
  13500. thread t([&]() { svr.listen(HOST, PORT); });
  13501. auto se = detail::scope_exit([&] {
  13502. svr.stop();
  13503. t.join();
  13504. });
  13505. svr.wait_until_ready();
  13506. bool verify_callback_called = false;
  13507. bool ip_matched_via_cn = true;
  13508. SSLClient cli(HOST, PORT);
  13509. cli.enable_server_certificate_verification(true);
  13510. cli.set_ca_cert_path(CA_CERT_FILE);
  13511. cli.set_connection_timeout(5);
  13512. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13513. verify_callback_called = true;
  13514. if (!ctx.cert) return false;
  13515. // The IP appears only in the CN, so it must NOT be accepted.
  13516. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13517. return true; // Accept for the purpose of this test
  13518. });
  13519. cli.Get("/test");
  13520. ASSERT_TRUE(verify_callback_called)
  13521. << "Verify callback should have been called";
  13522. EXPECT_FALSE(ip_matched_via_cn)
  13523. << "An IP host must not be authenticated via the certificate CN";
  13524. }
  13525. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13526. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13527. using namespace httplib::tls;
  13528. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13529. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13530. ASSERT_TRUE(svr.is_valid());
  13531. svr.Get("/test", [](const Request &, Response &res) {
  13532. res.set_content("ok", "text/plain");
  13533. });
  13534. thread t([&]() { svr.listen(HOST, PORT); });
  13535. auto se = detail::scope_exit([&] {
  13536. svr.stop();
  13537. t.join();
  13538. });
  13539. svr.wait_until_ready();
  13540. bool verify_callback_called = false;
  13541. bool san_matched = false;
  13542. bool wrong_ipv6_matched = true;
  13543. bool cn_ipv6_matched = true;
  13544. SSLClient cli(HOST, PORT);
  13545. cli.enable_server_certificate_verification(true);
  13546. cli.set_ca_cert_path(CA_CERT_FILE);
  13547. cli.set_connection_timeout(5);
  13548. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13549. verify_callback_called = true;
  13550. if (!ctx.cert) return false;
  13551. // Matches the IPv6 iPAddress SAN.
  13552. san_matched = ctx.check_hostname("2001:db8::1");
  13553. // A different IPv6 address must not match.
  13554. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13555. // "::1" lives only in the CN, so it must not be accepted.
  13556. cn_ipv6_matched = ctx.check_hostname("::1");
  13557. return true; // Accept for the purpose of this test
  13558. });
  13559. cli.Get("/test");
  13560. ASSERT_TRUE(verify_callback_called)
  13561. << "Verify callback should have been called";
  13562. EXPECT_TRUE(san_matched)
  13563. << "verify_hostname should match an IPv6 iPAddress SAN";
  13564. EXPECT_FALSE(wrong_ipv6_matched)
  13565. << "verify_hostname should not match a non-matching IPv6 address";
  13566. EXPECT_FALSE(cn_ipv6_matched)
  13567. << "An IPv6 host must not be authenticated via the certificate CN";
  13568. }
  13569. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13570. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13571. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13572. using namespace httplib::tls;
  13573. // SANs: DNS:a.zz, IP:42.46.122.122
  13574. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13575. ASSERT_TRUE(svr.is_valid());
  13576. svr.Get("/test", [](const Request &, Response &res) {
  13577. res.set_content("ok", "text/plain");
  13578. });
  13579. auto port = svr.bind_to_any_port(HOST);
  13580. thread t([&]() { svr.listen_after_bind(); });
  13581. auto se = detail::scope_exit([&] {
  13582. svr.stop();
  13583. t.join();
  13584. });
  13585. svr.wait_until_ready();
  13586. bool verify_callback_called = false;
  13587. bool dns_san_matched = false;
  13588. bool ip_san_matched = false;
  13589. bool ip_matched_via_dns_san = true;
  13590. bool dns_matched_via_ip_san = true;
  13591. SSLClient cli(HOST, port);
  13592. cli.enable_server_certificate_verification(true);
  13593. cli.set_ca_cert_path(CA_CERT_FILE);
  13594. cli.set_connection_timeout(5);
  13595. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13596. verify_callback_called = true;
  13597. if (!ctx.cert) return false;
  13598. dns_san_matched = ctx.check_hostname("a.zz");
  13599. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13600. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13601. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13602. return true; // Accept for the purpose of this test
  13603. });
  13604. cli.Get("/test");
  13605. ASSERT_TRUE(verify_callback_called)
  13606. << "Verify callback should have been called";
  13607. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13608. EXPECT_TRUE(ip_san_matched)
  13609. << "verify_hostname should match an iPAddress SAN";
  13610. EXPECT_FALSE(ip_matched_via_dns_san)
  13611. << "An IP host must not be authenticated via a dNSName SAN";
  13612. EXPECT_FALSE(dns_matched_via_ip_san)
  13613. << "A DNS host must not be authenticated via an iPAddress SAN";
  13614. }
  13615. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13616. // "www.*.example.test" names one host and not every host under example.test.
  13617. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13618. using namespace httplib::tls;
  13619. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13620. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13621. ASSERT_TRUE(svr.is_valid());
  13622. svr.Get("/test", [](const Request &, Response &res) {
  13623. res.set_content("ok", "text/plain");
  13624. });
  13625. auto port = svr.bind_to_any_port(HOST);
  13626. thread t([&]() { svr.listen_after_bind(); });
  13627. auto se = detail::scope_exit([&] {
  13628. svr.stop();
  13629. t.join();
  13630. });
  13631. svr.wait_until_ready();
  13632. bool verify_callback_called = false;
  13633. bool leftmost_wildcard_matched = false;
  13634. bool wildcard_spanned_labels = true;
  13635. bool inner_wildcard_matched = true;
  13636. SSLClient cli(HOST, port);
  13637. cli.enable_server_certificate_verification(true);
  13638. cli.set_ca_cert_path(CA_CERT_FILE);
  13639. cli.set_connection_timeout(5);
  13640. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13641. verify_callback_called = true;
  13642. if (!ctx.cert) return false;
  13643. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13644. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13645. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13646. return true; // Accept for the purpose of this test
  13647. });
  13648. cli.Get("/test");
  13649. ASSERT_TRUE(verify_callback_called)
  13650. << "Verify callback should have been called";
  13651. EXPECT_TRUE(leftmost_wildcard_matched)
  13652. << "A leftmost wildcard should match a single label";
  13653. EXPECT_FALSE(wildcard_spanned_labels)
  13654. << "A wildcard label must not match more than one label";
  13655. EXPECT_FALSE(inner_wildcard_matched)
  13656. << "A wildcard outside the leftmost label must not be honoured";
  13657. }
  13658. // sans() must report each SAN entry under its own type.
  13659. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13660. using namespace httplib::tls;
  13661. // SANs: DNS:a.zz, IP:42.46.122.122
  13662. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13663. ASSERT_TRUE(svr.is_valid());
  13664. svr.Get("/test", [](const Request &, Response &res) {
  13665. res.set_content("ok", "text/plain");
  13666. });
  13667. auto port = svr.bind_to_any_port(HOST);
  13668. thread t([&]() { svr.listen_after_bind(); });
  13669. auto se = detail::scope_exit([&] {
  13670. svr.stop();
  13671. t.join();
  13672. });
  13673. svr.wait_until_ready();
  13674. bool verify_callback_called = false;
  13675. std::vector<SanEntry> sans;
  13676. SSLClient cli(HOST, port);
  13677. cli.enable_server_certificate_verification(true);
  13678. cli.set_ca_cert_path(CA_CERT_FILE);
  13679. cli.set_connection_timeout(5);
  13680. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13681. verify_callback_called = true;
  13682. if (!ctx.cert) return false;
  13683. sans = ctx.sans();
  13684. return true; // Accept for the purpose of this test
  13685. });
  13686. cli.Get("/test");
  13687. ASSERT_TRUE(verify_callback_called)
  13688. << "Verify callback should have been called";
  13689. auto has_san = [&](SanType type, const std::string &value) {
  13690. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13691. return san.type == type && san.value == value;
  13692. });
  13693. };
  13694. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13695. << "sans() should report the dNSName SAN";
  13696. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13697. << "sans() should report the iPAddress SAN";
  13698. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13699. << "sans() must not report the dNSName SAN as an address";
  13700. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13701. << "sans() must not report the iPAddress SAN as a DNS name";
  13702. }
  13703. #endif
  13704. // mbedTLS-specific callback constructor test
  13705. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13706. #ifdef CPPHTTPLIB_SSL_ENABLED
  13707. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13709. ASSERT_TRUE(svr.is_valid());
  13710. // Set up a handler to verify client certificate is present
  13711. bool client_cert_verified = false;
  13712. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13713. // Verify that client certificate was provided
  13714. client_cert_verified = true;
  13715. res.set_content("success", "text/plain");
  13716. });
  13717. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13718. auto se = detail::scope_exit([&] {
  13719. svr.stop();
  13720. t.join();
  13721. ASSERT_FALSE(svr.is_running());
  13722. });
  13723. svr.wait_until_ready();
  13724. // Client with certificate
  13725. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13726. cli.enable_server_certificate_verification(false);
  13727. cli.set_connection_timeout(30);
  13728. auto res = cli.Get("/test");
  13729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13730. ASSERT_EQ(StatusCode::OK_200, res->status);
  13731. ASSERT_TRUE(client_cert_verified);
  13732. EXPECT_EQ("success", res->body);
  13733. }
  13734. #endif
  13735. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13736. // backends
  13737. #ifdef CPPHTTPLIB_SSL_ENABLED
  13738. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13739. using namespace httplib::tls;
  13740. // Test that when client CA cert file is provided,
  13741. // the server properly requests and validates client certificates
  13742. // Create a server with client authentication
  13743. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13744. ASSERT_TRUE(svr.is_valid());
  13745. bool handler_called = false;
  13746. svr.Get("/test", [&](const Request &req, Response &res) {
  13747. handler_called = true;
  13748. // Verify that a client certificate was provided
  13749. auto cert = req.peer_cert();
  13750. ASSERT_TRUE(static_cast<bool>(cert));
  13751. // Get the issuer name
  13752. std::string issuer_str = cert.issuer_name();
  13753. ASSERT_FALSE(issuer_str.empty());
  13754. // The client certificate should be issued by our test CA
  13755. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13756. res.set_content("authenticated", "text/plain");
  13757. });
  13758. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13759. auto se = detail::scope_exit([&] {
  13760. svr.stop();
  13761. t.join();
  13762. ASSERT_FALSE(svr.is_running());
  13763. });
  13764. svr.wait_until_ready();
  13765. // Connect with a client certificate issued by the CA
  13766. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13767. cli.enable_server_certificate_verification(false);
  13768. cli.set_connection_timeout(30);
  13769. auto res = cli.Get("/test");
  13770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13771. ASSERT_EQ(StatusCode::OK_200, res->status);
  13772. ASSERT_TRUE(handler_called);
  13773. EXPECT_EQ("authenticated", res->body);
  13774. }
  13775. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13776. using namespace httplib::tls;
  13777. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13778. ASSERT_TRUE(svr.is_valid());
  13779. svr.Get("/test", [](const Request &, Response &res) {
  13780. res.set_content("ok", "text/plain");
  13781. });
  13782. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13783. auto se = detail::scope_exit([&] {
  13784. svr.stop();
  13785. t.join();
  13786. });
  13787. svr.wait_until_ready();
  13788. SSLClient cli(HOST, PORT);
  13789. cli.enable_server_certificate_verification(false);
  13790. cli.set_connection_timeout(30);
  13791. bool cert_checked = false;
  13792. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13793. if (ctx.cert) {
  13794. auto sans = ctx.sans();
  13795. // Test certificate may or may not have SANs - just verify the API
  13796. // works If SANs exist, verify the types are valid
  13797. for (const auto &san : sans) {
  13798. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13799. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13800. san.type == SanType::OTHER);
  13801. EXPECT_FALSE(san.value.empty());
  13802. }
  13803. cert_checked = true;
  13804. }
  13805. return true;
  13806. });
  13807. auto res = cli.Get("/test");
  13808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13809. EXPECT_TRUE(cert_checked);
  13810. }
  13811. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13812. using namespace httplib::tls;
  13813. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13814. ASSERT_TRUE(svr.is_valid());
  13815. svr.Get("/test", [](const Request &, Response &res) {
  13816. res.set_content("ok", "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. });
  13823. svr.wait_until_ready();
  13824. SSLClient cli(HOST, PORT);
  13825. cli.enable_server_certificate_verification(false);
  13826. cli.set_connection_timeout(30);
  13827. bool validity_checked = false;
  13828. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13829. if (ctx.cert) {
  13830. time_t not_before = 0, not_after = 0;
  13831. bool result = ctx.validity(not_before, not_after);
  13832. EXPECT_TRUE(result);
  13833. // Verify that not_before < now < not_after for a valid cert
  13834. time_t now = time(nullptr);
  13835. EXPECT_LT(not_before, now);
  13836. EXPECT_GT(not_after, now);
  13837. validity_checked = true;
  13838. }
  13839. return true;
  13840. });
  13841. auto res = cli.Get("/test");
  13842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13843. EXPECT_TRUE(validity_checked);
  13844. }
  13845. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13846. using namespace httplib::tls;
  13847. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13848. ASSERT_TRUE(svr.is_valid());
  13849. svr.Get("/test", [](const Request &, Response &res) {
  13850. res.set_content("ok", "text/plain");
  13851. });
  13852. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13853. auto se = detail::scope_exit([&] {
  13854. svr.stop();
  13855. t.join();
  13856. });
  13857. svr.wait_until_ready();
  13858. SSLClient cli(HOST, PORT);
  13859. cli.enable_server_certificate_verification(false);
  13860. cli.set_connection_timeout(30);
  13861. bool serial_checked = false;
  13862. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13863. if (ctx.cert) {
  13864. std::string serial = ctx.serial();
  13865. EXPECT_FALSE(serial.empty());
  13866. // Serial should be a hex string
  13867. for (char c : serial) {
  13868. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13869. (c >= 'a' && c <= 'f'));
  13870. }
  13871. serial_checked = true;
  13872. }
  13873. return true;
  13874. });
  13875. auto res = cli.Get("/test");
  13876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13877. EXPECT_TRUE(serial_checked);
  13878. }
  13879. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13880. // Test 1: Valid CA file - no error should be recorded
  13881. {
  13882. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13883. CLIENT_CA_CERT_FILE);
  13884. ASSERT_TRUE(svr.is_valid());
  13885. // With valid setup, last_ssl_error should be 0
  13886. EXPECT_EQ(0, svr.ssl_last_error());
  13887. }
  13888. // Test 2: Invalid CA file content
  13889. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13890. {
  13891. // Create a temporary file with completely invalid content
  13892. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13893. {
  13894. std::ofstream ofs(temp_invalid_ca);
  13895. ofs << "This is not a certificate file at all\n";
  13896. ofs << "Just plain text content\n";
  13897. }
  13898. // Create server with invalid CA file
  13899. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13900. // Clean up temporary file
  13901. std::remove(temp_invalid_ca);
  13902. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13903. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13904. // Note: SSL_CTX_load_verify_locations typically fails first,
  13905. // but our error handling code path is still exercised
  13906. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13907. }
  13908. }
  13909. TEST(VerifyCallbackTest, VerifyContextFields) {
  13910. using namespace httplib::tls;
  13911. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13912. ASSERT_TRUE(svr.is_valid());
  13913. svr.Get("/test", [](const Request &, Response &res) {
  13914. res.set_content("ok", "text/plain");
  13915. });
  13916. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13917. auto se = detail::scope_exit([&] {
  13918. svr.stop();
  13919. t.join();
  13920. });
  13921. svr.wait_until_ready();
  13922. SSLClient cli(HOST, PORT);
  13923. cli.enable_server_certificate_verification(false);
  13924. cli.set_connection_timeout(30);
  13925. int callback_count = 0;
  13926. bool saw_leaf_cert = false;
  13927. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13928. if (ctx.cert) {
  13929. callback_count++;
  13930. // We should see at least one certificate (the leaf)
  13931. std::string cn = ctx.subject_cn();
  13932. if (!cn.empty()) { saw_leaf_cert = true; }
  13933. // Verify context fields are populated
  13934. EXPECT_NE(ctx.session, nullptr);
  13935. EXPECT_GE(ctx.depth, 0);
  13936. }
  13937. return true;
  13938. });
  13939. auto res = cli.Get("/test");
  13940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13941. EXPECT_GT(callback_count, 0);
  13942. EXPECT_TRUE(saw_leaf_cert);
  13943. }
  13944. // A verifier belongs to the client that set it, not to the thread that set it.
  13945. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13946. using namespace httplib::tls;
  13947. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13948. ASSERT_TRUE(svr.is_valid());
  13949. svr.Get("/test", [](const Request &, Response &res) {
  13950. res.set_content("ok", "text/plain");
  13951. });
  13952. auto port = svr.bind_to_any_port(HOST);
  13953. thread t([&]() { svr.listen_after_bind(); });
  13954. auto se = detail::scope_exit([&] {
  13955. svr.stop();
  13956. t.join();
  13957. });
  13958. svr.wait_until_ready();
  13959. auto rejecting_calls = 0;
  13960. SSLClient rejecting(HOST, port);
  13961. rejecting.enable_server_certificate_verification(false);
  13962. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13963. rejecting_calls++;
  13964. return false;
  13965. });
  13966. auto accepting_calls = 0;
  13967. SSLClient accepting(HOST, port);
  13968. accepting.enable_server_certificate_verification(false);
  13969. // Set on another thread than the requests below.
  13970. thread([&]() {
  13971. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13972. accepting_calls++;
  13973. return true;
  13974. });
  13975. }).join();
  13976. // Requested on another thread than the verifier was set on.
  13977. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13978. EXPECT_GT(rejecting_calls, 0);
  13979. auto res = accepting.Get("/test");
  13980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13981. EXPECT_GT(accepting_calls, 0);
  13982. }
  13983. // VerifyContext::session is the same handle the other tls:: functions take.
  13984. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13985. using namespace httplib::tls;
  13986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13987. ASSERT_TRUE(svr.is_valid());
  13988. svr.Get("/test", [](const Request &, Response &res) {
  13989. res.set_content("ok", "text/plain");
  13990. });
  13991. auto port = svr.bind_to_any_port(HOST);
  13992. thread t([&]() { svr.listen_after_bind(); });
  13993. auto se = detail::scope_exit([&] {
  13994. svr.stop();
  13995. t.join();
  13996. });
  13997. svr.wait_until_ready();
  13998. SSLClient cli(HOST, port);
  13999. cli.enable_server_certificate_verification(false);
  14000. session_t verifier_session = nullptr;
  14001. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14002. verifier_session = ctx.session;
  14003. return true;
  14004. });
  14005. session_t session_verifier_session = nullptr;
  14006. cli.set_session_verifier([&](session_t session) {
  14007. session_verifier_session = session;
  14008. return SSLVerifierResponse::NoDecisionMade;
  14009. });
  14010. auto res = cli.Get("/test");
  14011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14012. EXPECT_NE(nullptr, verifier_session);
  14013. EXPECT_EQ(session_verifier_session, verifier_session);
  14014. }
  14015. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14016. using httplib::tls::TlsError;
  14017. // Test that verify_error_to_string returns empty for success
  14018. std::string success_str = TlsError::verify_error_to_string(0);
  14019. EXPECT_TRUE(success_str.empty());
  14020. // Test that verify_error_to_string returns non-empty for error codes
  14021. // Using a common error code (certificate expired)
  14022. std::string error_str =
  14023. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14024. EXPECT_FALSE(error_str.empty());
  14025. }
  14026. TEST(SessionVerifierTest, CertificateAccepted) {
  14027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14028. ASSERT_TRUE(svr.is_valid());
  14029. svr.Get("/test", [](const Request &, Response &res) {
  14030. res.set_content("ok", "text/plain");
  14031. });
  14032. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14033. auto se = detail::scope_exit([&] {
  14034. svr.stop();
  14035. t.join();
  14036. });
  14037. svr.wait_until_ready();
  14038. SSLClient cli(HOST, PORT);
  14039. cli.enable_server_certificate_verification(false);
  14040. cli.set_connection_timeout(30);
  14041. bool callback_called = false;
  14042. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14043. EXPECT_NE(session, nullptr);
  14044. callback_called = true;
  14045. return SSLVerifierResponse::CertificateAccepted;
  14046. });
  14047. auto res = cli.Get("/test");
  14048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14049. EXPECT_EQ(200, res->status);
  14050. EXPECT_TRUE(callback_called);
  14051. }
  14052. TEST(SessionVerifierTest, CertificateRejected) {
  14053. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14054. ASSERT_TRUE(svr.is_valid());
  14055. svr.Get("/test", [](const Request &, Response &res) {
  14056. res.set_content("ok", "text/plain");
  14057. });
  14058. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14059. auto se = detail::scope_exit([&] {
  14060. svr.stop();
  14061. t.join();
  14062. });
  14063. svr.wait_until_ready();
  14064. SSLClient cli(HOST, PORT);
  14065. cli.enable_server_certificate_verification(false);
  14066. cli.set_connection_timeout(30);
  14067. bool callback_called = false;
  14068. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14069. EXPECT_NE(session, nullptr);
  14070. callback_called = true;
  14071. return SSLVerifierResponse::CertificateRejected;
  14072. });
  14073. auto res = cli.Get("/test");
  14074. EXPECT_FALSE(res);
  14075. EXPECT_TRUE(callback_called);
  14076. }
  14077. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14078. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14079. ASSERT_TRUE(svr.is_valid());
  14080. svr.Get("/test", [](const Request &, Response &res) {
  14081. res.set_content("ok", "text/plain");
  14082. });
  14083. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14084. auto se = detail::scope_exit([&] {
  14085. svr.stop();
  14086. t.join();
  14087. });
  14088. svr.wait_until_ready();
  14089. // NoDecisionMade with verification disabled should succeed (no default check)
  14090. SSLClient cli(HOST, PORT);
  14091. cli.enable_server_certificate_verification(false);
  14092. cli.set_connection_timeout(30);
  14093. bool callback_called = false;
  14094. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14095. EXPECT_NE(session, nullptr);
  14096. callback_called = true;
  14097. return SSLVerifierResponse::NoDecisionMade;
  14098. });
  14099. auto res = cli.Get("/test");
  14100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14101. EXPECT_EQ(200, res->status);
  14102. EXPECT_TRUE(callback_called);
  14103. }
  14104. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14105. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14106. ASSERT_TRUE(svr.is_valid());
  14107. svr.Get("/test", [](const Request &, Response &res) {
  14108. res.set_content("ok", "text/plain");
  14109. });
  14110. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14111. auto se = detail::scope_exit([&] {
  14112. svr.stop();
  14113. t.join();
  14114. });
  14115. svr.wait_until_ready();
  14116. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14117. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14118. // so we only check that the request fails, not whether the callback was
  14119. // called.
  14120. SSLClient cli(HOST, PORT);
  14121. cli.enable_server_certificate_verification(true);
  14122. cli.set_connection_timeout(30);
  14123. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14124. EXPECT_NE(session, nullptr);
  14125. return SSLVerifierResponse::NoDecisionMade;
  14126. });
  14127. auto res = cli.Get("/test");
  14128. EXPECT_FALSE(res);
  14129. }
  14130. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14131. // Test SSL server using PemMemory constructor with client CA certificates
  14132. // Read PEM files
  14133. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14134. read_file(SERVER_CERT_FILE, server_cert_pem);
  14135. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14136. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14137. // Create SSLServer with PemMemory constructor including client CA
  14138. SSLServer::PemMemory server_pem = {
  14139. server_cert_pem.c_str(),
  14140. server_cert_pem.size(),
  14141. server_key_pem.c_str(),
  14142. server_key_pem.size(),
  14143. client_ca_pem.c_str(),
  14144. client_ca_pem.size(),
  14145. nullptr // no password for server key
  14146. };
  14147. SSLServer svr(server_pem);
  14148. ASSERT_TRUE(svr.is_valid());
  14149. // No SSL error should be recorded for valid setup
  14150. EXPECT_EQ(0, svr.ssl_last_error());
  14151. // Set up server endpoints
  14152. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14153. res.set_content("ok", "text/plain");
  14154. });
  14155. // Start server in a thread
  14156. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14157. svr.wait_until_ready();
  14158. // Connect with client certificate (using constructor with paths)
  14159. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14160. cli.enable_server_certificate_verification(false);
  14161. auto res = cli.Get("/test-pem-ca");
  14162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14163. EXPECT_EQ(200, res->status);
  14164. EXPECT_EQ("ok", res->body);
  14165. svr.stop();
  14166. server_thread.join();
  14167. }
  14168. #endif
  14169. #ifdef _WIN32
  14170. TEST(CleanupTest, WSACleanup) {
  14171. int ret = WSACleanup();
  14172. ASSERT_EQ(0, ret);
  14173. }
  14174. #endif
  14175. #ifndef CPPHTTPLIB_SSL_ENABLED
  14176. TEST(NoSSLSupport, SimpleInterface) {
  14177. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14178. }
  14179. #endif
  14180. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14181. TEST(InvalidScheme, SimpleInterface) {
  14182. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14183. }
  14184. #endif
  14185. TEST(NoScheme, SimpleInterface) {
  14186. Client cli("yahoo.com:80");
  14187. ASSERT_TRUE(cli.is_valid());
  14188. }
  14189. TEST(SendAPI, SimpleInterface_Online) {
  14190. Client cli("http://yahoo.com");
  14191. Request req;
  14192. req.method = "GET";
  14193. req.path = "/";
  14194. auto res = cli.send(req);
  14195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14196. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14197. }
  14198. TEST(SendAPI, WithParamsInRequest) {
  14199. Server svr;
  14200. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14201. EXPECT_TRUE(req.has_param("test"));
  14202. EXPECT_EQ("test_value", req.get_param_value("test"));
  14203. });
  14204. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14205. auto se = detail::scope_exit([&] {
  14206. svr.stop();
  14207. t.join();
  14208. ASSERT_FALSE(svr.is_running());
  14209. });
  14210. svr.wait_until_ready();
  14211. Client cli(HOST, PORT);
  14212. {
  14213. Request req;
  14214. req.method = "GET";
  14215. req.path = "/";
  14216. req.params.emplace("test", "test_value");
  14217. auto res = cli.send(req);
  14218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14219. }
  14220. {
  14221. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14223. }
  14224. }
  14225. TEST(ClientImplMethods, GetSocketTest) {
  14226. httplib::Server svr;
  14227. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14228. res.status = StatusCode::OK_200;
  14229. });
  14230. auto port = svr.bind_to_any_port("127.0.0.1");
  14231. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14232. auto se = detail::scope_exit([&] {
  14233. svr.stop();
  14234. thread.join();
  14235. ASSERT_FALSE(svr.is_running());
  14236. });
  14237. svr.wait_until_ready();
  14238. {
  14239. httplib::Client cli("127.0.0.1", port);
  14240. cli.set_keep_alive(true);
  14241. // Use the behavior of cpp-httplib of opening the connection
  14242. // only when the first request happens. If that changes,
  14243. // this test would be obsolete.
  14244. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14245. // This also implicitly tests the server. But other tests would fail much
  14246. // earlier than this one to be considered.
  14247. auto res = cli.Get("/");
  14248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14249. EXPECT_EQ(StatusCode::OK_200, res->status);
  14250. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14251. }
  14252. }
  14253. #ifdef CPPHTTPLIB_SSL_ENABLED
  14254. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14255. Client cli("http://yahoo.com");
  14256. auto res = cli.Get("/");
  14257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14258. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14259. cli.set_follow_location(true);
  14260. res = cli.Get("/");
  14261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14262. EXPECT_EQ(StatusCode::OK_200, res->status);
  14263. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14264. }
  14265. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14266. Client cli("https://yahoo.com");
  14267. auto res = cli.Get("/");
  14268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14269. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14270. cli.set_follow_location(true);
  14271. res = cli.Get("/");
  14272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14273. EXPECT_EQ(StatusCode::OK_200, res->status);
  14274. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14275. }
  14276. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14277. Client cli("https://yahoo.com");
  14278. auto res = cli.Get("/");
  14279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14280. ASSERT_FALSE(!res);
  14281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14282. ASSERT_FALSE(res == nullptr);
  14283. ASSERT_TRUE(res != nullptr);
  14284. EXPECT_EQ(Error::Success, res.error());
  14285. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14286. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14287. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14288. cli.set_follow_location(true);
  14289. res = cli.Get("/");
  14290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14291. EXPECT_EQ(Error::Success, res.error());
  14292. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14293. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14294. EXPECT_EQ(StatusCode::OK_200, res->status);
  14295. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14296. }
  14297. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14298. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14299. Client cli("https://cdnjs.cloudflare.com");
  14300. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14301. Headers{{"Accept-Encoding", "br"}});
  14302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14303. EXPECT_EQ(StatusCode::OK_200, res->status);
  14304. EXPECT_EQ(287630U, res->body.size());
  14305. EXPECT_EQ("application/javascript; charset=utf-8",
  14306. res->get_header_value("Content-Type"));
  14307. }
  14308. #endif
  14309. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14310. #undef REDIR_HOST // Silence compiler warning
  14311. #define REDIR_HOST "https://httpbingo.org"
  14312. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14313. Client cli(REDIR_HOST);
  14314. cli.set_follow_location(true);
  14315. auto res =
  14316. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14318. EXPECT_EQ(StatusCode::OK_200, res->status);
  14319. }
  14320. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14321. Client cli(REDIR_HOST);
  14322. cli.set_follow_location(true);
  14323. Params params;
  14324. params.emplace("url", "http://example.com");
  14325. params.emplace("status_code", "302");
  14326. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14328. EXPECT_EQ(StatusCode::OK_200, res->status);
  14329. }
  14330. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14331. Client cli(REDIR_HOST);
  14332. cli.set_follow_location(true);
  14333. Params params;
  14334. params.emplace("url", "http://example.com");
  14335. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14337. EXPECT_EQ(StatusCode::OK_200, res->status);
  14338. }
  14339. TEST(HttpToHttpsRedirectTest, CertFile) {
  14340. auto ssl_port = PORT + 1;
  14341. Server svr;
  14342. ASSERT_TRUE(svr.is_valid());
  14343. svr.Get("/index", [&](const Request &, Response &res) {
  14344. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14345. "/index");
  14346. svr.stop();
  14347. });
  14348. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14349. ASSERT_TRUE(ssl_svr.is_valid());
  14350. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14351. res.set_content("test", "text/plain");
  14352. ssl_svr.stop();
  14353. });
  14354. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14355. thread t2 =
  14356. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14357. auto se = detail::scope_exit([&] {
  14358. t2.join();
  14359. t.join();
  14360. ASSERT_FALSE(svr.is_running());
  14361. });
  14362. svr.wait_until_ready();
  14363. ssl_svr.wait_until_ready();
  14364. Client cli("127.0.0.1", PORT);
  14365. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14366. cli.enable_server_certificate_verification(true);
  14367. cli.set_follow_location(true);
  14368. cli.set_connection_timeout(30);
  14369. auto res = cli.Get("/index");
  14370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14371. ASSERT_EQ(StatusCode::OK_200, res->status);
  14372. }
  14373. TEST(SSLClientRedirectTest, CertFile) {
  14374. auto ssl_port = PORT + 1;
  14375. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14376. ASSERT_TRUE(ssl_svr1.is_valid());
  14377. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14378. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14379. "/index");
  14380. ssl_svr1.stop();
  14381. });
  14382. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14383. ASSERT_TRUE(ssl_svr2.is_valid());
  14384. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14385. res.set_content("test", "text/plain");
  14386. ssl_svr2.stop();
  14387. });
  14388. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14389. thread t2 =
  14390. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14391. auto se = detail::scope_exit([&] {
  14392. t2.join();
  14393. t.join();
  14394. ASSERT_FALSE(ssl_svr1.is_running());
  14395. });
  14396. ssl_svr1.wait_until_ready();
  14397. ssl_svr2.wait_until_ready();
  14398. SSLClient cli("127.0.0.1", PORT);
  14399. std::string cert;
  14400. read_file(SERVER_CERT2_FILE, cert);
  14401. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14402. cli.enable_server_certificate_verification(true);
  14403. cli.set_follow_location(true);
  14404. cli.set_connection_timeout(30);
  14405. auto res = cli.Get("/index");
  14406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14407. ASSERT_EQ(StatusCode::OK_200, res->status);
  14408. }
  14409. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14410. // another port, so the client follows it with a new client.
  14411. static Result GetThroughTlsRedirectToDifferentPort(
  14412. const std::function<void(SSLClient &)> &setup,
  14413. const char *target_cert = SERVER_CERT2_FILE) {
  14414. auto ssl_port = PORT + 1;
  14415. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14416. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14417. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14418. "/index");
  14419. });
  14420. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14421. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14422. res.set_content("test", "text/plain");
  14423. });
  14424. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14425. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14426. auto se = detail::scope_exit([&] {
  14427. ssl_svr2.stop();
  14428. ssl_svr1.stop();
  14429. t2.join();
  14430. t.join();
  14431. });
  14432. ssl_svr1.wait_until_ready();
  14433. ssl_svr2.wait_until_ready();
  14434. SSLClient cli("127.0.0.1", PORT);
  14435. cli.set_follow_location(true);
  14436. cli.set_connection_timeout(30);
  14437. setup(cli);
  14438. return cli.Get("/index");
  14439. }
  14440. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14441. auto calls = 0;
  14442. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14443. cli.enable_server_certificate_verification(false);
  14444. // Accept the first server only.
  14445. cli.set_session_verifier([&](tls::session_t) {
  14446. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14447. : SSLVerifierResponse::CertificateRejected;
  14448. });
  14449. });
  14450. EXPECT_FALSE(res);
  14451. EXPECT_EQ(2, calls);
  14452. }
  14453. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14454. std::string pinned;
  14455. auto res = GetThroughTlsRedirectToDifferentPort(
  14456. [&](SSLClient &cli) {
  14457. cli.enable_server_certificate_verification(false);
  14458. // Pin the first certificate seen.
  14459. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14460. if (pinned.empty()) { pinned = ctx.serial(); }
  14461. return ctx.serial() == pinned;
  14462. });
  14463. },
  14464. // A certificate other than the first server's.
  14465. SERVER_CERT_FILE);
  14466. EXPECT_FALSE(res);
  14467. EXPECT_FALSE(pinned.empty());
  14468. }
  14469. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14470. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14471. std::string cert;
  14472. read_file(SERVER_CERT2_FILE, cert);
  14473. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14474. });
  14475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14476. EXPECT_EQ(StatusCode::OK_200, res->status);
  14477. }
  14478. #endif
  14479. #ifdef CPPHTTPLIB_SSL_ENABLED
  14480. // Test that set_ca_cert_store() skips system certs (consistent with
  14481. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14482. // should be trusted - system certs should NOT be loaded.
  14483. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14484. // Load a specific cert that is NOT a system CA cert
  14485. std::string cert;
  14486. read_file(SERVER_CERT2_FILE, cert);
  14487. SSLClient cli("google.com");
  14488. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14489. cli.enable_server_certificate_verification(true);
  14490. // This should FAIL because:
  14491. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14492. // 2. System certs should NOT be loaded when custom store is set
  14493. // If system certs WERE loaded, this would succeed
  14494. auto res = cli.Get("/");
  14495. ASSERT_FALSE(res);
  14496. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14497. }
  14498. // Same as above, but through the native store handle path. Regression test:
  14499. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14500. // merged system certs into the user-provided store.
  14501. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14502. std::string cert;
  14503. read_file(SERVER_CERT2_FILE, cert);
  14504. SSLClient cli("google.com");
  14505. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14506. cli.enable_server_certificate_verification(true);
  14507. auto res = cli.Get("/");
  14508. ASSERT_FALSE(res);
  14509. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14510. }
  14511. // A custom store set via the native handle must still verify a server whose
  14512. // cert it does contain.
  14513. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14514. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14515. ASSERT_TRUE(svr.is_valid());
  14516. svr.Get("/test", [&](const Request &, Response &res) {
  14517. res.set_content("test", "text/plain");
  14518. });
  14519. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14520. auto se = detail::scope_exit([&] {
  14521. svr.stop();
  14522. t.join();
  14523. ASSERT_FALSE(svr.is_running());
  14524. });
  14525. svr.wait_until_ready();
  14526. SSLClient cli("127.0.0.1", PORT);
  14527. std::string cert;
  14528. read_file(SERVER_CERT2_FILE, cert);
  14529. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14530. cli.enable_server_certificate_verification(true);
  14531. cli.set_connection_timeout(30);
  14532. auto res = cli.Get("/test");
  14533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14534. ASSERT_EQ(StatusCode::OK_200, res->status);
  14535. }
  14536. // CA certs loaded through the universal Client must be transferred to the
  14537. // client created internally for following an HTTPS redirect. Regression test:
  14538. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14539. // the CA data for redirect transfer.
  14540. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14541. auto ssl_port = PORT + 1;
  14542. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14543. ASSERT_TRUE(ssl_svr1.is_valid());
  14544. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14545. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14546. "/index");
  14547. });
  14548. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14549. ASSERT_TRUE(ssl_svr2.is_valid());
  14550. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14551. res.set_content("test", "text/plain");
  14552. });
  14553. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14554. thread t2 =
  14555. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14556. auto se = detail::scope_exit([&] {
  14557. ssl_svr2.stop();
  14558. ssl_svr1.stop();
  14559. t2.join();
  14560. t.join();
  14561. ASSERT_FALSE(ssl_svr1.is_running());
  14562. });
  14563. ssl_svr1.wait_until_ready();
  14564. ssl_svr2.wait_until_ready();
  14565. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14566. std::string cert;
  14567. read_file(SERVER_CERT2_FILE, cert);
  14568. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14569. cli.enable_server_certificate_verification(true);
  14570. cli.set_follow_location(true);
  14571. cli.set_connection_timeout(30);
  14572. auto res = cli.Get("/index");
  14573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14574. ASSERT_EQ(StatusCode::OK_200, res->status);
  14575. }
  14576. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14577. // so a host signed by a system CA verifies even though a custom CA is set
  14578. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14579. std::string cert;
  14580. read_file(SERVER_CERT2_FILE, cert);
  14581. SSLClient cli("google.com");
  14582. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14583. cli.enable_system_ca(true);
  14584. cli.enable_server_certificate_verification(true);
  14585. auto res = cli.Get("/");
  14586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14587. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14588. }
  14589. // The custom CA remains effective when combined with the system CA
  14590. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14591. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14592. ASSERT_TRUE(svr.is_valid());
  14593. svr.Get("/test", [&](const Request &, Response &res) {
  14594. res.set_content("test", "text/plain");
  14595. });
  14596. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14597. auto se = detail::scope_exit([&] {
  14598. svr.stop();
  14599. t.join();
  14600. ASSERT_FALSE(svr.is_running());
  14601. });
  14602. svr.wait_until_ready();
  14603. SSLClient cli("127.0.0.1", PORT);
  14604. std::string cert;
  14605. read_file(SERVER_CERT2_FILE, cert);
  14606. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14607. cli.enable_system_ca(true);
  14608. cli.enable_server_certificate_verification(true);
  14609. cli.set_connection_timeout(30);
  14610. auto res = cli.Get("/test");
  14611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14612. ASSERT_EQ(StatusCode::OK_200, res->status);
  14613. }
  14614. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14615. // skip chain verification entirely (only the certificate identity was
  14616. // checked), so a server presenting an untrusted certificate with a matching
  14617. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14618. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14619. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14620. ASSERT_TRUE(svr.is_valid());
  14621. svr.Get("/test", [&](const Request &, Response &res) {
  14622. res.set_content("test", "text/plain");
  14623. });
  14624. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14625. auto se = detail::scope_exit([&] {
  14626. svr.stop();
  14627. t.join();
  14628. ASSERT_FALSE(svr.is_running());
  14629. });
  14630. svr.wait_until_ready();
  14631. SSLClient cli("127.0.0.1", PORT);
  14632. std::string cert;
  14633. // A trusted CA that did not sign the server certificate. The server cert
  14634. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14635. // this connection.
  14636. read_file(CLIENT_CA_CERT_FILE, cert);
  14637. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14638. cli.enable_server_certificate_verification(true);
  14639. cli.set_connection_timeout(30);
  14640. auto res = cli.Get("/test");
  14641. ASSERT_FALSE(res);
  14642. }
  14643. // enable_system_ca(false) prevents system CA loading entirely
  14644. TEST(SSLClientTest, DisableSystemCa_Online) {
  14645. SSLClient cli("google.com");
  14646. cli.enable_system_ca(false);
  14647. cli.enable_server_certificate_verification(true);
  14648. auto res = cli.Get("/");
  14649. ASSERT_FALSE(res);
  14650. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14651. // itself when the CA chain is empty
  14652. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14653. res.error() == Error::SSLConnection);
  14654. }
  14655. // The universal Client forwards enable_system_ca()
  14656. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14657. std::string cert;
  14658. read_file(SERVER_CERT2_FILE, cert);
  14659. Client cli("https://google.com");
  14660. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14661. cli.enable_system_ca(true);
  14662. cli.enable_server_certificate_verification(true);
  14663. auto res = cli.Get("/");
  14664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14665. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14666. }
  14667. // The system CA policy must carry over to the client created internally for
  14668. // following a cross-host HTTPS redirect
  14669. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14670. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14671. ASSERT_TRUE(svr.is_valid());
  14672. svr.Get("/index", [&](const Request &, Response &res) {
  14673. res.set_redirect("https://www.google.com/");
  14674. });
  14675. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14676. auto se = detail::scope_exit([&] {
  14677. svr.stop();
  14678. t.join();
  14679. ASSERT_FALSE(svr.is_running());
  14680. });
  14681. svr.wait_until_ready();
  14682. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14683. std::string cert;
  14684. read_file(SERVER_CERT2_FILE, cert);
  14685. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14686. cli.enable_system_ca(true);
  14687. cli.enable_server_certificate_verification(true);
  14688. cli.set_follow_location(true);
  14689. cli.set_connection_timeout(30);
  14690. // Receiving any response proves the redirect client completed the TLS
  14691. // handshake with a system-CA-signed host
  14692. auto res = cli.Get("/index");
  14693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14694. }
  14695. TEST(MultipartFormDataTest, LargeData) {
  14696. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14697. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14698. const ContentReader &content_reader) {
  14699. if (req.is_multipart_form_data()) {
  14700. std::vector<FormData> items;
  14701. content_reader(
  14702. [&](const FormData &file) {
  14703. items.push_back(file);
  14704. return true;
  14705. },
  14706. [&](const char *data, size_t data_length) {
  14707. items.back().content.append(data, data_length);
  14708. return true;
  14709. });
  14710. EXPECT_TRUE(std::string(items[0].name) == "document");
  14711. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14712. EXPECT_TRUE(items[0].filename == "2MB_data");
  14713. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14714. EXPECT_TRUE(items[1].name == "hello");
  14715. EXPECT_TRUE(items[1].content == "world");
  14716. EXPECT_TRUE(items[1].filename == "");
  14717. EXPECT_TRUE(items[1].content_type == "");
  14718. } else {
  14719. std::string body;
  14720. content_reader([&](const char *data, size_t data_length) {
  14721. body.append(data, data_length);
  14722. return true;
  14723. });
  14724. }
  14725. });
  14726. auto port = svr.bind_to_any_port(HOST);
  14727. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14728. auto se = detail::scope_exit([&] {
  14729. svr.stop();
  14730. t.join();
  14731. ASSERT_FALSE(svr.is_running());
  14732. });
  14733. svr.wait_until_ready();
  14734. {
  14735. std::string data(1024 * 1024 * 2, '.');
  14736. std::stringstream buffer;
  14737. buffer << data;
  14738. SSLClient cli(HOST, port);
  14739. cli.enable_server_certificate_verification(false);
  14740. UploadFormDataItems items{
  14741. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14742. {"hello", "world", "", ""},
  14743. };
  14744. auto res = cli.Post("/post", items);
  14745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14746. ASSERT_EQ(StatusCode::OK_200, res->status);
  14747. }
  14748. }
  14749. TEST(MultipartFormDataTest, DataProviderItems) {
  14750. std::random_device seed_gen;
  14751. std::mt19937 random(seed_gen());
  14752. std::string rand1;
  14753. rand1.resize(1000);
  14754. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14755. std::string rand2;
  14756. rand2.resize(3000);
  14757. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14758. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14759. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14760. const ContentReader &content_reader) {
  14761. ASSERT_FALSE(req.is_multipart_form_data());
  14762. std::string body;
  14763. content_reader([&](const char *data, size_t data_length) {
  14764. body.append(data, data_length);
  14765. return true;
  14766. });
  14767. EXPECT_EQ(body, "");
  14768. });
  14769. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14770. const ContentReader &content_reader) {
  14771. ASSERT_TRUE(req.is_multipart_form_data());
  14772. std::vector<FormData> items;
  14773. content_reader(
  14774. [&](const FormData &file) {
  14775. items.push_back(file);
  14776. return true;
  14777. },
  14778. [&](const char *data, size_t data_length) {
  14779. items.back().content.append(data, data_length);
  14780. return true;
  14781. });
  14782. ASSERT_TRUE(items.size() == 2);
  14783. EXPECT_EQ(std::string(items[0].name), "name1");
  14784. EXPECT_EQ(items[0].content, "Testing123");
  14785. EXPECT_EQ(items[0].filename, "filename1");
  14786. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14787. EXPECT_EQ(items[1].name, "name2");
  14788. EXPECT_EQ(items[1].content, "Testing456");
  14789. EXPECT_EQ(items[1].filename, "");
  14790. EXPECT_EQ(items[1].content_type, "");
  14791. });
  14792. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14793. const ContentReader &content_reader) {
  14794. ASSERT_TRUE(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. ASSERT_TRUE(items.size() == 2);
  14806. EXPECT_EQ(items[0].name, "name3");
  14807. EXPECT_EQ(items[0].content, rand1);
  14808. EXPECT_EQ(items[0].filename, "filename3");
  14809. EXPECT_EQ(items[0].content_type, "");
  14810. EXPECT_EQ(items[1].name, "name4");
  14811. EXPECT_EQ(items[1].content, rand2);
  14812. EXPECT_EQ(items[1].filename, "filename4");
  14813. EXPECT_EQ(items[1].content_type, "");
  14814. });
  14815. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14816. const ContentReader &content_reader) {
  14817. ASSERT_TRUE(req.is_multipart_form_data());
  14818. std::vector<FormData> items;
  14819. content_reader(
  14820. [&](const FormData &file) {
  14821. items.push_back(file);
  14822. return true;
  14823. },
  14824. [&](const char *data, size_t data_length) {
  14825. items.back().content.append(data, data_length);
  14826. return true;
  14827. });
  14828. ASSERT_TRUE(items.size() == 4);
  14829. EXPECT_EQ(std::string(items[0].name), "name1");
  14830. EXPECT_EQ(items[0].content, "Testing123");
  14831. EXPECT_EQ(items[0].filename, "filename1");
  14832. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14833. EXPECT_EQ(items[1].name, "name2");
  14834. EXPECT_EQ(items[1].content, "Testing456");
  14835. EXPECT_EQ(items[1].filename, "");
  14836. EXPECT_EQ(items[1].content_type, "");
  14837. EXPECT_EQ(items[2].name, "name3");
  14838. EXPECT_EQ(items[2].content, rand1);
  14839. EXPECT_EQ(items[2].filename, "filename3");
  14840. EXPECT_EQ(items[2].content_type, "");
  14841. EXPECT_EQ(items[3].name, "name4");
  14842. EXPECT_EQ(items[3].content, rand2);
  14843. EXPECT_EQ(items[3].filename, "filename4");
  14844. EXPECT_EQ(items[3].content_type, "");
  14845. });
  14846. auto port = svr.bind_to_any_port("localhost");
  14847. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14848. auto se = detail::scope_exit([&] {
  14849. svr.stop();
  14850. t.join();
  14851. ASSERT_FALSE(svr.is_running());
  14852. });
  14853. svr.wait_until_ready();
  14854. {
  14855. SSLClient cli("localhost", port);
  14856. cli.enable_server_certificate_verification(false);
  14857. UploadFormDataItems items{
  14858. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14859. {"name2", "Testing456", "", ""}, // not a file
  14860. };
  14861. {
  14862. auto res = cli.Post("/post-none", {}, {}, {});
  14863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14864. ASSERT_EQ(StatusCode::OK_200, res->status);
  14865. }
  14866. FormDataProviderItems providers;
  14867. {
  14868. auto res =
  14869. cli.Post("/post-items", {}, items, providers); // empty providers
  14870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14871. ASSERT_EQ(StatusCode::OK_200, res->status);
  14872. }
  14873. providers.push_back({"name3",
  14874. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14875. // test the offset is given correctly at each step
  14876. if (!offset)
  14877. sink.os.write(rand1.data(), 30);
  14878. else if (offset == 30)
  14879. sink.os.write(rand1.data() + 30, 300);
  14880. else if (offset == 330)
  14881. sink.os.write(rand1.data() + 330, 670);
  14882. else if (offset == rand1.size())
  14883. sink.done();
  14884. return true;
  14885. },
  14886. "filename3",
  14887. {}});
  14888. providers.push_back({"name4",
  14889. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14890. // test the offset is given correctly at each step
  14891. if (!offset)
  14892. sink.os.write(rand2.data(), 2000);
  14893. else if (offset == 2000)
  14894. sink.os.write(rand2.data() + 2000, 1);
  14895. else if (offset == 2001)
  14896. sink.os.write(rand2.data() + 2001, 999);
  14897. else if (offset == rand2.size())
  14898. sink.done();
  14899. return true;
  14900. },
  14901. "filename4",
  14902. {}});
  14903. {
  14904. auto res = cli.Post("/post-providers", {}, {}, providers);
  14905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14906. ASSERT_EQ(StatusCode::OK_200, res->status);
  14907. }
  14908. {
  14909. auto res = cli.Post("/post-both", {}, items, providers);
  14910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14911. ASSERT_EQ(StatusCode::OK_200, res->status);
  14912. }
  14913. }
  14914. }
  14915. TEST(MultipartFormDataTest, BadHeader) {
  14916. Server svr;
  14917. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14918. res.set_content("ok", "text/plain");
  14919. });
  14920. thread t = thread([&] { svr.listen(HOST, PORT); });
  14921. auto se = detail::scope_exit([&] {
  14922. svr.stop();
  14923. t.join();
  14924. ASSERT_FALSE(svr.is_running());
  14925. });
  14926. svr.wait_until_ready();
  14927. const std::string body =
  14928. "This is the preamble. It is to be ignored, though it\r\n"
  14929. "is a handy place for composition agents to include an\r\n"
  14930. "explanatory note to non-MIME conformant readers.\r\n"
  14931. "\r\n"
  14932. "\r\n"
  14933. "--simple boundary\r\n"
  14934. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14935. ": BAD...\r\n"
  14936. "\r\n"
  14937. "value1\r\n"
  14938. "--simple boundary\r\n"
  14939. "Content-Disposition: form-data; name=\"field2\"; "
  14940. "filename=\"example.txt\"\r\n"
  14941. "\r\n"
  14942. "value2\r\n"
  14943. "--simple boundary--\r\n"
  14944. "This is the epilogue. It is also to be ignored.\r\n";
  14945. std::string content_type =
  14946. R"(multipart/form-data; boundary="simple boundary")";
  14947. Client cli(HOST, PORT);
  14948. auto res = cli.Post("/post", body, content_type.c_str());
  14949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14950. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14951. }
  14952. TEST(MultipartFormDataTest, WithPreamble) {
  14953. Server svr;
  14954. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14955. res.set_content("ok", "text/plain");
  14956. });
  14957. thread t = thread([&] { svr.listen(HOST, PORT); });
  14958. auto se = detail::scope_exit([&] {
  14959. svr.stop();
  14960. t.join();
  14961. ASSERT_FALSE(svr.is_running());
  14962. });
  14963. svr.wait_until_ready();
  14964. const std::string body =
  14965. "This is the preamble. It is to be ignored, though it\r\n"
  14966. "is a handy place for composition agents to include an\r\n"
  14967. "explanatory note to non-MIME conformant readers.\r\n"
  14968. "\r\n"
  14969. "\r\n"
  14970. "--simple boundary\r\n"
  14971. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14972. "\r\n"
  14973. "value1\r\n"
  14974. "--simple boundary\r\n"
  14975. "Content-Disposition: form-data; name=\"field2\"; "
  14976. "filename=\"example.txt\"\r\n"
  14977. "\r\n"
  14978. "value2\r\n"
  14979. "--simple boundary--\r\n"
  14980. "This is the epilogue. It is also to be ignored.\r\n";
  14981. std::string content_type =
  14982. R"(multipart/form-data; boundary="simple boundary")";
  14983. Client cli(HOST, PORT);
  14984. auto res = cli.Post("/post", body, content_type.c_str());
  14985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14986. EXPECT_EQ(StatusCode::OK_200, res->status);
  14987. }
  14988. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14989. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14990. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14991. const ContentReader &content_reader) {
  14992. if (req.is_multipart_form_data()) {
  14993. std::vector<FormData> items;
  14994. content_reader(
  14995. [&](const FormData &file) {
  14996. items.push_back(file);
  14997. return true;
  14998. },
  14999. [&](const char *data, size_t data_length) {
  15000. items.back().content.append(data, data_length);
  15001. return true;
  15002. });
  15003. EXPECT_TRUE(std::string(items[0].name) == "document");
  15004. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15005. EXPECT_TRUE(items[0].filename == "2MB_data");
  15006. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15007. EXPECT_TRUE(items[1].name == "hello");
  15008. EXPECT_TRUE(items[1].content == "world");
  15009. EXPECT_TRUE(items[1].filename == "");
  15010. EXPECT_TRUE(items[1].content_type == "");
  15011. } else {
  15012. std::string body;
  15013. content_reader([&](const char *data, size_t data_length) {
  15014. body.append(data, data_length);
  15015. return true;
  15016. });
  15017. }
  15018. });
  15019. auto port = svr.bind_to_any_port("localhost");
  15020. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15021. auto se = detail::scope_exit([&] {
  15022. svr.stop();
  15023. t.join();
  15024. ASSERT_FALSE(svr.is_running());
  15025. });
  15026. svr.wait_until_ready();
  15027. {
  15028. std::string data(1024 * 1024 * 2, '.');
  15029. std::stringstream buffer;
  15030. buffer << data;
  15031. SSLClient cli("localhost", port);
  15032. cli.enable_server_certificate_verification(false);
  15033. UploadFormDataItems items{
  15034. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15035. {"hello", "world", "", ""},
  15036. };
  15037. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15039. ASSERT_EQ(StatusCode::OK_200, res->status);
  15040. }
  15041. }
  15042. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15043. std::string data(1024 * 1024 * 2, '&');
  15044. std::stringstream buffer;
  15045. buffer << data;
  15046. Client cli("https://localhost:8080");
  15047. UploadFormDataItems items{
  15048. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15049. {"hello", "world", "", ""},
  15050. };
  15051. for (const char &c : " \t\r\n") {
  15052. auto res =
  15053. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15054. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15055. ASSERT_FALSE(res);
  15056. }
  15057. }
  15058. TEST(MultipartFormDataTest, PutFormData) {
  15059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15060. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15061. const ContentReader &content_reader) {
  15062. if (req.is_multipart_form_data()) {
  15063. std::vector<FormData> items;
  15064. content_reader(
  15065. [&](const FormData &file) {
  15066. items.push_back(file);
  15067. return true;
  15068. },
  15069. [&](const char *data, size_t data_length) {
  15070. items.back().content.append(data, data_length);
  15071. return true;
  15072. });
  15073. EXPECT_TRUE(std::string(items[0].name) == "document");
  15074. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15075. EXPECT_TRUE(items[0].filename == "2MB_data");
  15076. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15077. EXPECT_TRUE(items[1].name == "hello");
  15078. EXPECT_TRUE(items[1].content == "world");
  15079. EXPECT_TRUE(items[1].filename == "");
  15080. EXPECT_TRUE(items[1].content_type == "");
  15081. } else {
  15082. std::string body;
  15083. content_reader([&](const char *data, size_t data_length) {
  15084. body.append(data, data_length);
  15085. return true;
  15086. });
  15087. }
  15088. });
  15089. auto port = svr.bind_to_any_port("localhost");
  15090. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15091. auto se = detail::scope_exit([&] {
  15092. svr.stop();
  15093. t.join();
  15094. ASSERT_FALSE(svr.is_running());
  15095. });
  15096. svr.wait_until_ready();
  15097. {
  15098. std::string data(1024 * 1024 * 2, '&');
  15099. std::stringstream buffer;
  15100. buffer << data;
  15101. SSLClient cli("localhost", port);
  15102. cli.enable_server_certificate_verification(false);
  15103. UploadFormDataItems items{
  15104. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15105. {"hello", "world", "", ""},
  15106. };
  15107. auto res = cli.Put("/put", items);
  15108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15109. ASSERT_EQ(StatusCode::OK_200, res->status);
  15110. }
  15111. }
  15112. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15114. svr.Put("/put_customboundary",
  15115. [&](const Request &req, const Response & /*res*/,
  15116. const ContentReader &content_reader) {
  15117. if (req.is_multipart_form_data()) {
  15118. std::vector<FormData> items;
  15119. content_reader(
  15120. [&](const FormData &file) {
  15121. items.push_back(file);
  15122. return true;
  15123. },
  15124. [&](const char *data, size_t data_length) {
  15125. items.back().content.append(data, data_length);
  15126. return true;
  15127. });
  15128. EXPECT_TRUE(std::string(items[0].name) == "document");
  15129. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15130. EXPECT_TRUE(items[0].filename == "2MB_data");
  15131. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15132. EXPECT_TRUE(items[1].name == "hello");
  15133. EXPECT_TRUE(items[1].content == "world");
  15134. EXPECT_TRUE(items[1].filename == "");
  15135. EXPECT_TRUE(items[1].content_type == "");
  15136. } else {
  15137. std::string body;
  15138. content_reader([&](const char *data, size_t data_length) {
  15139. body.append(data, data_length);
  15140. return true;
  15141. });
  15142. }
  15143. });
  15144. auto port = svr.bind_to_any_port("localhost");
  15145. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15146. auto se = detail::scope_exit([&] {
  15147. svr.stop();
  15148. t.join();
  15149. ASSERT_FALSE(svr.is_running());
  15150. });
  15151. svr.wait_until_ready();
  15152. {
  15153. std::string data(1024 * 1024 * 2, '&');
  15154. std::stringstream buffer;
  15155. buffer << data;
  15156. SSLClient cli("localhost", port);
  15157. cli.enable_server_certificate_verification(false);
  15158. UploadFormDataItems items{
  15159. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15160. {"hello", "world", "", ""},
  15161. };
  15162. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15164. ASSERT_EQ(StatusCode::OK_200, res->status);
  15165. }
  15166. }
  15167. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15168. std::string data(1024 * 1024 * 2, '&');
  15169. std::stringstream buffer;
  15170. buffer << data;
  15171. Client cli("https://localhost:8080");
  15172. cli.enable_server_certificate_verification(false);
  15173. UploadFormDataItems items{
  15174. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15175. {"hello", "world", "", ""},
  15176. };
  15177. for (const char &c : " \t\r\n") {
  15178. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15179. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15180. ASSERT_FALSE(res);
  15181. }
  15182. }
  15183. TEST(MultipartFormDataTest, AlternateFilename) {
  15184. auto handled = false;
  15185. Server svr;
  15186. svr.Post("/test", [&](const Request &req, Response &res) {
  15187. ASSERT_EQ(2u, req.form.files.size());
  15188. ASSERT_EQ(1u, req.form.fields.size());
  15189. // Test files
  15190. const auto &file1 = req.form.get_file("file1");
  15191. ASSERT_EQ("file1", file1.name);
  15192. ASSERT_EQ("A.txt", file1.filename);
  15193. ASSERT_EQ("text/plain", file1.content_type);
  15194. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15195. const auto &file2 = req.form.get_file("file2");
  15196. ASSERT_EQ("file2", file2.name);
  15197. ASSERT_EQ("a.html", file2.filename);
  15198. ASSERT_EQ("text/html", file2.content_type);
  15199. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15200. file2.content);
  15201. // Test text field
  15202. const auto &text = req.form.get_field("text");
  15203. ASSERT_EQ("text default", text);
  15204. res.set_content("ok", "text/plain");
  15205. handled = true;
  15206. });
  15207. thread t = thread([&] { svr.listen(HOST, PORT); });
  15208. auto se = detail::scope_exit([&] {
  15209. svr.stop();
  15210. t.join();
  15211. ASSERT_FALSE(svr.is_running());
  15212. ASSERT_TRUE(handled);
  15213. });
  15214. svr.wait_until_ready();
  15215. auto req = "POST /test HTTP/1.1\r\n"
  15216. "Host: localhost\r\n"
  15217. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15218. "Content-Length: 399\r\n"
  15219. "\r\n"
  15220. "----------\r\n"
  15221. "Content-Disposition: form-data; name=\"text\"\r\n"
  15222. "\r\n"
  15223. "text default\r\n"
  15224. "----------\r\n"
  15225. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15226. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15227. "Content-Type: text/plain\r\n"
  15228. "\r\n"
  15229. "Content of a.txt.\r\n"
  15230. "\r\n"
  15231. "----------\r\n"
  15232. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15233. "\"a.html\"\r\n"
  15234. "Content-Type: text/html\r\n"
  15235. "\r\n"
  15236. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15237. "\r\n"
  15238. "------------\r\n";
  15239. ASSERT_TRUE(send_request(1, req));
  15240. }
  15241. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15242. auto handled = false;
  15243. Server svr;
  15244. svr.Post("/test", [&](const Request &req, Response &res) {
  15245. // Case-insensitive "utf-8''" prefix with a long value
  15246. const auto &file = req.form.get_file("file1");
  15247. ASSERT_EQ("file1", file.name);
  15248. // 8000 chars exercises both the Content-Disposition parser and the
  15249. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15250. // Prior to the fix, std::regex_match on this header would cause O(N)
  15251. // stack recursion in libstdc++, leading to SIGSEGV.
  15252. std::string expected_filename(8000, 'A');
  15253. ASSERT_EQ(expected_filename, file.filename);
  15254. res.set_content("ok", "text/plain");
  15255. handled = true;
  15256. });
  15257. thread t = thread([&] { svr.listen(HOST, PORT); });
  15258. auto se = detail::scope_exit([&] {
  15259. svr.stop();
  15260. t.join();
  15261. ASSERT_FALSE(svr.is_running());
  15262. ASSERT_TRUE(handled);
  15263. });
  15264. svr.wait_until_ready();
  15265. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15266. // Regression test for GHSA-qq6v-r583-3h69
  15267. std::string long_filename(8000, 'A');
  15268. std::string body = "----------\r\n"
  15269. "Content-Disposition: form-data; name=\"file1\"; "
  15270. "filename*=\"Utf-8''" +
  15271. long_filename +
  15272. "\"\r\n"
  15273. "\r\n"
  15274. "hello\r\n"
  15275. "------------\r\n";
  15276. auto req = "POST /test HTTP/1.1\r\n"
  15277. "Host: localhost\r\n"
  15278. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15279. "Content-Length: " +
  15280. std::to_string(body.size()) + "\r\n\r\n" + body;
  15281. ASSERT_TRUE(send_request(1, req));
  15282. }
  15283. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15284. auto handled = false;
  15285. Server svr;
  15286. svr.Post("/test", [&](const Request &req, Response &) {
  15287. ASSERT_EQ(2u, req.form.fields.size());
  15288. const auto &text1 = req.form.get_field("text1");
  15289. ASSERT_EQ("text1", text1);
  15290. const auto &text2 = req.form.get_field("text2");
  15291. ASSERT_EQ("text2", text2);
  15292. handled = true;
  15293. });
  15294. thread t = thread([&] { svr.listen(HOST, PORT); });
  15295. auto se = detail::scope_exit([&] {
  15296. svr.stop();
  15297. t.join();
  15298. ASSERT_FALSE(svr.is_running());
  15299. ASSERT_TRUE(handled);
  15300. });
  15301. svr.wait_until_ready();
  15302. auto req = "POST /test HTTP/1.1\r\n"
  15303. "Host: localhost\r\n"
  15304. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15305. "Content-Length: 146\r\n"
  15306. "\r\n----------\r\n"
  15307. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15308. "\r\n"
  15309. "text1"
  15310. "\r\n----------\r\n"
  15311. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15312. "\r\n"
  15313. "text2"
  15314. "\r\n------------";
  15315. std::string response;
  15316. ASSERT_TRUE(send_request(1, req, &response));
  15317. ASSERT_EQ("200", response.substr(9, 3));
  15318. }
  15319. TEST(MultipartFormDataTest, ContentLength) {
  15320. auto handled = false;
  15321. Server svr;
  15322. svr.Post("/test", [&](const Request &req, Response &) {
  15323. ASSERT_EQ(2u, req.form.fields.size());
  15324. const auto &text1 = req.form.get_field("text1");
  15325. ASSERT_EQ("text1", text1);
  15326. const auto &text2 = req.form.get_field("text2");
  15327. ASSERT_EQ("text2", text2);
  15328. handled = true;
  15329. });
  15330. thread t = thread([&] { svr.listen(HOST, PORT); });
  15331. auto se = detail::scope_exit([&] {
  15332. svr.stop();
  15333. t.join();
  15334. ASSERT_FALSE(svr.is_running());
  15335. ASSERT_TRUE(handled);
  15336. });
  15337. svr.wait_until_ready();
  15338. auto req = "POST /test HTTP/1.1\r\n"
  15339. "Host: localhost\r\n"
  15340. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15341. "Content-Length: 167\r\n"
  15342. "\r\n----------\r\n"
  15343. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15344. "Content-Length: 5\r\n"
  15345. "\r\n"
  15346. "text1"
  15347. "\r\n----------\r\n"
  15348. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15349. "\r\n"
  15350. "text2"
  15351. "\r\n------------\r\n";
  15352. std::string response;
  15353. ASSERT_TRUE(send_request(1, req, &response));
  15354. ASSERT_EQ("200", response.substr(9, 3));
  15355. }
  15356. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15357. auto handled = false;
  15358. Server svr;
  15359. svr.Post("/test", [&](const Request &req, Response &) {
  15360. ASSERT_EQ(2u, req.form.fields.size());
  15361. const auto &text1 = req.form.get_field("text1");
  15362. ASSERT_EQ("text1", text1);
  15363. // TODO: Add header access for text fields if needed
  15364. const auto &text2 = req.form.get_field("text2");
  15365. ASSERT_EQ("text2", text2);
  15366. // TODO: Header access for text fields needs to be implemented
  15367. // auto &headers = it->second.headers;
  15368. // ASSERT_EQ(3U, headers.size());
  15369. // auto custom_header = headers.find("x-whatever");
  15370. // ASSERT_TRUE(custom_header != headers.end());
  15371. // ASSERT_NE("customvalue", custom_header->second);
  15372. // ASSERT_EQ("CustomValue", custom_header->second);
  15373. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15374. handled = true;
  15375. });
  15376. thread t = thread([&] { svr.listen(HOST, PORT); });
  15377. auto se = detail::scope_exit([&] {
  15378. svr.stop();
  15379. t.join();
  15380. ASSERT_FALSE(svr.is_running());
  15381. ASSERT_TRUE(handled);
  15382. });
  15383. svr.wait_until_ready();
  15384. auto req = "POST /test HTTP/1.1\r\n"
  15385. "Host: localhost\r\n"
  15386. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15387. "Content-Length: 232\r\n"
  15388. "\r\n----------\r\n"
  15389. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15390. "Content-Length: 5\r\n"
  15391. "X-Test: 1\r\n"
  15392. "\r\n"
  15393. "text1"
  15394. "\r\n----------\r\n"
  15395. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15396. "Content-Type: text/plain\r\n"
  15397. "X-Whatever: CustomValue\r\n"
  15398. "\r\n"
  15399. "text2"
  15400. "\r\n------------\r\n"
  15401. "That should be disregarded. Not even read";
  15402. std::string response;
  15403. ASSERT_TRUE(send_request(1, req, &response));
  15404. ASSERT_EQ("200", response.substr(9, 3));
  15405. }
  15406. TEST(MultipartFormDataTest, LargeHeader) {
  15407. auto handled = false;
  15408. Server svr;
  15409. svr.Post("/test", [&](const Request &req, Response &) {
  15410. ASSERT_EQ(1u, req.form.fields.size());
  15411. const auto &text = req.form.get_field("name1");
  15412. ASSERT_EQ("text1", text);
  15413. handled = true;
  15414. });
  15415. thread t = thread([&] { svr.listen(HOST, PORT); });
  15416. auto se = detail::scope_exit([&] {
  15417. svr.stop();
  15418. t.join();
  15419. ASSERT_FALSE(svr.is_running());
  15420. ASSERT_TRUE(handled);
  15421. });
  15422. svr.wait_until_ready();
  15423. auto boundary = std::string("cpp-httplib-multipart-data");
  15424. std::string content = "--" + boundary +
  15425. "\r\n"
  15426. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15427. "\r\n"
  15428. "text1\r\n"
  15429. "--" +
  15430. boundary + "--\r\n";
  15431. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15432. "Host: localhost\r\n"
  15433. "Content-Type: multipart/form-data;boundary=" +
  15434. boundary +
  15435. "\r\n"
  15436. "Content-Length: " +
  15437. std::to_string(content.size()) +
  15438. "\r\n"
  15439. "Dummy-Header: ";
  15440. std::string header_suffix = "\r\n"
  15441. "\r\n";
  15442. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15443. size_t header_dummy_size =
  15444. read_buff_size -
  15445. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15446. auto header_dummy = std::string(header_dummy_size, '@');
  15447. auto req = header_prefix + header_dummy + header_suffix + content;
  15448. std::string response;
  15449. ASSERT_TRUE(send_request(1, req, &response));
  15450. ASSERT_EQ("200", response.substr(9, 3));
  15451. }
  15452. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15453. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15454. // (not chunked Transfer-Encoding) after the streaming refactor.
  15455. auto handled = false;
  15456. Server svr;
  15457. svr.Post("/upload", [&](const Request &req, Response &res) {
  15458. auto cl_it = req.headers.find("Content-Length");
  15459. EXPECT_TRUE(cl_it != req.headers.end());
  15460. auto te_it = req.headers.find("Transfer-Encoding");
  15461. EXPECT_TRUE(te_it == req.headers.end());
  15462. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15463. res.set_content("ok", "text/plain");
  15464. handled = true;
  15465. });
  15466. auto port = svr.bind_to_any_port(HOST);
  15467. auto t = thread([&] { svr.listen_after_bind(); });
  15468. auto se = detail::scope_exit([&] {
  15469. svr.stop();
  15470. t.join();
  15471. ASSERT_FALSE(svr.is_running());
  15472. ASSERT_TRUE(handled);
  15473. });
  15474. svr.wait_until_ready();
  15475. UploadFormDataItems items = {
  15476. {"field1", "hello", "", "text/plain"},
  15477. {"file1", "world", "test.txt", "application/octet-stream"},
  15478. };
  15479. Client cli(HOST, port);
  15480. auto res = cli.Post("/upload", {}, items);
  15481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15482. EXPECT_EQ(StatusCode::OK_200, res->status);
  15483. }
  15484. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15485. // Verify that make_multipart_content_provider coalesces many small segments
  15486. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15487. constexpr size_t kItemCount = 1000;
  15488. UploadFormDataItems items;
  15489. items.reserve(kItemCount);
  15490. for (size_t i = 0; i < kItemCount; i++) {
  15491. items.push_back(
  15492. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15493. }
  15494. const std::string boundary = "----test-boundary";
  15495. auto content_length = detail::get_multipart_content_length(items, boundary);
  15496. auto provider = detail::make_multipart_content_provider(items, boundary);
  15497. // Drive the provider the same way write_content_with_progress does
  15498. size_t write_count = 0;
  15499. size_t total_bytes = 0;
  15500. DataSink sink;
  15501. size_t offset = 0;
  15502. sink.write = [&](const char *d, size_t l) -> bool {
  15503. (void)d;
  15504. write_count++;
  15505. total_bytes += l;
  15506. offset += l;
  15507. return true;
  15508. };
  15509. sink.is_writable = []() -> bool { return true; };
  15510. while (offset < content_length) {
  15511. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15512. }
  15513. EXPECT_EQ(content_length, total_bytes);
  15514. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15515. // With buffering into 64KB blocks, write_count should be much smaller.
  15516. auto segment_count = 3 * kItemCount + 1;
  15517. EXPECT_LT(write_count, segment_count / 10);
  15518. }
  15519. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15520. // Integration test: send many UploadFormDataItems and verify the server
  15521. // receives all of them correctly (#2410).
  15522. constexpr size_t kItemCount = 500;
  15523. auto handled = false;
  15524. Server svr;
  15525. svr.Post("/upload", [&](const Request &req, Response &res) {
  15526. EXPECT_EQ(kItemCount, req.form.fields.size());
  15527. for (size_t i = 0; i < kItemCount; i++) {
  15528. auto key = "field" + std::to_string(i);
  15529. auto val = "value" + std::to_string(i);
  15530. auto it = req.form.fields.find(key);
  15531. if (it != req.form.fields.end()) {
  15532. EXPECT_EQ(val, it->second.content);
  15533. } else {
  15534. ADD_FAILURE() << "Missing field: " << key;
  15535. }
  15536. }
  15537. res.set_content("ok", "text/plain");
  15538. handled = true;
  15539. });
  15540. auto port = svr.bind_to_any_port(HOST);
  15541. auto t = thread([&] { svr.listen_after_bind(); });
  15542. auto se = detail::scope_exit([&] {
  15543. svr.stop();
  15544. t.join();
  15545. ASSERT_FALSE(svr.is_running());
  15546. ASSERT_TRUE(handled);
  15547. });
  15548. svr.wait_until_ready();
  15549. UploadFormDataItems items;
  15550. items.reserve(kItemCount);
  15551. for (size_t i = 0; i < kItemCount; i++) {
  15552. items.push_back(
  15553. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15554. }
  15555. Client cli(HOST, port);
  15556. auto res = cli.Post("/upload", items);
  15557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15558. EXPECT_EQ(StatusCode::OK_200, res->status);
  15559. }
  15560. TEST(MultipartFormDataTest, MakeFileProvider) {
  15561. // Verify make_file_provider sends a file's contents correctly.
  15562. const std::string file_content(4096, 'Z');
  15563. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15564. {
  15565. std::ofstream ofs(tmp_path, std::ios::binary);
  15566. ofs.write(file_content.data(),
  15567. static_cast<std::streamsize>(file_content.size()));
  15568. }
  15569. auto handled = false;
  15570. Server svr;
  15571. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15572. const ContentReader &content_reader) {
  15573. ASSERT_TRUE(req.is_multipart_form_data());
  15574. std::vector<FormData> items;
  15575. content_reader(
  15576. [&](const FormData &file) {
  15577. items.push_back(file);
  15578. return true;
  15579. },
  15580. [&](const char *data, size_t data_length) {
  15581. items.back().content.append(data, data_length);
  15582. return true;
  15583. });
  15584. ASSERT_EQ(1u, items.size());
  15585. EXPECT_EQ("myfile", items[0].name);
  15586. EXPECT_EQ("data.bin", items[0].filename);
  15587. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15588. EXPECT_EQ(file_content, items[0].content);
  15589. handled = true;
  15590. });
  15591. auto port = svr.bind_to_any_port(HOST);
  15592. auto t = thread([&] { svr.listen_after_bind(); });
  15593. auto se = detail::scope_exit([&] {
  15594. svr.stop();
  15595. t.join();
  15596. ASSERT_FALSE(svr.is_running());
  15597. ASSERT_TRUE(handled);
  15598. std::remove(tmp_path.c_str());
  15599. });
  15600. svr.wait_until_ready();
  15601. FormDataProviderItems providers;
  15602. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15603. "application/octet-stream"));
  15604. Client cli(HOST, port);
  15605. auto res = cli.Post("/upload", {}, {}, providers);
  15606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15607. EXPECT_EQ(StatusCode::OK_200, res->status);
  15608. }
  15609. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15610. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15611. // (100) headers is rejected with a 400 Bad Request response.
  15612. Server svr;
  15613. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15614. res.set_content("ok", "text/plain");
  15615. });
  15616. thread t = thread([&] { svr.listen(HOST, PORT); });
  15617. auto se = detail::scope_exit([&] {
  15618. svr.stop();
  15619. t.join();
  15620. ASSERT_FALSE(svr.is_running());
  15621. });
  15622. svr.wait_until_ready();
  15623. // Build a multipart part with 101 custom headers (exceeding
  15624. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15625. std::stringstream body;
  15626. body << "--simpleboundary\r\n"
  15627. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15628. for (int i = 0; i < 101; i++) {
  15629. body << "X-Custom-Header-" << i << ": value\r\n";
  15630. }
  15631. body << "\r\n"
  15632. << "value1\r\n"
  15633. << "--simpleboundary--\r\n";
  15634. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15635. Client cli(HOST, PORT);
  15636. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15638. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15639. }
  15640. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15641. // A body that never contains the declared boundary must not be accumulated
  15642. // while the parser waits for it. Buffering it would also make every read
  15643. // rescan everything seen so far, which is quadratic in the body size.
  15644. Server svr;
  15645. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15646. res.set_content("ok", "text/plain");
  15647. });
  15648. auto port = svr.bind_to_any_port(HOST);
  15649. thread t = thread([&] { svr.listen_after_bind(); });
  15650. auto se = detail::scope_exit([&] {
  15651. svr.stop();
  15652. t.join();
  15653. ASSERT_FALSE(svr.is_running());
  15654. });
  15655. svr.wait_until_ready();
  15656. Client cli(HOST, port);
  15657. cli.set_read_timeout(60, 0);
  15658. cli.set_write_timeout(60, 0);
  15659. // '-' is the worst case: it matches the first character of the boundary, so
  15660. // every position has to be checked against it.
  15661. auto post_dashes = [&](size_t size) {
  15662. const std::string body(size, '-');
  15663. auto start = std::chrono::steady_clock::now();
  15664. auto res =
  15665. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15666. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15667. std::chrono::steady_clock::now() - start)
  15668. .count();
  15669. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15670. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15671. return ms;
  15672. };
  15673. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15674. // Windows.
  15675. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15676. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15677. // Comparing the two sizes rather than checking an absolute duration keeps
  15678. // this meaningful across build types and CI load, both of which move the
  15679. // absolute numbers by more than an order of magnitude. Four times the bytes
  15680. // costs about four times the time when parsing is linear, and about sixteen
  15681. // times when the body is buffered and rescanned.
  15682. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15683. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15684. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15685. << "ms, which suggests the body is being buffered and rescanned";
  15686. }
  15687. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15688. // A boundary can only be followed by CRLF or by "--", so anything else is
  15689. // malformed no matter what comes next. The parser must say so right away
  15690. // instead of buffering the rest of the declared body.
  15691. Server svr;
  15692. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15693. res.set_content("ok", "text/plain");
  15694. });
  15695. auto port = svr.bind_to_any_port(HOST);
  15696. thread t = thread([&] { svr.listen_after_bind(); });
  15697. auto se = detail::scope_exit([&] {
  15698. svr.stop();
  15699. t.join();
  15700. ASSERT_FALSE(svr.is_running());
  15701. });
  15702. svr.wait_until_ready();
  15703. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15704. // buffers instead of failing would still be waiting for the remaining bytes.
  15705. const std::string body = "--zzzz\r\n"
  15706. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15707. "\r\n"
  15708. "text1"
  15709. "\r\n--zzzzXX";
  15710. const std::string req = "POST /post HTTP/1.1\r\n"
  15711. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15712. "Content-Length: 1048576\r\n"
  15713. "\r\n" +
  15714. body;
  15715. std::string response;
  15716. ASSERT_TRUE(send_request(3, req, &response, port));
  15717. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15718. EXPECT_EQ("400", response.substr(9, 3));
  15719. }
  15720. // Posts a multipart body split into two writes, so that the server sees the
  15721. // split at whatever offset the caller chose, and expects the single "text1"
  15722. // field to come through.
  15723. static void expect_split_multipart_ok(const std::string &body1,
  15724. const std::string &body2) {
  15725. auto handled = false;
  15726. Server svr;
  15727. svr.Post("/post", [&](const Request &req, Response &) {
  15728. EXPECT_EQ(1u, req.form.fields.size());
  15729. EXPECT_EQ("text1", req.form.get_field("text1"));
  15730. handled = true;
  15731. });
  15732. auto port = svr.bind_to_any_port(HOST);
  15733. thread t = thread([&] { svr.listen_after_bind(); });
  15734. auto se = detail::scope_exit([&] {
  15735. svr.stop();
  15736. t.join();
  15737. ASSERT_FALSE(svr.is_running());
  15738. ASSERT_TRUE(handled);
  15739. });
  15740. svr.wait_until_ready();
  15741. // "Connection: close" makes the server close once it has answered, so the
  15742. // response drain ends immediately instead of idling until the read timeout.
  15743. const std::string head =
  15744. "POST /post HTTP/1.1\r\n"
  15745. "Host: localhost\r\n"
  15746. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15747. "Connection: close\r\n"
  15748. "Content-Length: " +
  15749. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15750. std::string response;
  15751. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15752. ASSERT_GE(response.size(), 12u) << "no response";
  15753. EXPECT_EQ("200", response.substr(9, 3));
  15754. }
  15755. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15756. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15757. // ignored, including when it does not arrive in the same read as the
  15758. // close-delimiter itself.
  15759. expect_split_multipart_ok("--zzzz\r\n"
  15760. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15761. "\r\n"
  15762. "text1"
  15763. "\r\n--zzzz--",
  15764. "\r\nthis epilogue must be ignored\r\n");
  15765. }
  15766. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15767. // The initial boundary may be preceded by a preamble of any length and may
  15768. // straddle a read boundary. Discarding data while waiting for it must not
  15769. // throw away a partial boundary sitting at the end of the buffer.
  15770. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15771. "zz\r\n"
  15772. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15773. "\r\n"
  15774. "text1"
  15775. "\r\n--zzzz--\r\n");
  15776. }
  15777. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15778. // The received boundary was only checked for being non-empty, so it could be
  15779. // as long as a header is allowed to be. The parser scans the body for
  15780. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15781. // costs a nearly full comparison at nearly every position, making the
  15782. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15783. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15784. Server svr;
  15785. svr.Post("/post", [](const Request &req, Response &res) {
  15786. EXPECT_EQ(1u, req.form.fields.size());
  15787. EXPECT_EQ("text1", req.form.get_field("text1"));
  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. Client cli(HOST, port);
  15799. auto post_with_boundary_of_length = [&](size_t len) {
  15800. const std::string boundary(len, 'a');
  15801. const std::string body =
  15802. "--" + boundary +
  15803. "\r\n"
  15804. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15805. "\r\n"
  15806. "text1"
  15807. "\r\n--" +
  15808. boundary + "--\r\n";
  15809. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15810. };
  15811. auto res = post_with_boundary_of_length(70);
  15812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15813. EXPECT_EQ(StatusCode::OK_200, res->status);
  15814. res = post_with_boundary_of_length(71);
  15815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15816. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15817. }
  15818. TEST(MakeFileBodyTest, Basic) {
  15819. const std::string file_content(4096, 'Z');
  15820. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15821. {
  15822. std::ofstream ofs(tmp_path, std::ios::binary);
  15823. ofs.write(file_content.data(),
  15824. static_cast<std::streamsize>(file_content.size()));
  15825. }
  15826. auto handled = false;
  15827. Server svr;
  15828. svr.Post("/upload", [&](const Request &req, Response &res) {
  15829. EXPECT_EQ(file_content, req.body);
  15830. handled = true;
  15831. res.status = StatusCode::OK_200;
  15832. });
  15833. auto port = svr.bind_to_any_port(HOST);
  15834. auto t = thread([&] { svr.listen_after_bind(); });
  15835. auto se = detail::scope_exit([&] {
  15836. svr.stop();
  15837. t.join();
  15838. ASSERT_FALSE(svr.is_running());
  15839. ASSERT_TRUE(handled);
  15840. std::remove(tmp_path.c_str());
  15841. });
  15842. svr.wait_until_ready();
  15843. auto fb = make_file_body(tmp_path);
  15844. ASSERT_GT(fb.first, 0u);
  15845. Client cli(HOST, port);
  15846. auto res =
  15847. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15849. EXPECT_EQ(StatusCode::OK_200, res->status);
  15850. }
  15851. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15852. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15853. {
  15854. std::ofstream ofs(path, std::ios::binary);
  15855. const std::string content(100, 'A');
  15856. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15857. }
  15858. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15859. auto body = make_file_body(path);
  15860. ASSERT_EQ(100u, body.first);
  15861. ASSERT_TRUE(static_cast<bool>(body.second));
  15862. // Rewritten shorter after its length was measured - and, on a server, after
  15863. // that length has already gone out as Content-Length.
  15864. {
  15865. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15866. const std::string content(10, 'A');
  15867. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15868. }
  15869. std::string written;
  15870. DataSink sink;
  15871. sink.write = [&](const char *d, size_t l) {
  15872. written.append(d, l);
  15873. return true;
  15874. };
  15875. // The provider has to report failure. write_content_with_progress() advances
  15876. // its offset only by what was written, so a provider that returns true
  15877. // without completing the length it promised is called again straight away,
  15878. // and again.
  15879. EXPECT_FALSE(body.second(0, body.first, sink));
  15880. EXPECT_EQ(std::string(10, 'A'), written);
  15881. }
  15882. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15883. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15884. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15885. {
  15886. std::ofstream ofs(path, std::ios::binary);
  15887. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15888. }
  15889. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15890. auto body = make_file_body(path);
  15891. ASSERT_EQ(content.size(), body.first);
  15892. ASSERT_TRUE(static_cast<bool>(body.second));
  15893. std::string written;
  15894. DataSink sink;
  15895. sink.write = [&](const char *d, size_t l) {
  15896. written.append(d, l);
  15897. return true;
  15898. };
  15899. EXPECT_TRUE(body.second(0, body.first, sink));
  15900. EXPECT_EQ(content, written);
  15901. }
  15902. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15903. static constexpr unsigned int number_of_tasks{1000000};
  15904. std::atomic_uint count{0};
  15905. std::unique_ptr<TaskQueue> task_queue{
  15906. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15907. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15908. auto queued = task_queue->enqueue(
  15909. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15910. EXPECT_TRUE(queued);
  15911. }
  15912. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15913. task_queue->shutdown();
  15914. #else
  15915. EXPECT_NO_THROW(task_queue->shutdown());
  15916. #endif
  15917. EXPECT_EQ(number_of_tasks, count.load());
  15918. }
  15919. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15920. static constexpr unsigned int number_of_tasks{1000000};
  15921. static constexpr unsigned int qlimit{2};
  15922. unsigned int queued_count{0};
  15923. std::atomic_uint count{0};
  15924. std::unique_ptr<TaskQueue> task_queue{
  15925. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15926. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15927. if (task_queue->enqueue(
  15928. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15929. queued_count++;
  15930. }
  15931. }
  15932. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15933. task_queue->shutdown();
  15934. #else
  15935. EXPECT_NO_THROW(task_queue->shutdown());
  15936. #endif
  15937. EXPECT_EQ(queued_count, count.load());
  15938. EXPECT_TRUE(queued_count <= number_of_tasks);
  15939. EXPECT_TRUE(queued_count >= qlimit);
  15940. }
  15941. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15942. // Use a short idle timeout so a dynamic thread spawns, times out and
  15943. // exits during the test, and the pool keeps working afterwards.
  15944. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15945. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15946. /*idle_timeout_sec=*/1}};
  15947. std::atomic_uint count{0};
  15948. std::condition_variable cv;
  15949. std::mutex mtx;
  15950. bool release = false;
  15951. // Block the base thread so the second task spawns a dynamic thread.
  15952. EXPECT_TRUE(task_queue->enqueue([&] {
  15953. std::unique_lock<std::mutex> lock(mtx);
  15954. while (!release) {
  15955. cv.wait(lock);
  15956. }
  15957. count++;
  15958. }));
  15959. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15960. // Let the dynamic thread finish its task and exceed the idle timeout.
  15961. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15962. {
  15963. std::unique_lock<std::mutex> lock(mtx);
  15964. release = true;
  15965. }
  15966. cv.notify_all();
  15967. // The pool must still accept and run tasks after the dynamic thread exited.
  15968. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15969. task_queue->shutdown();
  15970. EXPECT_EQ(3u, count.load());
  15971. }
  15972. TEST(TaskQueueTest, MaxQueuedRequests) {
  15973. static constexpr unsigned int qlimit{3};
  15974. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15975. std::condition_variable sem_cv;
  15976. std::mutex sem_mtx;
  15977. int credits = 0;
  15978. bool queued;
  15979. /* Fill up the queue with tasks that will block until we give them credits to
  15980. * complete. */
  15981. for (unsigned int n = 0; n <= qlimit;) {
  15982. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15983. std::unique_lock<std::mutex> lock(sem_mtx);
  15984. while (credits <= 0) {
  15985. sem_cv.wait(lock);
  15986. }
  15987. /* Consume the credit and signal the test code if they are all gone. */
  15988. if (--credits == 0) { sem_cv.notify_one(); }
  15989. });
  15990. if (n < qlimit) {
  15991. /* The first qlimit enqueues must succeed. */
  15992. EXPECT_TRUE(queued);
  15993. } else {
  15994. /* The last one will succeed only when the worker thread
  15995. * starts and dequeues the first blocking task. Although
  15996. * not necessary for the correctness of this test, we sleep for
  15997. * a short while to avoid busy waiting. */
  15998. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15999. }
  16000. if (queued) { n++; }
  16001. }
  16002. /* Further enqueues must fail since the queue is full. */
  16003. for (auto i = 0; i < 4; i++) {
  16004. queued = task_queue->enqueue([] {});
  16005. EXPECT_FALSE(queued);
  16006. }
  16007. /* Give the credits to allow the previous tasks to complete. */
  16008. {
  16009. std::unique_lock<std::mutex> lock(sem_mtx);
  16010. credits += qlimit + 1;
  16011. }
  16012. sem_cv.notify_all();
  16013. /* Wait for all the credits to be consumed. */
  16014. {
  16015. std::unique_lock<std::mutex> lock(sem_mtx);
  16016. while (credits > 0) {
  16017. sem_cv.wait(lock);
  16018. }
  16019. }
  16020. /* Check that we are able again to enqueue at least qlimit tasks. */
  16021. for (unsigned int i = 0; i < qlimit; i++) {
  16022. queued = task_queue->enqueue([] {});
  16023. EXPECT_TRUE(queued);
  16024. }
  16025. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16026. task_queue->shutdown();
  16027. #else
  16028. EXPECT_NO_THROW(task_queue->shutdown());
  16029. #endif
  16030. }
  16031. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16032. Server svr;
  16033. std::string method;
  16034. std::string body;
  16035. auto has_content_length = false;
  16036. auto has_transfer_encoding = false;
  16037. std::atomic<int> bad_requests{0};
  16038. // Leftover body bytes get parsed as a malformed request and answered with
  16039. // 400
  16040. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16041. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16042. });
  16043. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16044. res.set_redirect("/down", StatusCode::SeeOther_303);
  16045. });
  16046. svr.Get("/down", [&](const Request &req, Response &res) {
  16047. method = req.method;
  16048. body = req.body;
  16049. has_content_length = req.has_header("Content-Length");
  16050. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16051. res.set_content("ok", "text/plain");
  16052. });
  16053. auto port = svr.bind_to_any_port(HOST);
  16054. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16055. auto se = detail::scope_exit([&] {
  16056. svr.stop();
  16057. thread.join();
  16058. ASSERT_FALSE(svr.is_running());
  16059. });
  16060. svr.wait_until_ready();
  16061. const std::string payload = "SECRET-BODY";
  16062. auto check = [&](Client &cli, const Result &res) {
  16063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16064. EXPECT_EQ(StatusCode::OK_200, res->status);
  16065. EXPECT_EQ("ok", res->body);
  16066. EXPECT_EQ("GET", method);
  16067. EXPECT_TRUE(body.empty());
  16068. EXPECT_FALSE(has_content_length);
  16069. EXPECT_FALSE(has_transfer_encoding);
  16070. // Nothing of the original body may be left on the connection
  16071. auto res2 = cli.Get("/down");
  16072. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16073. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16074. EXPECT_EQ("ok", res2->body);
  16075. EXPECT_EQ(0, bad_requests);
  16076. };
  16077. // With content length
  16078. {
  16079. Client cli(HOST, port);
  16080. cli.set_keep_alive(true);
  16081. cli.set_follow_location(true);
  16082. auto res = cli.Post(
  16083. "/up", payload.size(),
  16084. [&](size_t offset, size_t length, DataSink &sink) {
  16085. return sink.write(payload.data() + offset, length);
  16086. },
  16087. "text/plain");
  16088. check(cli, res);
  16089. }
  16090. // Without content length (chunked)
  16091. {
  16092. Client cli(HOST, port);
  16093. cli.set_keep_alive(true);
  16094. cli.set_follow_location(true);
  16095. auto res = cli.Post(
  16096. "/up",
  16097. [&](size_t /*offset*/, DataSink &sink) {
  16098. sink.write(payload.data(), payload.size());
  16099. sink.done();
  16100. return true;
  16101. },
  16102. "text/plain");
  16103. check(cli, res);
  16104. }
  16105. }
  16106. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16107. Server svr;
  16108. std::string target;
  16109. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16110. // Echo the still-encoded name back in the Location
  16111. const std::string prefix = "/start/";
  16112. res.status = StatusCode::Found_302;
  16113. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16114. });
  16115. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16116. target = req.target;
  16117. res.set_content("ok", "text/plain");
  16118. });
  16119. auto port = svr.bind_to_any_port(HOST);
  16120. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16121. auto se = detail::scope_exit([&] {
  16122. svr.stop();
  16123. thread.join();
  16124. ASSERT_FALSE(svr.is_running());
  16125. });
  16126. svr.wait_until_ready();
  16127. // Decoding the Location path would turn the first four into a path
  16128. // separator, a query delimiter, a fragment delimiter and a different
  16129. // percent-encoded octet. The rest must keep reaching the server as they are.
  16130. const std::vector<std::string> names = {
  16131. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16132. };
  16133. for (auto path_encode : {true, false}) {
  16134. Client cli(HOST, port);
  16135. cli.set_follow_location(true);
  16136. cli.set_path_encode(path_encode);
  16137. for (const auto &name : names) {
  16138. target.clear();
  16139. auto res = cli.Get("/start/" + name);
  16140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16141. EXPECT_EQ(StatusCode::OK_200, res->status);
  16142. EXPECT_EQ("/dest/" + name, target);
  16143. }
  16144. }
  16145. }
  16146. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16147. Server svr;
  16148. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16149. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16150. });
  16151. svr.Get("/hello", [](const Request &req, Response &res) {
  16152. res.set_content(req.get_param_value("key"), "text/plain");
  16153. });
  16154. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16155. auto se = detail::scope_exit([&] {
  16156. svr.stop();
  16157. thread.join();
  16158. ASSERT_FALSE(svr.is_running());
  16159. });
  16160. svr.wait_until_ready();
  16161. {
  16162. Client cli(HOST, PORT);
  16163. cli.set_follow_location(true);
  16164. auto res = cli.Get("/");
  16165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16166. EXPECT_EQ(StatusCode::OK_200, res->status);
  16167. EXPECT_EQ("val&key2=val2", res->body);
  16168. }
  16169. }
  16170. #endif
  16171. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16172. Server svr;
  16173. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16174. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16175. });
  16176. svr.Get("/hello", [](const Request &req, Response &res) {
  16177. res.set_content(req.get_param_value("key"), "text/plain");
  16178. });
  16179. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16180. auto se = detail::scope_exit([&] {
  16181. svr.stop();
  16182. thread.join();
  16183. ASSERT_FALSE(svr.is_running());
  16184. });
  16185. svr.wait_until_ready();
  16186. {
  16187. Client cli(HOST, PORT);
  16188. cli.set_follow_location(true);
  16189. auto res = cli.Get("/");
  16190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16191. EXPECT_EQ(StatusCode::OK_200, res->status);
  16192. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16193. }
  16194. }
  16195. TEST(RedirectTest, RedirectWithPlusInPath) {
  16196. Server svr;
  16197. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16198. res.set_redirect("/a+b");
  16199. });
  16200. // Route pattern uses regex; escape + as \\+
  16201. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16202. res.set_content(req.path, "text/plain");
  16203. });
  16204. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16205. auto se = detail::scope_exit([&] {
  16206. svr.stop();
  16207. thread.join();
  16208. ASSERT_FALSE(svr.is_running());
  16209. });
  16210. svr.wait_until_ready();
  16211. {
  16212. Client cli(HOST, PORT);
  16213. cli.set_follow_location(true);
  16214. auto res = cli.Get("/");
  16215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16216. EXPECT_EQ(StatusCode::OK_200, res->status);
  16217. EXPECT_EQ("/a+b", res->body);
  16218. }
  16219. }
  16220. TEST(RedirectTest, ResolveRelativeLocation) {
  16221. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16222. const std::vector<std::pair<std::string, std::string>> cases = {
  16223. {"g", "/b/c/g"},
  16224. {"./g", "/b/c/g"},
  16225. {"g/", "/b/c/g/"},
  16226. {"?y", "/b/c/d;p?y"},
  16227. {"g?y", "/b/c/g?y"},
  16228. {"#s", "/b/c/d;p?q#s"},
  16229. {"g#s", "/b/c/g#s"},
  16230. {"g?y#s", "/b/c/g?y#s"},
  16231. {";x", "/b/c/;x"},
  16232. {"g;x", "/b/c/g;x"},
  16233. {".", "/b/c/"},
  16234. {"./", "/b/c/"},
  16235. {"..", "/b/"},
  16236. {"../", "/b/"},
  16237. {"../g", "/b/g"},
  16238. {"../..", "/"},
  16239. {"../../", "/"},
  16240. {"../../g", "/g"},
  16241. {"../../../g", "/g"},
  16242. {"g.", "/b/c/g."},
  16243. {".g", "/b/c/.g"},
  16244. {"g..", "/b/c/g.."},
  16245. {"..g", "/b/c/..g"},
  16246. {"./../g", "/b/g"},
  16247. {"./g/.", "/b/c/g/"},
  16248. {"g/./h", "/b/c/g/h"},
  16249. {"g/../h", "/b/c/h"},
  16250. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16251. {"g;x=1/../y", "/b/c/y"},
  16252. {"g?y/./x", "/b/c/g?y/./x"},
  16253. {"g#s/../x", "/b/c/g#s/../x"},
  16254. // Not relative-path references, so left for parse_url.
  16255. {"/g", "/g"},
  16256. {"//g", "//g"},
  16257. {"http://g/x", "http://g/x"},
  16258. {"g:h", "g:h"},
  16259. };
  16260. for (const auto &c : cases) {
  16261. EXPECT_EQ(c.second,
  16262. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16263. << c.first;
  16264. }
  16265. }
  16266. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16267. Server svr;
  16268. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16269. res.set_redirect(req.get_param_value("to"));
  16270. });
  16271. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16272. res.set_content(req.target, "text/plain");
  16273. });
  16274. svr.Get("/other", [](const Request &req, Response &res) {
  16275. res.set_content(req.target, "text/plain");
  16276. });
  16277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16278. auto se = detail::scope_exit([&] {
  16279. svr.stop();
  16280. thread.join();
  16281. ASSERT_FALSE(svr.is_running());
  16282. });
  16283. svr.wait_until_ready();
  16284. const std::vector<std::pair<std::string, std::string>> cases = {
  16285. {"next", "/dir/next"},
  16286. {"./next?x=1", "/dir/next?x=1"},
  16287. {"../other", "/other"},
  16288. };
  16289. for (const auto &c : cases) {
  16290. Client cli(HOST, PORT);
  16291. cli.set_follow_location(true);
  16292. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16293. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16294. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16295. EXPECT_EQ(c.second, res->body) << c.first;
  16296. }
  16297. }
  16298. #ifdef CPPHTTPLIB_SSL_ENABLED
  16299. TEST(RedirectTest, Issue2185_Online) {
  16300. SSLClient client("github.com");
  16301. client.set_follow_location(true);
  16302. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16303. "Coollab-Windows.zip");
  16304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16305. EXPECT_EQ(StatusCode::OK_200, res->status);
  16306. EXPECT_EQ(9920427U, res->body.size());
  16307. }
  16308. #endif
  16309. TEST(VulnerabilityTest, CRLFInjection) {
  16310. Server svr;
  16311. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16312. res.set_content("Hello 1", "text/plain");
  16313. });
  16314. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16315. res.set_content("Hello 2", "text/plain");
  16316. });
  16317. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16318. res.set_content("Hello 3", "text/plain");
  16319. });
  16320. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16321. res.set_content("Hello 4", "text/plain");
  16322. });
  16323. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16324. for (const auto &x : req.headers) {
  16325. auto key = x.first;
  16326. EXPECT_STRNE("evil", key.c_str());
  16327. }
  16328. });
  16329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16330. auto se = detail::scope_exit([&] {
  16331. svr.stop();
  16332. thread.join();
  16333. ASSERT_FALSE(svr.is_running());
  16334. });
  16335. svr.wait_until_ready();
  16336. {
  16337. Client cli(HOST, PORT);
  16338. cli.Post("/test1", "A=B",
  16339. "application/x-www-form-urlencoded\r\nevil: hello1");
  16340. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16341. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16342. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16343. }
  16344. }
  16345. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16346. auto server_thread = std::thread([] {
  16347. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16348. default_socket_options(srv);
  16349. sockaddr_in addr{};
  16350. addr.sin_family = AF_INET;
  16351. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16352. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16353. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16354. ::listen(srv, 1);
  16355. sockaddr_in cli_addr{};
  16356. socklen_t cli_len = sizeof(cli_addr);
  16357. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16358. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16359. std::string buf_all;
  16360. char buf[2048];
  16361. ssize_t n;
  16362. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16363. buf_all.append(buf, static_cast<size_t>(n));
  16364. size_t pos;
  16365. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16366. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16367. auto e = request_block.find("\r\n");
  16368. if (e != std::string::npos) {
  16369. auto request_line = request_block.substr(0, e);
  16370. std::string msg =
  16371. "CRLF injection detected in request line: '" + request_line + "'";
  16372. EXPECT_FALSE(true) << msg;
  16373. }
  16374. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16375. ::send(cli,
  16376. #ifdef _WIN32
  16377. static_cast<const char *>(resp.c_str()),
  16378. static_cast<int>(resp.size()),
  16379. #else
  16380. resp.c_str(), resp.size(),
  16381. #endif
  16382. 0);
  16383. buf_all.erase(0, pos + 4);
  16384. }
  16385. }
  16386. detail::close_socket(cli);
  16387. detail::close_socket(srv);
  16388. });
  16389. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16390. auto cli = Client("127.0.0.1", PORT + 1);
  16391. auto headers = Headers{
  16392. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16393. {"Connection", "keep-alive"}};
  16394. auto res = cli.Get("/hi", headers);
  16395. EXPECT_FALSE(res);
  16396. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16397. server_thread.join();
  16398. }
  16399. // A request rejected before any byte reaches the socket must fail right away
  16400. // instead of waiting for a response the server will never send.
  16401. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16402. // The kernel completes the TCP handshake from the listen backlog, so the
  16403. // client connects, but nothing ever reads, responds or closes.
  16404. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16405. default_socket_options(srv);
  16406. sockaddr_in addr{};
  16407. addr.sin_family = AF_INET;
  16408. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16409. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16410. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16411. ASSERT_EQ(0, ::listen(srv, 8));
  16412. auto cli = Client("127.0.0.1", PORT + 1);
  16413. cli.set_read_timeout(10, 0);
  16414. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16415. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16416. std::chrono::steady_clock::now() - start)
  16417. .count();
  16418. };
  16419. {
  16420. Request req;
  16421. req.method = "GE T";
  16422. req.path = "/";
  16423. auto start = std::chrono::steady_clock::now();
  16424. auto res = cli.send(req);
  16425. EXPECT_FALSE(res);
  16426. EXPECT_EQ(Error::Write, res.error());
  16427. EXPECT_LT(elapsed_ms(start), 1000);
  16428. }
  16429. {
  16430. auto start = std::chrono::steady_clock::now();
  16431. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16432. EXPECT_FALSE(res);
  16433. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16434. EXPECT_LT(elapsed_ms(start), 1000);
  16435. }
  16436. EXPECT_FALSE(cli.is_socket_open());
  16437. detail::close_socket(srv);
  16438. }
  16439. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16440. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16441. default_socket_options(srv);
  16442. sockaddr_in addr{};
  16443. addr.sin_family = AF_INET;
  16444. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16445. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16446. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16447. ASSERT_EQ(0, ::listen(srv, 1));
  16448. std::string received;
  16449. auto server_thread = std::thread([&] {
  16450. auto sock = ::accept(srv, nullptr, nullptr);
  16451. if (sock == INVALID_SOCKET) { return; }
  16452. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16453. char buf[2048];
  16454. ssize_t n;
  16455. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16456. received.append(buf, static_cast<size_t>(n));
  16457. }
  16458. detail::close_socket(sock);
  16459. });
  16460. {
  16461. auto cli = Client("127.0.0.1", PORT + 1);
  16462. // "Z" sorts after the default headers, so writing straight to the socket
  16463. // would have sent the request line and those headers before the rejection.
  16464. auto handle =
  16465. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16466. EXPECT_FALSE(handle.is_valid());
  16467. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16468. }
  16469. server_thread.join();
  16470. detail::close_socket(srv);
  16471. EXPECT_TRUE(received.empty()) << received;
  16472. }
  16473. TEST(PathParamsTest, StaticMatch) {
  16474. const auto pattern = "/users/all";
  16475. detail::PathParamsMatcher matcher(pattern);
  16476. Request request;
  16477. request.path = "/users/all";
  16478. ASSERT_TRUE(matcher.match(request));
  16479. std::unordered_map<std::string, std::string> expected_params = {};
  16480. EXPECT_EQ(request.path_params, expected_params);
  16481. }
  16482. TEST(PathParamsTest, StaticMismatch) {
  16483. const auto pattern = "/users/all";
  16484. detail::PathParamsMatcher matcher(pattern);
  16485. Request request;
  16486. request.path = "/users/1";
  16487. ASSERT_FALSE(matcher.match(request));
  16488. }
  16489. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16490. const auto pattern = "/users/:id/subscriptions";
  16491. detail::PathParamsMatcher matcher(pattern);
  16492. Request request;
  16493. request.path = "/users/42/subscriptions";
  16494. ASSERT_TRUE(matcher.match(request));
  16495. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16496. EXPECT_EQ(request.path_params, expected_params);
  16497. }
  16498. TEST(PathParamsTest, SingleParamInTheEnd) {
  16499. const auto pattern = "/users/:id";
  16500. detail::PathParamsMatcher matcher(pattern);
  16501. Request request;
  16502. request.path = "/users/24";
  16503. ASSERT_TRUE(matcher.match(request));
  16504. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16505. EXPECT_EQ(request.path_params, expected_params);
  16506. }
  16507. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16508. const auto pattern = "/users/:id/";
  16509. detail::PathParamsMatcher matcher(pattern);
  16510. Request request;
  16511. request.path = "/users/42/";
  16512. ASSERT_TRUE(matcher.match(request));
  16513. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16514. EXPECT_EQ(request.path_params, expected_params);
  16515. }
  16516. TEST(PathParamsTest, EmptyParam) {
  16517. const auto pattern = "/users/:id/";
  16518. detail::PathParamsMatcher matcher(pattern);
  16519. Request request;
  16520. request.path = "/users//";
  16521. ASSERT_TRUE(matcher.match(request));
  16522. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16523. EXPECT_EQ(request.path_params, expected_params);
  16524. }
  16525. TEST(PathParamsTest, FragmentMismatch) {
  16526. const auto pattern = "/users/:id/";
  16527. detail::PathParamsMatcher matcher(pattern);
  16528. Request request;
  16529. request.path = "/admins/24/";
  16530. ASSERT_FALSE(matcher.match(request));
  16531. }
  16532. TEST(PathParamsTest, ExtraFragments) {
  16533. const auto pattern = "/users/:id";
  16534. detail::PathParamsMatcher matcher(pattern);
  16535. Request request;
  16536. request.path = "/users/42/subscriptions";
  16537. ASSERT_FALSE(matcher.match(request));
  16538. }
  16539. TEST(PathParamsTest, MissingTrailingParam) {
  16540. const auto pattern = "/users/:id";
  16541. detail::PathParamsMatcher matcher(pattern);
  16542. Request request;
  16543. request.path = "/users";
  16544. ASSERT_FALSE(matcher.match(request));
  16545. }
  16546. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16547. const auto pattern = "/users/:id/subscriptions";
  16548. detail::PathParamsMatcher matcher(pattern);
  16549. Request request;
  16550. request.path = "/users/subscriptions";
  16551. ASSERT_FALSE(matcher.match(request));
  16552. }
  16553. TEST(PathParamsTest, MultipleParams) {
  16554. const auto pattern = "/users/:userid/subscriptions/:subid";
  16555. detail::PathParamsMatcher matcher(pattern);
  16556. Request request;
  16557. request.path = "/users/42/subscriptions/2";
  16558. ASSERT_TRUE(matcher.match(request));
  16559. std::unordered_map<std::string, std::string> expected_params = {
  16560. {"userid", "42"}, {"subid", "2"}};
  16561. EXPECT_EQ(request.path_params, expected_params);
  16562. }
  16563. TEST(PathParamsTest, SequenceOfParams) {
  16564. const auto pattern = "/values/:x/:y/:z";
  16565. detail::PathParamsMatcher matcher(pattern);
  16566. Request request;
  16567. request.path = "/values/1/2/3";
  16568. ASSERT_TRUE(matcher.match(request));
  16569. std::unordered_map<std::string, std::string> expected_params = {
  16570. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16571. EXPECT_EQ(request.path_params, expected_params);
  16572. }
  16573. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16574. const auto pattern = "/prefix:suffix";
  16575. detail::PathParamsMatcher matcher(pattern);
  16576. Request request;
  16577. request.path = "/prefix:suffix";
  16578. ASSERT_TRUE(matcher.match(request));
  16579. const std::unordered_map<std::string, std::string> expected_params = {};
  16580. EXPECT_EQ(request.path_params, expected_params);
  16581. }
  16582. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16583. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16584. // calling thread's stack on a long enough path for a quantified pattern;
  16585. // RegexMatcher must refuse to run regex matching on paths beyond
  16586. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16587. detail::RegexMatcher matcher("/files/(.*)");
  16588. Request within_limit;
  16589. within_limit.path = "/files/" + std::string(10, 'A');
  16590. EXPECT_TRUE(matcher.match(within_limit));
  16591. Request over_limit;
  16592. over_limit.path =
  16593. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16594. EXPECT_FALSE(matcher.match(over_limit));
  16595. }
  16596. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16597. Server svr;
  16598. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16599. res.set_content("ok", "text/plain");
  16600. });
  16601. auto port = svr.bind_to_any_port(HOST);
  16602. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16603. auto se = detail::scope_exit([&] {
  16604. svr.stop();
  16605. thread.join();
  16606. ASSERT_FALSE(svr.is_running());
  16607. });
  16608. svr.wait_until_ready();
  16609. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16610. // request URI limit; this used to be able to crash the process.
  16611. std::string path =
  16612. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16613. std::string req = "GET " + path +
  16614. " HTTP/1.1\r\n"
  16615. "Host: " +
  16616. std::string(HOST) + ":" + std::to_string(port) +
  16617. "\r\n"
  16618. "Connection: close\r\n"
  16619. "\r\n";
  16620. std::string response;
  16621. ASSERT_TRUE(send_request(5, req, &response, port));
  16622. EXPECT_NE(std::string::npos, response.find("404"));
  16623. }
  16624. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16625. Server svr;
  16626. auto handler = [](const Request & /*req*/, Response &res) {
  16627. res.set_content("hit", "text/plain");
  16628. };
  16629. // No regex metacharacter, so this one is compared literally
  16630. svr.Get("/literal/route", handler);
  16631. // '.' is a regex metacharacter, so this one must keep regex semantics
  16632. svr.Get("/a.c", handler);
  16633. auto port = svr.bind_to_any_port(HOST);
  16634. std::thread t([&]() { svr.listen_after_bind(); });
  16635. auto se = detail::scope_exit([&] {
  16636. svr.stop();
  16637. t.join();
  16638. ASSERT_FALSE(svr.is_running());
  16639. });
  16640. svr.wait_until_ready();
  16641. Client cli(HOST, port);
  16642. struct {
  16643. const char *path;
  16644. int status;
  16645. } cases[] = {
  16646. {"/literal/route", StatusCode::OK_200},
  16647. {"/literal/routes", StatusCode::NotFound_404},
  16648. {"/literal/rout", StatusCode::NotFound_404},
  16649. {"/abc", StatusCode::OK_200},
  16650. {"/a.c", StatusCode::OK_200},
  16651. };
  16652. for (const auto &x : cases) {
  16653. auto res = cli.Get(x.path);
  16654. ASSERT_TRUE(res) << x.path;
  16655. EXPECT_EQ(x.status, res->status) << x.path;
  16656. }
  16657. }
  16658. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16659. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16660. // from exhausting the stack, so it must only constrain routes that actually
  16661. // run a regular expression. A literal route is matched by comparison and
  16662. // stays usable at any length.
  16663. Server svr;
  16664. const std::string pattern =
  16665. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16666. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16667. res.set_content("hit", "text/plain");
  16668. });
  16669. auto port = svr.bind_to_any_port(HOST);
  16670. std::thread t([&]() { svr.listen_after_bind(); });
  16671. auto se = detail::scope_exit([&] {
  16672. svr.stop();
  16673. t.join();
  16674. ASSERT_FALSE(svr.is_running());
  16675. });
  16676. svr.wait_until_ready();
  16677. Client cli(HOST, port);
  16678. auto res = cli.Get(pattern);
  16679. ASSERT_TRUE(res);
  16680. EXPECT_EQ(StatusCode::OK_200, res->status);
  16681. }
  16682. TEST(ParseUrlTest, VariousPatterns) {
  16683. {
  16684. detail::UrlComponents uc;
  16685. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16686. EXPECT_EQ("http", uc.scheme);
  16687. EXPECT_EQ("example.com", uc.host);
  16688. EXPECT_EQ("8080", uc.port);
  16689. EXPECT_EQ("/path", uc.path);
  16690. EXPECT_EQ("?q=1", uc.query);
  16691. }
  16692. {
  16693. detail::UrlComponents uc;
  16694. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16695. EXPECT_EQ("https", uc.scheme);
  16696. EXPECT_EQ("example.com", uc.host);
  16697. EXPECT_TRUE(uc.port.empty());
  16698. EXPECT_EQ("/path", uc.path);
  16699. }
  16700. {
  16701. detail::UrlComponents uc;
  16702. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16703. EXPECT_EQ("::1", uc.host);
  16704. EXPECT_EQ("8080", uc.port);
  16705. EXPECT_EQ("/path", uc.path);
  16706. }
  16707. {
  16708. detail::UrlComponents uc;
  16709. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16710. }
  16711. {
  16712. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16713. // the path while the connection still targets the bracketed host.
  16714. detail::UrlComponents uc;
  16715. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16716. }
  16717. {
  16718. detail::UrlComponents uc;
  16719. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16720. }
  16721. {
  16722. detail::UrlComponents uc;
  16723. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16724. EXPECT_EQ("::1", uc.host);
  16725. EXPECT_TRUE(uc.port.empty());
  16726. EXPECT_EQ("/path", uc.path);
  16727. }
  16728. {
  16729. detail::UrlComponents uc;
  16730. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16731. EXPECT_TRUE(uc.scheme.empty());
  16732. EXPECT_EQ("example.com", uc.host);
  16733. EXPECT_EQ("/path", uc.path);
  16734. EXPECT_EQ("?q=1", uc.query);
  16735. }
  16736. {
  16737. detail::UrlComponents uc;
  16738. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16739. EXPECT_TRUE(uc.host.empty());
  16740. EXPECT_EQ("/path", uc.path);
  16741. EXPECT_EQ("?q=1", uc.query);
  16742. }
  16743. {
  16744. detail::UrlComponents uc;
  16745. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16746. EXPECT_EQ("example.com", uc.host);
  16747. EXPECT_EQ("8080", uc.port);
  16748. }
  16749. {
  16750. // Unix socket path — must not be parsed as host
  16751. detail::UrlComponents uc;
  16752. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16753. EXPECT_TRUE(uc.host.empty());
  16754. }
  16755. {
  16756. detail::UrlComponents uc;
  16757. ASSERT_TRUE(detail::parse_url("", uc));
  16758. EXPECT_TRUE(uc.host.empty());
  16759. EXPECT_TRUE(uc.path.empty());
  16760. }
  16761. {
  16762. detail::UrlComponents uc;
  16763. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16764. }
  16765. {
  16766. detail::UrlComponents uc;
  16767. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16768. }
  16769. {
  16770. // Accepted by parse_url; callers restrict to http/https
  16771. detail::UrlComponents uc;
  16772. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16773. EXPECT_EQ("ftp", uc.scheme);
  16774. }
  16775. {
  16776. detail::UrlComponents uc;
  16777. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16778. }
  16779. {
  16780. detail::UrlComponents uc;
  16781. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16782. }
  16783. }
  16784. TEST(ParseUrlTest, FragmentHandling) {
  16785. {
  16786. detail::UrlComponents uc;
  16787. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16788. EXPECT_EQ("/path", uc.path);
  16789. EXPECT_TRUE(uc.query.empty());
  16790. }
  16791. {
  16792. detail::UrlComponents uc;
  16793. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16794. EXPECT_TRUE(uc.path.empty());
  16795. EXPECT_TRUE(uc.query.empty());
  16796. }
  16797. }
  16798. TEST(ParseUrlTest, UserinfoHandling) {
  16799. // userinfo, and a backslash some parsers take for '/', are rejected: such
  16800. // parsers would see evil.com as the host.
  16801. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16802. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16803. for (auto url : urls) {
  16804. detail::UrlComponents uc;
  16805. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16806. }
  16807. }
  16808. TEST(ParseUrlTest, IPv6EdgeCases) {
  16809. {
  16810. detail::UrlComponents uc;
  16811. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16812. EXPECT_TRUE(uc.scheme.empty());
  16813. EXPECT_EQ("::1", uc.host);
  16814. EXPECT_EQ("8080", uc.port);
  16815. }
  16816. {
  16817. // Zone ID '%25' is not in [a-fA-F0-9:]
  16818. detail::UrlComponents uc;
  16819. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16820. }
  16821. }
  16822. TEST(ParseUrlTest, SchemeEdgeCases) {
  16823. {
  16824. detail::UrlComponents uc;
  16825. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16826. }
  16827. {
  16828. detail::UrlComponents uc;
  16829. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16830. }
  16831. {
  16832. detail::UrlComponents uc;
  16833. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16834. }
  16835. }
  16836. TEST(ParseUrlTest, PortEdgeCases) {
  16837. {
  16838. detail::UrlComponents uc;
  16839. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16840. EXPECT_TRUE(uc.port.empty());
  16841. EXPECT_EQ("/path", uc.path);
  16842. }
  16843. {
  16844. // parse_url accepts any port string; validation is done by parse_port
  16845. detail::UrlComponents uc;
  16846. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16847. EXPECT_EQ("abc", uc.port);
  16848. }
  16849. }
  16850. TEST(ParseUrlTest, WebSocketPatterns) {
  16851. {
  16852. detail::UrlComponents uc;
  16853. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16854. EXPECT_EQ("ws", uc.scheme);
  16855. EXPECT_EQ("echo.example.com", uc.host);
  16856. EXPECT_EQ("8080", uc.port);
  16857. EXPECT_EQ("/ws", uc.path);
  16858. }
  16859. {
  16860. detail::UrlComponents uc;
  16861. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16862. EXPECT_EQ("wss", uc.scheme);
  16863. EXPECT_EQ("echo.example.com", uc.host);
  16864. EXPECT_TRUE(uc.port.empty());
  16865. EXPECT_EQ("/ws", uc.path);
  16866. }
  16867. }
  16868. TEST(ParseUrlTest, QueryOnly) {
  16869. detail::UrlComponents uc;
  16870. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16871. EXPECT_TRUE(uc.host.empty());
  16872. EXPECT_TRUE(uc.path.empty());
  16873. EXPECT_EQ("?q=1&r=2", uc.query);
  16874. }
  16875. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16876. detail::UrlComponents uc;
  16877. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16878. EXPECT_TRUE(uc.scheme.empty());
  16879. EXPECT_EQ("example.com", uc.host);
  16880. EXPECT_EQ("443", uc.port);
  16881. EXPECT_EQ("/path", uc.path);
  16882. }
  16883. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16884. // If ipv6 regex working, regex match codepath is taken.
  16885. // else port will default to 80 in Client impl
  16886. int clientImplMagicPort = 80;
  16887. int port = 4321;
  16888. // above ports must be different to avoid false negative
  16889. EXPECT_NE(clientImplMagicPort, port);
  16890. std::string ipV6TestURL = "http://[ff06::c3]";
  16891. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16892. CLIENT_PRIVATE_KEY_FILE);
  16893. EXPECT_EQ(cli.port(), port);
  16894. }
  16895. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16896. auto file_path = "./www/dir/index.html";
  16897. auto dir_path = "./www/dir";
  16898. detail::FileStat stat_file(file_path);
  16899. EXPECT_TRUE(stat_file.is_file());
  16900. EXPECT_FALSE(stat_file.is_dir());
  16901. detail::FileStat stat_dir(dir_path);
  16902. EXPECT_FALSE(stat_dir.is_file());
  16903. EXPECT_TRUE(stat_dir.is_dir());
  16904. }
  16905. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16906. // IPv4 with default HTTP port (80)
  16907. EXPECT_EQ("example.com",
  16908. detail::make_host_and_port_string("example.com", 80, false));
  16909. // IPv4 with default HTTPS port (443)
  16910. EXPECT_EQ("example.com",
  16911. detail::make_host_and_port_string("example.com", 443, true));
  16912. // IPv4 with non-default HTTP port
  16913. EXPECT_EQ("example.com:8080",
  16914. detail::make_host_and_port_string("example.com", 8080, false));
  16915. // IPv4 with non-default HTTPS port
  16916. EXPECT_EQ("example.com:8443",
  16917. detail::make_host_and_port_string("example.com", 8443, true));
  16918. // IPv6 with default HTTP port (80)
  16919. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16920. // IPv6 with default HTTPS port (443)
  16921. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16922. // IPv6 with non-default HTTP port
  16923. EXPECT_EQ("[::1]:8080",
  16924. detail::make_host_and_port_string("::1", 8080, false));
  16925. // IPv6 with non-default HTTPS port
  16926. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16927. // IPv6 full address with default port
  16928. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16929. detail::make_host_and_port_string(
  16930. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16931. // IPv6 full address with non-default port
  16932. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16933. detail::make_host_and_port_string(
  16934. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16935. // IPv6 localhost with non-default port
  16936. EXPECT_EQ("[::1]:3000",
  16937. detail::make_host_and_port_string("::1", 3000, false));
  16938. // IPv6 with zone ID (link-local address) with default port
  16939. EXPECT_EQ("[fe80::1%eth0]",
  16940. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16941. // IPv6 with zone ID (link-local address) with non-default port
  16942. EXPECT_EQ("[fe80::1%eth0]:8080",
  16943. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16944. // Edge case: Port 443 with is_ssl=false (should add port)
  16945. EXPECT_EQ("example.com:443",
  16946. detail::make_host_and_port_string("example.com", 443, false));
  16947. // Edge case: Port 80 with is_ssl=true (should add port)
  16948. EXPECT_EQ("example.com:80",
  16949. detail::make_host_and_port_string("example.com", 80, true));
  16950. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16951. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16952. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16953. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16954. // Security fix: Already bracketed IPv6 should not get double brackets
  16955. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16956. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16957. EXPECT_EQ("[::1]:8080",
  16958. detail::make_host_and_port_string("[::1]", 8080, false));
  16959. EXPECT_EQ("[2001:db8::1]:8080",
  16960. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16961. EXPECT_EQ("[fe80::1%eth0]",
  16962. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16963. EXPECT_EQ("[fe80::1%eth0]:8080",
  16964. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16965. // Edge case: Empty host (should return as-is)
  16966. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16967. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16968. // This is a known limitation but shouldn't crash
  16969. EXPECT_EQ("[host:name]",
  16970. detail::make_host_and_port_string("host:name", 80, false));
  16971. // Port number edge cases (no validation, but should not crash)
  16972. EXPECT_EQ("example.com:0",
  16973. detail::make_host_and_port_string("example.com", 0, false));
  16974. EXPECT_EQ("example.com:-1",
  16975. detail::make_host_and_port_string("example.com", -1, false));
  16976. EXPECT_EQ("example.com:65535",
  16977. detail::make_host_and_port_string("example.com", 65535, false));
  16978. EXPECT_EQ("example.com:65536",
  16979. detail::make_host_and_port_string("example.com", 65536, false));
  16980. }
  16981. #ifdef CPPHTTPLIB_SSL_ENABLED
  16982. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16983. httplib::SSLClient cli("roblox.com", 443);
  16984. cli.set_follow_location(true);
  16985. auto res = cli.Get("/");
  16986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16987. EXPECT_EQ(StatusCode::OK_200, res->status);
  16988. }
  16989. #endif
  16990. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16991. Server svr;
  16992. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16993. EXPECT_EQ(res.status, 400);
  16994. });
  16995. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16996. auto se = detail::scope_exit([&] {
  16997. svr.stop();
  16998. thread.join();
  16999. ASSERT_FALSE(svr.is_running());
  17000. });
  17001. svr.wait_until_ready();
  17002. Client cli(HOST, PORT);
  17003. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17004. }
  17005. TEST(InvalidHeaderCharsTest, is_field_name) {
  17006. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17007. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17008. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17009. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17010. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17011. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17012. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17013. EXPECT_FALSE(detail::fields::is_field_name(""));
  17014. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17015. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17016. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17017. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17018. }
  17019. TEST(InvalidHeaderCharsTest, is_field_value) {
  17020. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17021. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17022. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17023. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17024. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17025. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17026. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17027. EXPECT_TRUE(detail::fields::is_field_value(""));
  17028. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17029. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17030. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17031. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17032. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17033. }
  17034. TEST(InvalidHeaderCharsTest, OnServer) {
  17035. Server svr;
  17036. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17037. std::string header = "Not Set";
  17038. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17039. res.set_header(header, "value");
  17040. res.set_content("Page Content Page Content", "text/plain");
  17041. });
  17042. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17043. std::string header = "Not Set";
  17044. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17045. res.set_header("X-Test", header);
  17046. res.set_content("Page Content Page Content", "text/plain");
  17047. });
  17048. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17049. auto se = detail::scope_exit([&] {
  17050. svr.stop();
  17051. thread.join();
  17052. ASSERT_FALSE(svr.is_running());
  17053. });
  17054. svr.wait_until_ready();
  17055. Client cli(HOST, PORT);
  17056. {
  17057. auto res = cli.Get(
  17058. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17060. EXPECT_EQ("Page Content Page Content", res->body);
  17061. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17062. }
  17063. {
  17064. auto res = cli.Get(
  17065. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17067. EXPECT_EQ("Page Content Page Content", res->body);
  17068. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17069. }
  17070. }
  17071. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17072. auto handled = false;
  17073. Server svr;
  17074. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17075. thread t = thread([&] { svr.listen(HOST, PORT); });
  17076. auto se = detail::scope_exit([&] {
  17077. svr.stop();
  17078. t.join();
  17079. ASSERT_FALSE(svr.is_running());
  17080. ASSERT_FALSE(handled);
  17081. });
  17082. svr.wait_until_ready();
  17083. auto req = "POST /test HTTP/1.1\r\n"
  17084. "Content-Length: x\r\n"
  17085. "\r\n";
  17086. std::string response;
  17087. ASSERT_TRUE(send_request(1, req, &response));
  17088. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17089. response.substr(0, response.find("\r\n")));
  17090. }
  17091. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17092. // case-insensitive, and a server that receives a 100-continue expectation in
  17093. // an HTTP/1.0 request MUST ignore it.
  17094. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17095. std::string response;
  17096. ASSERT_TRUE(send_request(1, req, &response, port));
  17097. *got_100 = response.find("100 Continue") != std::string::npos;
  17098. }
  17099. class ExpectTokenTest : public ::testing::Test {
  17100. protected:
  17101. void SetUp() override {
  17102. svr_.Post("/p", [](const Request &, Response &res) {
  17103. res.set_content("ok", "text/plain");
  17104. });
  17105. port_ = svr_.bind_to_any_port(HOST);
  17106. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17107. svr_.wait_until_ready();
  17108. }
  17109. void TearDown() override {
  17110. svr_.stop();
  17111. if (thread_.joinable()) { thread_.join(); }
  17112. }
  17113. std::string request(const char *version, const char *expect_value) const {
  17114. return std::string("POST /p ") + version +
  17115. "\r\n"
  17116. "Host: localhost\r\n"
  17117. "Content-Length: 2\r\n"
  17118. "Connection: close\r\n"
  17119. "Expect: " +
  17120. expect_value +
  17121. "\r\n"
  17122. "\r\n"
  17123. "hi";
  17124. }
  17125. Server svr_;
  17126. int port_ = 0;
  17127. thread thread_;
  17128. };
  17129. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17130. bool got_100 = false;
  17131. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17132. EXPECT_TRUE(got_100);
  17133. }
  17134. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17135. bool got_100 = true;
  17136. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17137. EXPECT_FALSE(got_100);
  17138. }
  17139. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17140. bool got_100 = false;
  17141. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17142. EXPECT_TRUE(got_100);
  17143. }
  17144. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17145. bool got_100 = false;
  17146. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17147. EXPECT_TRUE(got_100);
  17148. }
  17149. // `100 Continue` is sent only when the server starts reading the body, so a
  17150. // request rejected before that never invites the client to send it. The
  17151. // requests below carry the expectation but withhold the body, as a client
  17152. // waiting for `100 Continue` would.
  17153. // A POST that expects `100 Continue` and withholds its two-byte body.
  17154. static std::string expect_headers_only(const std::string &path) {
  17155. return "POST " + path +
  17156. " HTTP/1.1\r\n"
  17157. "Host: localhost\r\n"
  17158. "Content-Length: 2\r\n"
  17159. "Expect: 100-continue\r\n"
  17160. "\r\n";
  17161. }
  17162. class ExpectLazyContinueTest : public ::testing::Test {
  17163. protected:
  17164. void SetUp() override {
  17165. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17166. if (req.path == "/pre-routing") {
  17167. res.status = StatusCode::Unauthorized_401;
  17168. return Server::HandlerResponse::Handled;
  17169. }
  17170. return Server::HandlerResponse::Unhandled;
  17171. });
  17172. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17173. if (req.matched_route == "/pre-request") {
  17174. res.status = StatusCode::Forbidden_403;
  17175. return Server::HandlerResponse::Handled;
  17176. }
  17177. return Server::HandlerResponse::Unhandled;
  17178. });
  17179. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17180. res.set_content("ok", "text/plain");
  17181. });
  17182. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17183. res.set_content("ok", "text/plain");
  17184. });
  17185. svr_.Post("/reader-used", [](const Request &, Response &res,
  17186. const ContentReader &content_reader) {
  17187. std::string body;
  17188. content_reader([&](const char *data, size_t len) {
  17189. body.append(data, len);
  17190. return true;
  17191. });
  17192. res.set_content(body, "text/plain");
  17193. });
  17194. svr_.Post("/reader-unused",
  17195. [](const Request &, Response &res, const ContentReader &) {
  17196. res.set_content("ignored", "text/plain");
  17197. });
  17198. port_ = svr_.bind_to_any_port(HOST);
  17199. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17200. svr_.wait_until_ready();
  17201. }
  17202. void TearDown() override {
  17203. svr_.stop();
  17204. if (thread_.joinable()) { thread_.join(); }
  17205. }
  17206. // Sends `req` and reads until the server closes the connection. Returns
  17207. // false if the read had to wait for the client-side timeout instead.
  17208. bool send_until_closed(const std::string &req, std::string *resp) const {
  17209. auto start = std::chrono::steady_clock::now();
  17210. if (!send_request(3, req, resp, port_)) { return false; }
  17211. auto elapsed = std::chrono::steady_clock::now() - start;
  17212. return elapsed < std::chrono::seconds(2);
  17213. }
  17214. // The final response comes without `100 Continue`, and the server closes
  17215. // the connection since the body may or may not follow.
  17216. void expect_final_without_interim(const std::string &path,
  17217. const char *status_line) const {
  17218. std::string resp;
  17219. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17220. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17221. EXPECT_EQ(0u, resp.find(status_line));
  17222. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17223. }
  17224. Server svr_;
  17225. int port_ = 0;
  17226. thread thread_;
  17227. };
  17228. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17229. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17230. }
  17231. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17232. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17233. }
  17234. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17235. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17236. }
  17237. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17238. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17239. }
  17240. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17241. // The body follows once `100 Continue` has had time to arrive.
  17242. auto req = expect_headers_only("/reader-used");
  17243. req.insert(req.size() - 2, "Connection: close\r\n");
  17244. std::string resp;
  17245. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17246. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17247. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17248. EXPECT_NE(std::string::npos, resp.find("hi"));
  17249. }
  17250. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17251. // Large enough for the client to add `Expect: 100-continue` itself.
  17252. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17253. std::atomic<bool> body_sent{false};
  17254. Client cli(HOST, port_);
  17255. auto res = cli.Post(
  17256. "/pre-request", length,
  17257. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17258. body_sent = true;
  17259. std::string chunk(len, 'x');
  17260. sink.write(chunk.data(), chunk.size());
  17261. return true;
  17262. },
  17263. "application/octet-stream");
  17264. ASSERT_TRUE(res);
  17265. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17266. EXPECT_FALSE(body_sent);
  17267. }
  17268. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17269. Server svr;
  17270. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17271. return StatusCode::ExpectationFailed_417;
  17272. });
  17273. svr.Post("/p", [](const Request &, Response &res) {
  17274. res.set_content("ok", "text/plain");
  17275. });
  17276. auto port = svr.bind_to_any_port(HOST);
  17277. thread t = thread([&] { svr.listen_after_bind(); });
  17278. auto se = detail::scope_exit([&] {
  17279. svr.stop();
  17280. t.join();
  17281. });
  17282. svr.wait_until_ready();
  17283. std::string resp;
  17284. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17285. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17286. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17287. // Exactly one response: the route handler must not run after the 417.
  17288. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17289. }
  17290. #ifndef _WIN32
  17291. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17292. static constexpr char reject[] = "Unauthorized";
  17293. static constexpr char accept[] = "Upload accepted";
  17294. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17295. Server svr;
  17296. svr.set_expect_100_continue_handler(
  17297. [](const Request & /*req*/, Response &res) {
  17298. res.status = StatusCode::Unauthorized_401;
  17299. res.set_content(reject, "text/plain");
  17300. return res.status;
  17301. });
  17302. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17303. res.set_content(accept, "text/plain");
  17304. });
  17305. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17306. auto se = detail::scope_exit([&] {
  17307. svr.stop();
  17308. thread.join();
  17309. ASSERT_FALSE(svr.is_running());
  17310. });
  17311. svr.wait_until_ready();
  17312. {
  17313. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17314. curl_easy_init(), &curl_easy_cleanup};
  17315. ASSERT_NE(curl, nullptr);
  17316. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17317. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17318. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17319. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17320. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17321. &curl_slist_free_all};
  17322. ASSERT_NE(list, nullptr);
  17323. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17324. struct read_data {
  17325. size_t read_size;
  17326. size_t total_size;
  17327. } data = {0, total_size};
  17328. using read_callback_t =
  17329. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17330. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17331. void *userdata) -> size_t {
  17332. read_data *d = (read_data *)userdata;
  17333. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17334. std::fill_n(ptr, size * nmemb, 'A');
  17335. d->read_size += size * nmemb;
  17336. return size * nmemb;
  17337. };
  17338. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17339. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17340. std::vector<char> buffer;
  17341. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17342. using write_callback_t =
  17343. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17344. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17345. void *userdata) -> size_t {
  17346. std::vector<char> *buf = (std::vector<char> *)userdata;
  17347. buf->reserve(buf->size() + size * nmemb + 1);
  17348. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17349. return size * nmemb;
  17350. };
  17351. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17352. {
  17353. const auto res = curl_easy_perform(curl.get());
  17354. ASSERT_EQ(res, CURLE_OK);
  17355. }
  17356. {
  17357. auto response_code = long{};
  17358. const auto res =
  17359. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17360. ASSERT_EQ(res, CURLE_OK);
  17361. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17362. }
  17363. {
  17364. auto dl = curl_off_t{};
  17365. const auto res =
  17366. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17367. ASSERT_EQ(res, CURLE_OK);
  17368. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17369. }
  17370. {
  17371. buffer.push_back('\0');
  17372. ASSERT_STRCASEEQ(buffer.data(), reject);
  17373. }
  17374. }
  17375. }
  17376. #endif
  17377. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17378. // Regression test for #2458.
  17379. //
  17380. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17381. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17382. // ticket can make the client socket spuriously readable during the
  17383. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17384. // the client withholds the body and then blocks reading a response that never
  17385. // comes, failing with `Failed to read connection`.
  17386. //
  17387. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17388. // within the timeout. This raw OpenSSL server deliberately never sends
  17389. // `100 Continue`; the client must still deliver the body and receive 200.
  17390. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17391. signal(SIGPIPE, SIG_IGN);
  17392. const auto port = PORT + 4;
  17393. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17394. ASSERT_NE(srv, INVALID_SOCKET);
  17395. int opt = 1;
  17396. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17397. sockaddr_in addr{};
  17398. addr.sin_family = AF_INET;
  17399. addr.sin_port = htons(static_cast<uint16_t>(port));
  17400. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17401. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17402. ASSERT_EQ(0, ::listen(srv, 1));
  17403. std::atomic<size_t> server_body_bytes{0};
  17404. auto server_thread = std::thread([&] {
  17405. sockaddr_in cli_addr{};
  17406. socklen_t cli_len = sizeof(cli_addr);
  17407. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17408. if (cli == INVALID_SOCKET) { return; }
  17409. // Bound the lifetime of the server side so a buggy client (which never
  17410. // sends the body) cannot make this thread block forever on join.
  17411. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17412. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17413. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17414. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17415. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17416. SSL *ssl = SSL_new(ctx);
  17417. SSL_set_fd(ssl, static_cast<int>(cli));
  17418. if (SSL_accept(ssl) > 0) {
  17419. // Read the request headers. Reading here also flushes the TLS 1.3
  17420. // session tickets to the client. Deliberately do NOT send
  17421. // `100 Continue`.
  17422. std::string buf;
  17423. char tmp[1024];
  17424. while (buf.find("\r\n\r\n") == std::string::npos) {
  17425. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17426. if (n <= 0) { break; }
  17427. buf.append(tmp, static_cast<size_t>(n));
  17428. }
  17429. // A correct client sends the body now; count what arrives.
  17430. auto pos = buf.find("\r\n\r\n");
  17431. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17432. while (body < 4096) {
  17433. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17434. if (n <= 0) { break; }
  17435. body += static_cast<size_t>(n);
  17436. }
  17437. server_body_bytes = body;
  17438. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17439. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17440. SSL_shutdown(ssl);
  17441. }
  17442. SSL_free(ssl);
  17443. detail::close_socket(cli);
  17444. SSL_CTX_free(ctx);
  17445. });
  17446. auto se = detail::scope_exit([&] {
  17447. server_thread.join();
  17448. detail::close_socket(srv);
  17449. });
  17450. SSLClient cli("127.0.0.1", port);
  17451. cli.enable_server_certificate_verification(false);
  17452. cli.set_connection_timeout(5, 0);
  17453. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17454. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17455. std::string body(4096, 'A');
  17456. auto res = cli.Put("/api/test", body, "application/json");
  17457. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17458. EXPECT_EQ(StatusCode::OK_200, res->status);
  17459. EXPECT_EQ(body.size(), server_body_bytes.load());
  17460. }
  17461. #endif
  17462. template <typename S, typename C>
  17463. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17464. svr.Get("/stream", [&](const Request &, Response &res) {
  17465. auto data = new std::string("01234567890123456789");
  17466. res.set_content_provider(
  17467. data->size(), "text/plain",
  17468. [&, data](size_t offset, size_t length, DataSink &sink) {
  17469. const size_t DATA_CHUNK_SIZE = 4;
  17470. const auto &d = *data;
  17471. std::this_thread::sleep_for(std::chrono::seconds(1));
  17472. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17473. return true;
  17474. },
  17475. [data](bool success) {
  17476. EXPECT_FALSE(success);
  17477. delete data;
  17478. });
  17479. });
  17480. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17481. auto i = new size_t(0);
  17482. res.set_content_provider(
  17483. "text/plain",
  17484. [i](size_t, DataSink &sink) {
  17485. if (*i < 5) {
  17486. std::this_thread::sleep_for(std::chrono::seconds(1));
  17487. sink.write("abcd", 4);
  17488. (*i)++;
  17489. } else {
  17490. sink.done();
  17491. }
  17492. return true;
  17493. },
  17494. [i](bool success) {
  17495. EXPECT_FALSE(success);
  17496. delete i;
  17497. });
  17498. });
  17499. svr.Get("/chunked", [&](const Request &, Response &res) {
  17500. auto i = new size_t(0);
  17501. res.set_chunked_content_provider(
  17502. "text/plain",
  17503. [i](size_t, DataSink &sink) {
  17504. if (*i < 5) {
  17505. std::this_thread::sleep_for(std::chrono::seconds(1));
  17506. sink.os << "abcd";
  17507. (*i)++;
  17508. } else {
  17509. sink.done();
  17510. }
  17511. return true;
  17512. },
  17513. [i](bool success) {
  17514. EXPECT_FALSE(success);
  17515. delete i;
  17516. });
  17517. });
  17518. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17519. auto se = detail::scope_exit([&] {
  17520. svr.stop();
  17521. listen_thread.join();
  17522. ASSERT_FALSE(svr.is_running());
  17523. });
  17524. svr.wait_until_ready();
  17525. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17526. {
  17527. auto start = std::chrono::steady_clock::now();
  17528. auto res = cli.Get("/stream");
  17529. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17530. std::chrono::steady_clock::now() - start)
  17531. .count();
  17532. ASSERT_FALSE(res);
  17533. EXPECT_EQ(Error::Read, res.error());
  17534. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17535. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17536. }
  17537. {
  17538. auto start = std::chrono::steady_clock::now();
  17539. auto res = cli.Get("/stream_without_length");
  17540. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17541. std::chrono::steady_clock::now() - start)
  17542. .count();
  17543. ASSERT_FALSE(res);
  17544. EXPECT_EQ(Error::Read, res.error());
  17545. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17546. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17547. }
  17548. {
  17549. auto start = std::chrono::steady_clock::now();
  17550. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17551. EXPECT_EQ("abcd", string(data, data_length));
  17552. return true;
  17553. });
  17554. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17555. std::chrono::steady_clock::now() - start)
  17556. .count();
  17557. ASSERT_FALSE(res);
  17558. EXPECT_EQ(Error::Read, res.error());
  17559. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17560. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17561. }
  17562. }
  17563. TEST(MaxTimeoutTest, ContentStream) {
  17564. time_t timeout = 2000;
  17565. time_t threshold = 200;
  17566. Server svr;
  17567. Client cli("localhost", PORT);
  17568. max_timeout_test(svr, cli, timeout, threshold);
  17569. }
  17570. #ifdef CPPHTTPLIB_SSL_ENABLED
  17571. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17572. time_t timeout = 2000;
  17573. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17575. SSLClient cli("localhost", PORT);
  17576. cli.enable_server_certificate_verification(false);
  17577. max_timeout_test(svr, cli, timeout, threshold);
  17578. }
  17579. #endif
  17580. class EventDispatcher {
  17581. public:
  17582. EventDispatcher() {}
  17583. bool wait_event(DataSink *sink) {
  17584. unique_lock<mutex> lk(m_);
  17585. int id = id_;
  17586. // Wait with timeout to prevent hanging if client disconnects
  17587. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17588. [&] { return cid_ == id; })) {
  17589. return false; // Timeout occurred
  17590. }
  17591. sink->write(message_.data(), message_.size());
  17592. return true;
  17593. }
  17594. void send_event(const string &message) {
  17595. lock_guard<mutex> lk(m_);
  17596. cid_ = id_++;
  17597. message_ = message;
  17598. cv_.notify_all();
  17599. }
  17600. private:
  17601. mutex m_;
  17602. condition_variable cv_;
  17603. atomic_int id_{0};
  17604. atomic_int cid_{-1};
  17605. string message_;
  17606. };
  17607. TEST(ClientInThreadTest, Issue2068) {
  17608. EventDispatcher ed;
  17609. Server svr;
  17610. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17611. res.set_chunked_content_provider("text/event-stream",
  17612. [&](size_t /*offset*/, DataSink &sink) {
  17613. return ed.wait_event(&sink);
  17614. });
  17615. });
  17616. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17617. svr.wait_until_ready();
  17618. thread event_thread([&] {
  17619. int id = 0;
  17620. while (svr.is_running()) {
  17621. this_thread::sleep_for(chrono::milliseconds(500));
  17622. std::stringstream ss;
  17623. ss << "data: " << id << "\n\n";
  17624. ed.send_event(ss.str());
  17625. id++;
  17626. }
  17627. });
  17628. auto se = detail::scope_exit([&] {
  17629. svr.stop();
  17630. listen_thread.join();
  17631. event_thread.join();
  17632. ASSERT_FALSE(svr.is_running());
  17633. });
  17634. {
  17635. auto client = detail::make_unique<Client>(HOST, PORT);
  17636. client->set_read_timeout(std::chrono::minutes(10));
  17637. std::atomic<bool> stop{false};
  17638. std::thread t([&] {
  17639. client->Get("/event1",
  17640. [&](const char *, size_t) -> bool { return !stop; });
  17641. });
  17642. std::this_thread::sleep_for(std::chrono::seconds(2));
  17643. stop = true;
  17644. client->stop();
  17645. t.join();
  17646. // Reset client after thread has finished
  17647. client.reset();
  17648. }
  17649. }
  17650. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17651. auto handled = false;
  17652. Server svr;
  17653. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17654. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17655. auto se = detail::scope_exit([&] {
  17656. svr.stop();
  17657. t.join();
  17658. ASSERT_FALSE(svr.is_running());
  17659. ASSERT_FALSE(handled);
  17660. });
  17661. svr.wait_until_ready();
  17662. // Two Content-Length headers with different values — must be rejected
  17663. auto req = "POST /test HTTP/1.1\r\n"
  17664. "Content-Length: 5\r\n"
  17665. "Content-Length: 10\r\n"
  17666. "\r\n"
  17667. "hello";
  17668. std::string response;
  17669. ASSERT_TRUE(send_request(1, req, &response));
  17670. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17671. response.substr(0, response.find("\r\n")));
  17672. }
  17673. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17674. auto handled = false;
  17675. Server svr;
  17676. svr.Post("/test", [&](const Request &, Response &res) {
  17677. handled = true;
  17678. res.set_content("ok", "text/plain");
  17679. });
  17680. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17681. auto se = detail::scope_exit([&] {
  17682. svr.stop();
  17683. t.join();
  17684. ASSERT_FALSE(svr.is_running());
  17685. ASSERT_TRUE(handled);
  17686. });
  17687. svr.wait_until_ready();
  17688. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17689. auto req = "POST /test HTTP/1.1\r\n"
  17690. "Host: localhost\r\n"
  17691. "Content-Length: 5\r\n"
  17692. "Content-Length: 5\r\n"
  17693. "\r\n"
  17694. "hello";
  17695. std::string response;
  17696. ASSERT_TRUE(send_request(1, req, &response));
  17697. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17698. }
  17699. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17700. Server svr;
  17701. svr.Get("/test", [](const Request &, Response &res) {
  17702. res.set_content("ok", "text/plain");
  17703. });
  17704. auto port = svr.bind_to_any_port(HOST);
  17705. thread t = thread([&] { svr.listen_after_bind(); });
  17706. auto se = detail::scope_exit([&] {
  17707. svr.stop();
  17708. t.join();
  17709. ASSERT_FALSE(svr.is_running());
  17710. });
  17711. svr.wait_until_ready();
  17712. auto status_line = [&](const std::string &host_lines) {
  17713. std::string res;
  17714. send_request(
  17715. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17716. &res, port);
  17717. return res.substr(0, res.find("\r\n"));
  17718. };
  17719. const char *accepted[] = {
  17720. "Host: localhost\r\n",
  17721. "Host: a.example:8080\r\n",
  17722. "Host: my_service\r\n",
  17723. "Host: [::1]:8080\r\n",
  17724. "Host: [fe80::1%25eth0]\r\n",
  17725. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17726. };
  17727. for (auto host_lines : accepted) {
  17728. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17729. }
  17730. const char *rejected[] = {
  17731. "Host: a.example\r\nHost: b.example\r\n",
  17732. "Host: a.example\r\nHost: a.example\r\n",
  17733. "Host: a@b.example\r\n",
  17734. "Host: a.example/b\r\n",
  17735. "Host: a.example\\b\r\n",
  17736. "Host: a.example?b\r\n",
  17737. "Host: a.example#b\r\n",
  17738. "Host: a.example b.example\r\n",
  17739. };
  17740. for (auto host_lines : rejected) {
  17741. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17742. << host_lines;
  17743. }
  17744. }
  17745. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17746. Server svr;
  17747. svr.Get("/", [](const Request &req, Response &res) {
  17748. EXPECT_EQ(2U, req.trailers.size());
  17749. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17750. // Denied
  17751. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17752. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17753. // Accepted
  17754. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17755. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17756. EXPECT_TRUE(req.has_trailer("X-World"));
  17757. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17758. res.set_content("ok", "text/plain");
  17759. });
  17760. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17761. auto se = detail::scope_exit([&] {
  17762. svr.stop();
  17763. t.join();
  17764. ASSERT_FALSE(svr.is_running());
  17765. });
  17766. svr.wait_until_ready();
  17767. const std::string req = "GET / HTTP/1.1\r\n"
  17768. "Transfer-Encoding: chunked\r\n"
  17769. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17770. "\r\n"
  17771. "0\r\n"
  17772. "Content-Length: 10\r\n"
  17773. "Host: internal.local\r\n"
  17774. "Content-Type: malicious/content\r\n"
  17775. "Cookie: any\r\n"
  17776. "Set-Cookie: any\r\n"
  17777. "X-Forwarded-For: attacker.com\r\n"
  17778. "X-Real-Ip: 1.1.1.1\r\n"
  17779. "X-Hello: hello\r\n"
  17780. "X-World: world\r\n"
  17781. "\r\n";
  17782. std::string res;
  17783. ASSERT_TRUE(send_request(1, req, &res));
  17784. }
  17785. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17786. // several field lines, and the combined value is what has to be parsed. A
  17787. // Trailer field split across lines therefore declares every name it lists;
  17788. // reading only the first line silently drops the trailers the later lines
  17789. // declare. The prohibited-trailer filter still applies to every line.
  17790. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17791. Server svr;
  17792. size_t observed_trailer_count = 0;
  17793. std::string observed_hello;
  17794. std::string observed_world;
  17795. bool observed_content_length = true;
  17796. svr.Get("/", [&](const Request &req, Response &res) {
  17797. observed_trailer_count = req.trailers.size();
  17798. observed_hello = req.get_trailer_value("X-Hello");
  17799. observed_world = req.get_trailer_value("X-World");
  17800. observed_content_length = req.has_trailer("Content-Length");
  17801. res.set_content("ok", "text/plain");
  17802. });
  17803. auto port = svr.bind_to_any_port(HOST);
  17804. thread t = thread([&]() { svr.listen_after_bind(); });
  17805. auto se = detail::scope_exit([&] {
  17806. svr.stop();
  17807. t.join();
  17808. ASSERT_FALSE(svr.is_running());
  17809. });
  17810. svr.wait_until_ready();
  17811. const std::string req = "GET / HTTP/1.1\r\n"
  17812. "Host: localhost\r\n"
  17813. "Transfer-Encoding: chunked\r\n"
  17814. "Trailer: X-Hello\r\n"
  17815. "Trailer: X-World, Content-Length\r\n"
  17816. "\r\n"
  17817. "0\r\n"
  17818. "X-Hello: hello\r\n"
  17819. "X-World: world\r\n"
  17820. "Content-Length: 10\r\n"
  17821. "\r\n";
  17822. std::string res;
  17823. ASSERT_TRUE(send_request(1, req, &res, port));
  17824. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17825. // Accepted: both field lines contribute to the declared set
  17826. EXPECT_EQ(2U, observed_trailer_count);
  17827. EXPECT_EQ(observed_hello, "hello");
  17828. EXPECT_EQ(observed_world, "world");
  17829. // Denied: a prohibited name stays prohibited on a later field line
  17830. EXPECT_FALSE(observed_content_length);
  17831. }
  17832. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17833. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17834. // unbounded run of fields that are never declared, because the counter would
  17835. // only advance for declared fields.
  17836. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17837. Server svr;
  17838. bool handler_called = false;
  17839. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17840. handler_called = true;
  17841. res.set_content("ok", "text/plain");
  17842. });
  17843. auto port = svr.bind_to_any_port(HOST);
  17844. thread t = thread([&]() { svr.listen_after_bind(); });
  17845. auto se = detail::scope_exit([&] {
  17846. svr.stop();
  17847. t.join();
  17848. ASSERT_FALSE(svr.is_running());
  17849. });
  17850. svr.wait_until_ready();
  17851. // Declare nothing, then send far more undeclared trailer fields than the
  17852. // header-count limit. Parsing must stop and reject the request rather than
  17853. // read every line.
  17854. std::string req = "GET / HTTP/1.1\r\n"
  17855. "Transfer-Encoding: chunked\r\n"
  17856. "\r\n"
  17857. "0\r\n";
  17858. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17859. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17860. }
  17861. req += "\r\n";
  17862. std::string res;
  17863. ASSERT_TRUE(send_request(1, req, &res, port));
  17864. // The request is rejected before the handler runs.
  17865. EXPECT_FALSE(handler_called);
  17866. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17867. }
  17868. // The set of declared trailer names is capped so a peer cannot grow it without
  17869. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17870. // declared past the cap is not honored, even if the field is actually sent.
  17871. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17872. Server svr;
  17873. // One name inside the cap and one past it, so the test tracks the cap rather
  17874. // than a fixed count.
  17875. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17876. const std::string within_cap_name = "X-T-0";
  17877. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17878. bool observed_within_cap = false;
  17879. bool observed_past_cap = false;
  17880. svr.Get("/", [&](const Request &req, Response &res) {
  17881. observed_within_cap = req.has_trailer(within_cap_name);
  17882. observed_past_cap = req.has_trailer(past_cap_name);
  17883. res.set_content("ok", "text/plain");
  17884. });
  17885. auto port = svr.bind_to_any_port(HOST);
  17886. thread t = thread([&]() { svr.listen_after_bind(); });
  17887. auto se = detail::scope_exit([&] {
  17888. svr.stop();
  17889. t.join();
  17890. ASSERT_FALSE(svr.is_running());
  17891. });
  17892. svr.wait_until_ready();
  17893. // Declare more trailer names than the cap in a single Trailer field, then
  17894. // actually send the first (within the cap) and the last (past it).
  17895. std::string trailer_decl = "Trailer: ";
  17896. for (int i = 0; i < declared_count; i++) {
  17897. if (i != 0) { trailer_decl += ", "; }
  17898. trailer_decl += "X-T-" + std::to_string(i);
  17899. }
  17900. trailer_decl += "\r\n";
  17901. const std::string req = "GET / HTTP/1.1\r\n"
  17902. "Host: localhost\r\n"
  17903. "Transfer-Encoding: chunked\r\n" +
  17904. trailer_decl +
  17905. "\r\n"
  17906. "0\r\n" +
  17907. within_cap_name + ": a\r\n" + past_cap_name +
  17908. ": b\r\n"
  17909. "\r\n";
  17910. std::string res;
  17911. ASSERT_TRUE(send_request(1, req, &res, port));
  17912. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17913. // A name within the cap is honored; one declared past the cap is dropped.
  17914. EXPECT_TRUE(observed_within_cap);
  17915. EXPECT_FALSE(observed_past_cap);
  17916. }
  17917. // A direct client that is not listed in trusted_proxies must not be able to
  17918. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17919. // the peer address on the actual TCP connection determines whether the
  17920. // header is honored.
  17921. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17922. Server svr;
  17923. // Deliberately does NOT include the loopback address the test client
  17924. // actually connects from, so the direct connection is not a trusted proxy.
  17925. svr.set_trusted_proxies({"203.0.113.66"});
  17926. std::string observed_remote_addr;
  17927. svr.Get("/ip", [&](const Request &req, Response &res) {
  17928. observed_remote_addr = req.remote_addr;
  17929. res.set_content("ok", "text/plain");
  17930. });
  17931. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17932. auto se = detail::scope_exit([&] {
  17933. svr.stop();
  17934. t.join();
  17935. ASSERT_FALSE(svr.is_running());
  17936. });
  17937. svr.wait_until_ready();
  17938. Client cli(HOST, PORT);
  17939. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17941. EXPECT_EQ(StatusCode::OK_200, res->status);
  17942. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17943. // ignored entirely and the real connection-level address retained.
  17944. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17945. observed_remote_addr == "127.0.0.1");
  17946. }
  17947. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17948. Server svr;
  17949. std::string observed_remote_addr;
  17950. std::string observed_xff;
  17951. svr.Get("/ip", [&](const Request &req, Response &res) {
  17952. observed_remote_addr = req.remote_addr;
  17953. observed_xff = req.get_header_value("X-Forwarded-For");
  17954. res.set_content("ok", "text/plain");
  17955. });
  17956. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17957. auto se = detail::scope_exit([&] {
  17958. svr.stop();
  17959. t.join();
  17960. ASSERT_FALSE(svr.is_running());
  17961. });
  17962. svr.wait_until_ready();
  17963. Client cli(HOST, PORT);
  17964. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17966. EXPECT_EQ(StatusCode::OK_200, res->status);
  17967. EXPECT_EQ(observed_xff, "203.0.113.66");
  17968. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17969. observed_remote_addr == "127.0.0.1");
  17970. }
  17971. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17972. Server svr;
  17973. svr.set_trusted_proxies({"203.0.113.66"});
  17974. std::string observed_remote_addr;
  17975. std::string observed_xff;
  17976. svr.Get("/ip", [&](const Request &req, Response &res) {
  17977. observed_remote_addr = req.remote_addr;
  17978. observed_xff = req.get_header_value("X-Forwarded-For");
  17979. res.set_content("ok", "text/plain");
  17980. });
  17981. thread t = thread([&]() { svr.listen(HOST, PORT); });
  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. Client cli(HOST, PORT);
  17989. auto res = cli.Get("/ip");
  17990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17991. EXPECT_EQ(StatusCode::OK_200, res->status);
  17992. EXPECT_EQ(observed_xff, "");
  17993. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17994. observed_remote_addr == "127.0.0.1");
  17995. }
  17996. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17997. Server svr;
  17998. // Include the loopback address the test client actually connects from, so
  17999. // the direct connection itself is recognized as the trusted proxy hop.
  18000. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18001. std::string observed_remote_addr;
  18002. std::string observed_xff;
  18003. svr.Get("/ip", [&](const Request &req, Response &res) {
  18004. observed_remote_addr = req.remote_addr;
  18005. observed_xff = req.get_header_value("X-Forwarded-For");
  18006. res.set_content("ok", "text/plain");
  18007. });
  18008. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18009. auto se = detail::scope_exit([&] {
  18010. svr.stop();
  18011. t.join();
  18012. ASSERT_FALSE(svr.is_running());
  18013. });
  18014. svr.wait_until_ready();
  18015. Client cli(HOST, PORT);
  18016. auto res = cli.Get(
  18017. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18019. EXPECT_EQ(StatusCode::OK_200, res->status);
  18020. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18021. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18022. }
  18023. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18024. Server svr;
  18025. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18026. std::string observed_remote_addr;
  18027. std::string observed_xff;
  18028. svr.Get("/ip", [&](const Request &req, Response &res) {
  18029. observed_remote_addr = req.remote_addr;
  18030. observed_xff = req.get_header_value("X-Forwarded-For");
  18031. res.set_content("ok", "text/plain");
  18032. });
  18033. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18034. auto se = detail::scope_exit([&] {
  18035. svr.stop();
  18036. t.join();
  18037. ASSERT_FALSE(svr.is_running());
  18038. });
  18039. svr.wait_until_ready();
  18040. Client cli(HOST, PORT);
  18041. auto res = cli.Get(
  18042. "/ip",
  18043. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18045. EXPECT_EQ(StatusCode::OK_200, res->status);
  18046. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18047. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18048. }
  18049. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18050. Server svr;
  18051. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18052. std::string observed_remote_addr;
  18053. std::string observed_xff;
  18054. svr.Get("/ip", [&](const Request &req, Response &res) {
  18055. observed_remote_addr = req.remote_addr;
  18056. observed_xff = req.get_header_value("X-Forwarded-For");
  18057. res.set_content("ok", "text/plain");
  18058. });
  18059. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18060. auto se = detail::scope_exit([&] {
  18061. svr.stop();
  18062. t.join();
  18063. ASSERT_FALSE(svr.is_running());
  18064. });
  18065. svr.wait_until_ready();
  18066. Client cli(HOST, PORT);
  18067. auto res = cli.Get(
  18068. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18070. EXPECT_EQ(StatusCode::OK_200, res->status);
  18071. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18072. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18073. // and must not be selected.
  18074. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18075. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18076. }
  18077. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18078. Server svr;
  18079. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18080. std::string observed_remote_addr;
  18081. svr.Get("/ip", [&](const Request &req, Response &res) {
  18082. observed_remote_addr = req.remote_addr;
  18083. res.set_content("ok", "text/plain");
  18084. });
  18085. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18086. auto se = detail::scope_exit([&] {
  18087. svr.stop();
  18088. t.join();
  18089. ASSERT_FALSE(svr.is_running());
  18090. });
  18091. svr.wait_until_ready();
  18092. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18093. // a forged address and the trusted proxy's own address; the forged value must
  18094. // not win over the address the trusted proxy actually recorded.
  18095. Client cli(HOST, PORT);
  18096. auto res = cli.Get(
  18097. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18099. EXPECT_EQ(StatusCode::OK_200, res->status);
  18100. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18101. }
  18102. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18103. Server svr;
  18104. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18105. std::string observed_remote_addr;
  18106. std::string observed_xff;
  18107. svr.Get("/ip", [&](const Request &req, Response &res) {
  18108. observed_remote_addr = req.remote_addr;
  18109. observed_xff = req.get_header_value("X-Forwarded-For");
  18110. res.set_content("ok", "text/plain");
  18111. });
  18112. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18113. auto se = detail::scope_exit([&] {
  18114. svr.stop();
  18115. t.join();
  18116. ASSERT_FALSE(svr.is_running());
  18117. });
  18118. svr.wait_until_ready();
  18119. Client cli(HOST, PORT);
  18120. auto res = cli.Get(
  18121. "/ip",
  18122. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18124. EXPECT_EQ(StatusCode::OK_200, res->status);
  18125. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18126. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18127. }
  18128. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18129. Server svr;
  18130. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18131. std::string observed_remote_addr;
  18132. std::string observed_xff;
  18133. svr.Get("/ip", [&](const Request &req, Response &res) {
  18134. observed_remote_addr = req.remote_addr;
  18135. observed_xff = req.get_header_value("X-Forwarded-For");
  18136. res.set_content("ok", "text/plain");
  18137. });
  18138. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18139. auto se = detail::scope_exit([&] {
  18140. svr.stop();
  18141. t.join();
  18142. ASSERT_FALSE(svr.is_running());
  18143. });
  18144. svr.wait_until_ready();
  18145. std::string raw_req =
  18146. "GET /ip HTTP/1.1\r\n"
  18147. "Host: localhost\r\n"
  18148. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18149. "Connection: close\r\n"
  18150. "\r\n";
  18151. std::string out;
  18152. ASSERT_TRUE(send_request(5, raw_req, &out));
  18153. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18154. // Header parser trims surrounding whitespace of the header value
  18155. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18156. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18157. }
  18158. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18159. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18160. // their own X-Forwarded-For as a separate field line rather than extending the
  18161. // one the client sent, so every occurrence has to be taken into account.
  18162. // Reading only the first one hands back the address the client chose.
  18163. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18164. Server svr;
  18165. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18166. std::string observed_remote_addr;
  18167. size_t observed_xff_count = 0;
  18168. svr.Get("/ip", [&](const Request &req, Response &res) {
  18169. observed_remote_addr = req.remote_addr;
  18170. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18171. res.set_content("ok", "text/plain");
  18172. });
  18173. auto port = svr.bind_to_any_port(HOST);
  18174. thread t = thread([&]() { svr.listen_after_bind(); });
  18175. auto se = detail::scope_exit([&] {
  18176. svr.stop();
  18177. t.join();
  18178. ASSERT_FALSE(svr.is_running());
  18179. });
  18180. svr.wait_until_ready();
  18181. // The client supplies the first field line; the trusted proxy appends the
  18182. // address it observed as a second one.
  18183. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18184. "Host: localhost\r\n"
  18185. "X-Forwarded-For: 1.2.3.4\r\n"
  18186. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18187. "Connection: close\r\n"
  18188. "\r\n";
  18189. std::string out;
  18190. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18191. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18192. EXPECT_EQ(observed_xff_count, 2U);
  18193. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18194. // The same chain spread over one field line per hop derives the same client
  18195. // address, i.e. the split and the comma-joined representations agree.
  18196. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18197. "Host: localhost\r\n"
  18198. "X-Forwarded-For: 1.2.3.4\r\n"
  18199. "X-Forwarded-For: 198.51.100.23\r\n"
  18200. "X-Forwarded-For: 192.0.2.45\r\n"
  18201. "Connection: close\r\n"
  18202. "\r\n";
  18203. out.clear();
  18204. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18205. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18206. EXPECT_EQ(observed_xff_count, 3U);
  18207. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18208. }
  18209. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18210. // crash the server (it used to call front() on an empty vector inside
  18211. // get_client_ip). The connection-level remote address must be retained instead.
  18212. static void run_malformed_xff_test(const std::string &xff_value) {
  18213. Server svr;
  18214. svr.set_trusted_proxies({"192.0.2.45"});
  18215. std::string observed_remote_addr;
  18216. svr.Get("/ip", [&](const Request &req, Response &res) {
  18217. observed_remote_addr = req.remote_addr;
  18218. res.set_content("ok", "text/plain");
  18219. });
  18220. int port = 0;
  18221. thread t = thread([&]() {
  18222. port = svr.bind_to_any_port(HOST);
  18223. svr.listen_after_bind();
  18224. });
  18225. auto se = detail::scope_exit([&] {
  18226. svr.stop();
  18227. t.join();
  18228. ASSERT_FALSE(svr.is_running());
  18229. });
  18230. svr.wait_until_ready();
  18231. Client cli(HOST, port);
  18232. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18234. EXPECT_EQ(StatusCode::OK_200, res->status);
  18235. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18236. observed_remote_addr == "127.0.0.1");
  18237. }
  18238. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18239. run_malformed_xff_test("");
  18240. }
  18241. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18242. run_malformed_xff_test(",");
  18243. }
  18244. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18245. run_malformed_xff_test(", , ,");
  18246. }
  18247. // The same rule applies to Accept: a request whose acceptable types are spread
  18248. // over several field lines must be negotiated against all of them.
  18249. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18250. // case-insensitive connection options. Comparing the whole field value against
  18251. // one option misses a client that sends several of them, and misses every
  18252. // casing but the one written in the comparison.
  18253. //
  18254. // Sends req, reads the response, then reuses the same socket for a second
  18255. // request to find out whether the server kept the connection.
  18256. static void probe_connection_reuse(int port, const std::string &req,
  18257. bool *announced_close, bool *reusable) {
  18258. auto error = Error::Success;
  18259. auto sock = detail::create_client_socket(
  18260. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18261. /*connection_timeout_sec=*/5, 0,
  18262. /*read_timeout_sec=*/1, 0,
  18263. /*write_timeout_sec=*/5, 0, std::string(), error);
  18264. ASSERT_NE(sock, INVALID_SOCKET);
  18265. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18266. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18267. "Host: localhost\r\n"
  18268. "Connection: close\r\n"
  18269. "\r\n";
  18270. std::string first_response;
  18271. std::string second_response;
  18272. detail::process_client_socket(
  18273. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18274. [&](Stream &strm) {
  18275. if (strm.write(req.data(), req.size()) !=
  18276. static_cast<ssize_t>(req.size())) {
  18277. return false;
  18278. }
  18279. char buf[512];
  18280. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18281. // Headers plus the two-byte body of the handler below
  18282. while (reader.getline()) {
  18283. first_response += reader.ptr();
  18284. if (first_response.find("ok") != std::string::npos) { break; }
  18285. }
  18286. if (strm.write(second.data(), second.size()) !=
  18287. static_cast<ssize_t>(second.size())) {
  18288. return true;
  18289. }
  18290. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18291. while (reader2.getline()) {
  18292. second_response += reader2.ptr();
  18293. if (second_response.find("ok") != std::string::npos) { break; }
  18294. }
  18295. return true;
  18296. });
  18297. *announced_close =
  18298. first_response.find("Connection: close") != std::string::npos;
  18299. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18300. }
  18301. class ConnectionTokenTest : public ::testing::Test {
  18302. protected:
  18303. void SetUp() override {
  18304. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18305. res.set_content("ok", "text/plain");
  18306. });
  18307. port_ = svr_.bind_to_any_port(HOST);
  18308. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18309. svr_.wait_until_ready();
  18310. }
  18311. void TearDown() override {
  18312. svr_.stop();
  18313. if (thread_.joinable()) { thread_.join(); }
  18314. }
  18315. Server svr_;
  18316. int port_ = 0;
  18317. thread thread_;
  18318. };
  18319. // "close" alongside another option still closes the connection, and the
  18320. // response says so rather than leaving the peer to discover it.
  18321. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18322. bool announced_close = false;
  18323. bool reusable = true;
  18324. probe_connection_reuse(port_,
  18325. "GET /keepalive HTTP/1.1\r\n"
  18326. "Host: localhost\r\n"
  18327. "Connection: keep-alive, close\r\n"
  18328. "\r\n",
  18329. &announced_close, &reusable);
  18330. EXPECT_TRUE(announced_close);
  18331. EXPECT_FALSE(reusable);
  18332. }
  18333. // "close" split over two field lines is the same list, so it is honored too.
  18334. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18335. bool announced_close = false;
  18336. bool reusable = true;
  18337. probe_connection_reuse(port_,
  18338. "GET /keepalive HTTP/1.1\r\n"
  18339. "Host: localhost\r\n"
  18340. "Connection: keep-alive\r\n"
  18341. "Connection: close\r\n"
  18342. "\r\n",
  18343. &announced_close, &reusable);
  18344. EXPECT_TRUE(announced_close);
  18345. EXPECT_FALSE(reusable);
  18346. }
  18347. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18348. // keep-alive in the spelling everyone actually sends keeps its connection.
  18349. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18350. bool announced_close = false;
  18351. bool reusable = false;
  18352. probe_connection_reuse(port_,
  18353. "GET /keepalive HTTP/1.0\r\n"
  18354. "Host: localhost\r\n"
  18355. "Connection: keep-alive\r\n"
  18356. "\r\n",
  18357. &announced_close, &reusable);
  18358. EXPECT_FALSE(announced_close);
  18359. EXPECT_TRUE(reusable);
  18360. }
  18361. // A token the value merely contains is not the token itself.
  18362. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18363. bool announced_close = false;
  18364. bool reusable = false;
  18365. probe_connection_reuse(port_,
  18366. "GET /keepalive HTTP/1.1\r\n"
  18367. "Host: localhost\r\n"
  18368. "Connection: notclose\r\n"
  18369. "\r\n",
  18370. &announced_close, &reusable);
  18371. EXPECT_FALSE(announced_close);
  18372. EXPECT_TRUE(reusable);
  18373. }
  18374. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18375. Server svr;
  18376. std::vector<std::string> observed_types;
  18377. svr.Get("/", [&](const Request &req, Response &res) {
  18378. observed_types = req.accept_content_types;
  18379. res.set_content("ok", "text/plain");
  18380. });
  18381. auto port = svr.bind_to_any_port(HOST);
  18382. thread t = thread([&]() { svr.listen_after_bind(); });
  18383. auto se = detail::scope_exit([&] {
  18384. svr.stop();
  18385. t.join();
  18386. ASSERT_FALSE(svr.is_running());
  18387. });
  18388. svr.wait_until_ready();
  18389. Client cli(HOST, port);
  18390. Headers headers;
  18391. headers.emplace("Accept", "text/plain;q=0.5");
  18392. headers.emplace("Accept", "application/json");
  18393. auto res = cli.Get("/", headers);
  18394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18395. EXPECT_EQ(StatusCode::OK_200, res->status);
  18396. // Sorted by q-value, so the second field line's type comes first
  18397. ASSERT_EQ(2U, observed_types.size());
  18398. EXPECT_EQ("application/json", observed_types[0]);
  18399. EXPECT_EQ("text/plain", observed_types[1]);
  18400. }
  18401. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18402. // empty field line must not contribute a bare comma to the combined value.
  18403. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18404. Server svr;
  18405. std::vector<std::string> observed_types;
  18406. svr.Get("/", [&](const Request &req, Response &res) {
  18407. observed_types = req.accept_content_types;
  18408. res.set_content("ok", "text/plain");
  18409. });
  18410. auto port = svr.bind_to_any_port(HOST);
  18411. thread t = thread([&]() { svr.listen_after_bind(); });
  18412. auto se = detail::scope_exit([&] {
  18413. svr.stop();
  18414. t.join();
  18415. ASSERT_FALSE(svr.is_running());
  18416. });
  18417. svr.wait_until_ready();
  18418. // Empty first field line, then a real one
  18419. std::string raw_req = "GET / HTTP/1.1\r\n"
  18420. "Host: localhost\r\n"
  18421. "Accept:\r\n"
  18422. "Accept: application/json\r\n"
  18423. "Connection: close\r\n"
  18424. "\r\n";
  18425. std::string out;
  18426. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18427. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18428. ASSERT_EQ(1U, observed_types.size());
  18429. EXPECT_EQ("application/json", observed_types[0]);
  18430. }
  18431. // The skip in get_combined_header_value() is what keeps an empty field line
  18432. // from contributing a bare comma. Only a trailing empty field line exercises
  18433. // it: a leading one is already covered by the "combined is still empty" check,
  18434. // and parse_accept_header() now ignores the empty element either way, so the
  18435. // request-level test above can no longer tell the two apart.
  18436. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18437. Headers headers;
  18438. headers.emplace("Accept", "text/html");
  18439. headers.emplace("Accept", "");
  18440. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18441. headers.clear();
  18442. headers.emplace("Accept", "");
  18443. headers.emplace("Accept", "application/json");
  18444. EXPECT_EQ("application/json",
  18445. detail::get_combined_header_value(headers, "Accept"));
  18446. }
  18447. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18448. // An encoding offered on a later Accept-Encoding field line is still offered.
  18449. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18450. Server svr;
  18451. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18452. res.set_content(std::string(1024, 'x'), "text/plain");
  18453. });
  18454. auto port = svr.bind_to_any_port(HOST);
  18455. thread t = thread([&]() { svr.listen_after_bind(); });
  18456. auto se = detail::scope_exit([&] {
  18457. svr.stop();
  18458. t.join();
  18459. ASSERT_FALSE(svr.is_running());
  18460. });
  18461. svr.wait_until_ready();
  18462. Client cli(HOST, port);
  18463. cli.set_decompress(false);
  18464. Headers headers;
  18465. headers.emplace("Accept-Encoding", "identity");
  18466. headers.emplace("Accept-Encoding", "gzip");
  18467. auto res = cli.Get("/", headers);
  18468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18469. EXPECT_EQ(StatusCode::OK_200, res->status);
  18470. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18471. }
  18472. #endif
  18473. #ifndef _WIN32
  18474. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18475. Server svr;
  18476. svr.Post("/post", [&](const Request &req, Response &res) {
  18477. res.set_content(req.body, "text/plain");
  18478. });
  18479. svr.Put("/put", [&](const Request &req, Response &res) {
  18480. res.set_content(req.body, "text/plain");
  18481. });
  18482. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18483. res.set_content(req.body, "text/plain");
  18484. });
  18485. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18486. res.set_content(req.body, "text/plain");
  18487. });
  18488. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18489. auto se = detail::scope_exit([&] {
  18490. svr.stop();
  18491. t.join();
  18492. ASSERT_FALSE(svr.is_running());
  18493. });
  18494. svr.wait_until_ready();
  18495. std::string resp;
  18496. // POST without Content-Length
  18497. ASSERT_TRUE(send_request(5,
  18498. "POST /post HTTP/1.1\r\n"
  18499. "Host: localhost\r\n"
  18500. "Connection: close\r\n"
  18501. "\r\n",
  18502. &resp));
  18503. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18504. // PUT without Content-Length
  18505. resp.clear();
  18506. ASSERT_TRUE(send_request(5,
  18507. "PUT /put HTTP/1.1\r\n"
  18508. "Host: localhost\r\n"
  18509. "Connection: close\r\n"
  18510. "\r\n",
  18511. &resp));
  18512. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18513. // PATCH without Content-Length
  18514. resp.clear();
  18515. ASSERT_TRUE(send_request(5,
  18516. "PATCH /patch HTTP/1.1\r\n"
  18517. "Host: localhost\r\n"
  18518. "Connection: close\r\n"
  18519. "\r\n",
  18520. &resp));
  18521. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18522. // DELETE without Content-Length
  18523. resp.clear();
  18524. ASSERT_TRUE(send_request(5,
  18525. "DELETE /delete HTTP/1.1\r\n"
  18526. "Host: localhost\r\n"
  18527. "Connection: close\r\n"
  18528. "\r\n",
  18529. &resp));
  18530. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18531. }
  18532. #endif
  18533. //==============================================================================
  18534. // open_stream() Tests
  18535. //==============================================================================
  18536. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18537. std::string result;
  18538. char buf[8192];
  18539. ssize_t n;
  18540. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18541. result.append(buf, static_cast<size_t>(n));
  18542. }
  18543. return result;
  18544. }
  18545. // Mock stream for unit tests
  18546. class MockStream : public Stream {
  18547. public:
  18548. std::string data;
  18549. size_t pos = 0;
  18550. ssize_t error_after = -1; // -1 = no error
  18551. explicit MockStream(const std::string &d, ssize_t err = -1)
  18552. : data(d), error_after(err) {}
  18553. bool is_readable() const override { return true; }
  18554. bool wait_readable() const override { return true; }
  18555. bool wait_writable() const override { return true; }
  18556. ssize_t read(char *ptr, size_t size) override {
  18557. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18558. if (pos >= data.size()) return 0;
  18559. size_t limit =
  18560. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18561. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18562. std::memcpy(ptr, data.data() + pos, to_read);
  18563. pos += to_read;
  18564. return static_cast<ssize_t>(to_read);
  18565. }
  18566. ssize_t write(const char *, size_t) override { return -1; }
  18567. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18568. ip = "127.0.0.1";
  18569. port = 0;
  18570. }
  18571. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18572. ip = "127.0.0.1";
  18573. port = 0;
  18574. }
  18575. socket_t socket() const override { return INVALID_SOCKET; }
  18576. time_t duration() const override { return 0; }
  18577. };
  18578. TEST(StreamHandleTest, Basic) {
  18579. ClientImpl::StreamHandle handle;
  18580. EXPECT_FALSE(handle.is_valid());
  18581. handle.response = detail::make_unique<Response>();
  18582. handle.error = Error::Connection;
  18583. EXPECT_FALSE(handle.is_valid());
  18584. handle.error = Error::Success;
  18585. EXPECT_TRUE(handle.is_valid());
  18586. }
  18587. TEST(BodyReaderTest, Basic) {
  18588. MockStream stream("Hello, World!");
  18589. detail::BodyReader reader;
  18590. reader.stream = &stream;
  18591. reader.content_length = 13;
  18592. char buf[32];
  18593. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18594. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18595. EXPECT_TRUE(reader.eof);
  18596. }
  18597. TEST(BodyReaderTest, NoStream) {
  18598. detail::BodyReader reader;
  18599. char buf[32];
  18600. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18601. EXPECT_EQ(Error::Connection, reader.last_error);
  18602. }
  18603. TEST(BodyReaderTest, Error) {
  18604. MockStream stream("Hello, World!", 5);
  18605. detail::BodyReader reader;
  18606. reader.stream = &stream;
  18607. reader.content_length = 13;
  18608. char buf[32];
  18609. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18610. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18611. EXPECT_EQ(Error::Read, reader.last_error);
  18612. }
  18613. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18614. // Mock-based StreamHandle tests relying on private internals are removed.
  18615. class OpenStreamTest : public ::testing::Test {
  18616. protected:
  18617. void SetUp() override {
  18618. svr_.Get("/hello", [](const Request &, Response &res) {
  18619. res.set_content("Hello World!", "text/plain");
  18620. });
  18621. svr_.Get("/large", [](const Request &, Response &res) {
  18622. res.set_content(std::string(10000, 'X'), "text/plain");
  18623. });
  18624. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18625. res.set_content("Hello World!", "image/jpeg");
  18626. res.set_header("Content-Encoding", "UTF-8");
  18627. });
  18628. svr_.Get("/chunked", [](const Request &, Response &res) {
  18629. res.set_chunked_content_provider("text/plain",
  18630. [](size_t offset, DataSink &sink) {
  18631. if (offset < 15) {
  18632. sink.write("chunk", 5);
  18633. return true;
  18634. }
  18635. sink.done();
  18636. return true;
  18637. });
  18638. });
  18639. svr_.Get("/compressible", [](const Request &, Response &res) {
  18640. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18641. DataSink &sink) {
  18642. if (offset < 100 * 1024) {
  18643. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18644. sink.write(chunk.data(), chunk.size());
  18645. return true;
  18646. }
  18647. sink.done();
  18648. return true;
  18649. });
  18650. });
  18651. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18652. [](const Request & /*req*/, Response &res) {
  18653. auto i = new int(0);
  18654. res.set_header("Trailer", "Content-Length, X-Allowed");
  18655. res.set_chunked_content_provider(
  18656. "text/plain",
  18657. [i](size_t /*offset*/, DataSink &sink) {
  18658. switch (*i) {
  18659. case 0: sink.os << "123"; break;
  18660. case 1: sink.os << "456"; break;
  18661. case 2: sink.os << "789"; break;
  18662. case 3: {
  18663. sink.done_with_trailer(
  18664. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18665. } break;
  18666. }
  18667. (*i)++;
  18668. return true;
  18669. },
  18670. [i](bool success) {
  18671. EXPECT_TRUE(success);
  18672. delete i;
  18673. });
  18674. });
  18675. // Echo headers endpoint for header-related tests
  18676. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18677. std::string body;
  18678. for (const auto &h : req.headers) {
  18679. body.append(h.first);
  18680. body.push_back(':');
  18681. body.append(h.second);
  18682. body.push_back('\n');
  18683. }
  18684. res.set_content(body, "text/plain");
  18685. });
  18686. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18687. std::string body;
  18688. for (const auto &h : req.headers) {
  18689. body.append(h.first);
  18690. body.push_back(':');
  18691. body.append(h.second);
  18692. body.push_back('\n');
  18693. }
  18694. res.set_content(body, "text/plain");
  18695. });
  18696. port_ = svr_.bind_to_any_port("127.0.0.1");
  18697. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18698. svr_.wait_until_ready();
  18699. }
  18700. void TearDown() override {
  18701. svr_.stop();
  18702. if (thread_.joinable()) thread_.join();
  18703. }
  18704. Server svr_;
  18705. std::thread thread_;
  18706. int port_ = 0;
  18707. };
  18708. TEST_F(OpenStreamTest, Basic) {
  18709. Client cli("127.0.0.1", port_);
  18710. auto handle = cli.open_stream("GET", "/hello");
  18711. EXPECT_TRUE(handle.is_valid());
  18712. EXPECT_EQ("Hello World!", read_all(handle));
  18713. }
  18714. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18715. Client cli("127.0.0.1", port_);
  18716. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18717. ASSERT_TRUE(handle.is_valid());
  18718. EXPECT_EQ("Hello World!", read_all(handle));
  18719. }
  18720. TEST_F(OpenStreamTest, SmallBuffer) {
  18721. Client cli("127.0.0.1", port_);
  18722. auto handle = cli.open_stream("GET", "/hello");
  18723. std::string result;
  18724. char buf[4];
  18725. ssize_t n;
  18726. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18727. result.append(buf, static_cast<size_t>(n));
  18728. EXPECT_EQ("Hello World!", result);
  18729. }
  18730. TEST_F(OpenStreamTest, DefaultHeaders) {
  18731. Client cli("127.0.0.1", port_);
  18732. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18733. {
  18734. auto handle = cli.open_stream("GET", "/echo-headers");
  18735. ASSERT_TRUE(handle.is_valid());
  18736. auto body = read_all(handle);
  18737. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18738. std::string::npos);
  18739. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18740. std::string::npos);
  18741. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18742. }
  18743. // open_stream POST with body and no explicit content_type should NOT add
  18744. // text/plain Content-Type (behavior differs from non-streaming path), but
  18745. // should include Content-Length
  18746. {
  18747. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18748. ASSERT_TRUE(handle.is_valid());
  18749. auto body = read_all(handle);
  18750. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18751. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18752. }
  18753. // open_stream POST with explicit Content-Type should preserve it
  18754. {
  18755. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18756. {{"Content-Type", "application/custom"}},
  18757. "{}", "application/custom");
  18758. ASSERT_TRUE(handle.is_valid());
  18759. auto body = read_all(handle);
  18760. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18761. }
  18762. // User-specified User-Agent must not be overwritten for stream API
  18763. {
  18764. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18765. {{"User-Agent", "MyAgent/1.2"}});
  18766. ASSERT_TRUE(handle.is_valid());
  18767. auto body = read_all(handle);
  18768. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18769. }
  18770. }
  18771. TEST_F(OpenStreamTest, Large) {
  18772. Client cli("127.0.0.1", port_);
  18773. auto handle = cli.open_stream("GET", "/large");
  18774. EXPECT_EQ(10000u, read_all(handle).size());
  18775. }
  18776. TEST_F(OpenStreamTest, ConnectionError) {
  18777. Client cli("127.0.0.1", 9999);
  18778. auto handle = cli.open_stream("GET", "/hello");
  18779. EXPECT_FALSE(handle.is_valid());
  18780. }
  18781. TEST_F(OpenStreamTest, Chunked) {
  18782. Client cli("127.0.0.1", port_);
  18783. auto handle = cli.open_stream("GET", "/chunked");
  18784. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18785. "Transfer-Encoding") == "chunked");
  18786. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18787. }
  18788. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18789. Client cli("127.0.0.1", port_);
  18790. auto handle =
  18791. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18792. ASSERT_TRUE(handle.is_valid());
  18793. // Consume body to allow trailers to be received/parsed
  18794. auto body = read_all(handle);
  18795. // Explicitly parse trailers (ensure trailers are available for assertion)
  18796. handle.parse_trailers_if_needed();
  18797. EXPECT_EQ(std::string("123456789"), body);
  18798. // The response should include a Trailer header declaring both names
  18799. ASSERT_TRUE(handle.response);
  18800. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18801. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18802. handle.response->get_header_value("Trailer"));
  18803. // Prohibited trailer must not be present
  18804. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18805. // Allowed trailer should be present
  18806. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18807. EXPECT_EQ(std::string("yes"),
  18808. handle.response->get_trailer_value("X-Allowed"));
  18809. // Verify trailers are NOT present as regular headers
  18810. EXPECT_EQ(std::string(""),
  18811. handle.response->get_header_value("Content-Length"));
  18812. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18813. }
  18814. // Accepts one connection on an OS-assigned port, which it hands over through
  18815. // port_promise, reads the request head and sends back response. after_send,
  18816. // if given, runs on the connection before it is closed.
  18817. static std::thread
  18818. serve_single_response(std::promise<int> &port_promise,
  18819. const std::string &response,
  18820. std::function<void(socket_t)> after_send = nullptr) {
  18821. return std::thread([&port_promise, response, after_send] {
  18822. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18823. default_socket_options(srv);
  18824. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18825. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18826. sockaddr_in addr{};
  18827. addr.sin_family = AF_INET;
  18828. addr.sin_port = htons(0); // Let OS assign a free port
  18829. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18830. int opt = 1;
  18831. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18832. #ifdef _WIN32
  18833. reinterpret_cast<const char *>(&opt),
  18834. #else
  18835. &opt,
  18836. #endif
  18837. sizeof(opt));
  18838. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18839. ::listen(srv, 1) != 0) {
  18840. port_promise.set_value(-1);
  18841. detail::close_socket(srv);
  18842. return;
  18843. }
  18844. socklen_t addr_len = sizeof(addr);
  18845. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18846. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18847. sockaddr_in cli_addr{};
  18848. socklen_t cli_len = sizeof(cli_addr);
  18849. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18850. if (cli != INVALID_SOCKET) {
  18851. // Read the complete HTTP request (until the blank line that terminates
  18852. // headers) before sending the response. If the server closes the socket
  18853. // while the client's request data is still unread in the kernel receive
  18854. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18855. // connection on both sides: it discards the client's receive buffer
  18856. // (which already holds our response) and causes any in-progress write on
  18857. // the client to fail with ECONNRESET. Reading all request data first
  18858. // ensures close() emits a graceful FIN.
  18859. {
  18860. char rbuf[256];
  18861. std::string req;
  18862. while (req.find("\r\n\r\n") == std::string::npos) {
  18863. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18864. if (n <= 0) { break; }
  18865. req.append(rbuf, static_cast<size_t>(n));
  18866. }
  18867. }
  18868. ::send(cli,
  18869. #ifdef _WIN32
  18870. static_cast<const char *>(response.c_str()),
  18871. static_cast<int>(response.size()),
  18872. #else
  18873. response.c_str(), response.size(),
  18874. #endif
  18875. 0);
  18876. if (after_send) { after_send(cli); }
  18877. detail::close_socket(cli);
  18878. }
  18879. detail::close_socket(srv);
  18880. });
  18881. }
  18882. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18883. #ifndef _WIN32
  18884. signal(SIGPIPE, SIG_IGN);
  18885. #endif
  18886. std::promise<int> port_promise;
  18887. auto port_future = port_promise.get_future();
  18888. auto server_thread =
  18889. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18890. "Content-Type: text/plain\r\n"
  18891. "Content-Length: not-a-number\r\n"
  18892. "Connection: close\r\n"
  18893. "\r\n"
  18894. "hello");
  18895. auto port = port_future.get();
  18896. ASSERT_GT(port, 0);
  18897. Client cli("127.0.0.1", port);
  18898. auto handle = cli.open_stream("GET", "/");
  18899. EXPECT_FALSE(handle.is_valid());
  18900. server_thread.join();
  18901. }
  18902. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18903. #ifndef _WIN32
  18904. signal(SIGPIPE, SIG_IGN);
  18905. #endif
  18906. std::promise<int> port_promise;
  18907. auto port_future = port_promise.get_future();
  18908. auto server_thread = serve_single_response(
  18909. port_promise, "HTTP/1.1 200 OK\r\n"
  18910. "Content-Type: text/plain\r\n"
  18911. "Content-Length: 99999999999999999999999999\r\n"
  18912. "Connection: close\r\n"
  18913. "\r\n"
  18914. "hello");
  18915. auto port = port_future.get();
  18916. ASSERT_GT(port, 0);
  18917. // Historically std::stoull would throw std::out_of_range here and crash
  18918. // the process, then parsing silently clamped to a bogus framing length and
  18919. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18920. // so the stream fails to open, matching the not-a-number case above. The
  18921. // process still must NOT terminate.
  18922. Client cli("127.0.0.1", port);
  18923. auto handle = cli.open_stream("GET", "/");
  18924. EXPECT_FALSE(handle.is_valid());
  18925. server_thread.join();
  18926. }
  18927. // Serves `response` to the single request `fn` makes with a fresh client.
  18928. template <typename Fn>
  18929. static void with_single_response(const std::string &response, Fn fn) {
  18930. #ifndef _WIN32
  18931. signal(SIGPIPE, SIG_IGN);
  18932. #endif
  18933. std::promise<int> port_promise;
  18934. auto port_future = port_promise.get_future();
  18935. auto server_thread = serve_single_response(port_promise, response);
  18936. auto se = detail::scope_exit([&] { server_thread.join(); });
  18937. auto port = port_future.get();
  18938. ASSERT_GT(port, 0);
  18939. Client cli("127.0.0.1", port);
  18940. fn(cli);
  18941. }
  18942. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  18943. const char *responses[] = {
  18944. "HTTP/1.1 103 Early Hints\r\n"
  18945. "Link: </style.css>; rel=preload\r\n"
  18946. "\r\n"
  18947. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  18948. "HTTP/1.1 100 Continue\r\n"
  18949. "X-Note: interim\r\n"
  18950. "\r\n"
  18951. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  18952. };
  18953. for (auto response : responses) {
  18954. with_single_response(response, [](Client &cli) {
  18955. auto res = cli.Get("/");
  18956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18957. EXPECT_EQ(StatusCode::OK_200, res->status);
  18958. EXPECT_EQ("ok", res->body);
  18959. });
  18960. }
  18961. }
  18962. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  18963. #ifndef _WIN32
  18964. signal(SIGPIPE, SIG_IGN);
  18965. #endif
  18966. // The server answers the head without asking for the body. Bytes it then
  18967. // reads on the connection would be taken for the body the request declared.
  18968. auto closed_by_client = false;
  18969. std::promise<int> port_promise;
  18970. auto server_thread = serve_single_response(
  18971. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  18972. [&](socket_t sock) {
  18973. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  18974. char buf[256];
  18975. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  18976. });
  18977. Client cli("127.0.0.1", port_promise.get_future().get());
  18978. cli.set_keep_alive(true);
  18979. cli.set_read_timeout(1, 0);
  18980. // Long enough for the client to send Expect: 100-continue.
  18981. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18983. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  18984. cli.Get("/second");
  18985. server_thread.join();
  18986. EXPECT_TRUE(closed_by_client);
  18987. }
  18988. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  18989. // Long enough for the client to send Expect: 100-continue
  18990. with_single_response(
  18991. "HTTP/1.1 103 Early Hints\r\n"
  18992. "Link: </style.css>; rel=preload\r\n"
  18993. "\r\n"
  18994. "HTTP/1.1 401 Unauthorized\r\n"
  18995. "Content-Length: 0\r\n\r\n",
  18996. [](Client &cli) {
  18997. cli.set_read_timeout(2, 0);
  18998. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19000. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19001. });
  19002. }
  19003. #ifdef CPPHTTPLIB_SSL_ENABLED
  19004. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19005. #ifndef _WIN32
  19006. signal(SIGPIPE, SIG_IGN);
  19007. #endif
  19008. auto reused = false;
  19009. std::promise<int> port_promise;
  19010. auto server_thread = serve_single_response(
  19011. port_promise,
  19012. "HTTP/1.1 401 Unauthorized\r\n"
  19013. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19014. "Content-Length: 0\r\n\r\n",
  19015. [&](socket_t sock) {
  19016. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19017. char buf[256];
  19018. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19019. });
  19020. Client cli("127.0.0.1", port_promise.get_future().get());
  19021. cli.set_keep_alive(true);
  19022. cli.set_digest_auth("user", "pass");
  19023. cli.set_read_timeout(1, 0);
  19024. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19025. server_thread.join();
  19026. EXPECT_FALSE(reused);
  19027. }
  19028. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19029. // Any other answer to CONNECT would read as the origin's response.
  19030. struct {
  19031. const char *response;
  19032. bool passed_on;
  19033. } cases[] = {
  19034. {"HTTP/1.1 201 Created\r\n"
  19035. "Set-Cookie: session=from-proxy\r\n"
  19036. "Content-Length: 0\r\n\r\n",
  19037. false},
  19038. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19039. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19040. "Content-Length: 0\r\n\r\n",
  19041. true},
  19042. };
  19043. for (const auto &c : cases) {
  19044. std::promise<int> port_promise;
  19045. auto server_thread = serve_single_response(port_promise, c.response);
  19046. SSLClient cli("example.com", 443);
  19047. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19048. auto res = cli.Get("/");
  19049. server_thread.join();
  19050. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19051. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19052. if (res) {
  19053. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19054. }
  19055. }
  19056. }
  19057. #endif
  19058. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19059. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19060. // the chunked coding and drop Content-Length, so a front-end that trusts
  19061. // Content-Length would disagree about where the body ends (response
  19062. // smuggling). The client must reject such a response.
  19063. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19064. for (const char *te : {"chunked", "gzip, chunked"}) {
  19065. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19066. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19067. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19068. "5\r\nhello\r\n0\r\n\r\n";
  19069. with_single_response(response, [&](Client &cli) {
  19070. auto res = cli.Get("/");
  19071. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19072. EXPECT_EQ(Error::Read, res.error()) << te;
  19073. });
  19074. with_single_response(response, [&](Client &cli) {
  19075. auto handle = cli.open_stream("GET", "/");
  19076. EXPECT_FALSE(handle.is_valid()) << te;
  19077. EXPECT_EQ(Error::Read, handle.error) << te;
  19078. });
  19079. }
  19080. }
  19081. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19082. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19083. // closing the connection (unlike a request, which must be rejected).
  19084. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19085. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19086. "Transfer-Encoding: chunked\r\n"
  19087. "Connection: close\r\n"
  19088. "\r\n"
  19089. "5\r\nhello\r\n0\r\n\r\n",
  19090. "HTTP/1.1 200 OK\r\n"
  19091. "Transfer-Encoding: gzip\r\n"
  19092. "Connection: close\r\n"
  19093. "\r\n"
  19094. "hello"}) {
  19095. with_single_response(response, [&](Client &cli) {
  19096. auto res = cli.Get("/");
  19097. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19098. EXPECT_EQ("hello", res->body);
  19099. });
  19100. with_single_response(response, [&](Client &cli) {
  19101. auto handle = cli.open_stream("GET", "/");
  19102. ASSERT_TRUE(handle.is_valid()) << response;
  19103. EXPECT_EQ("hello", read_all(handle));
  19104. });
  19105. }
  19106. }
  19107. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19108. // framing headers describe nothing to read and must not be rejected.
  19109. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19110. const std::string framing = "Content-Length: 5\r\n"
  19111. "Transfer-Encoding: chunked\r\n"
  19112. "Connection: close\r\n"
  19113. "\r\n";
  19114. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19115. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19116. });
  19117. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19118. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19119. });
  19120. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19121. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19122. with_single_response(response, [&](Client &cli) {
  19123. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19124. });
  19125. with_single_response(response, [&](Client &cli) {
  19126. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19127. });
  19128. }
  19129. }
  19130. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19131. // response, is faulty framing, so the connection is not reused after it.
  19132. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19133. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19134. "Content-Length: 0\r\n"
  19135. "Transfer-Encoding: chunked\r\n"
  19136. "\r\n"
  19137. "5\r\nhello\r\n0\r\n\r\n",
  19138. "HTTP/1.0 200 Connection established\r\n"
  19139. "Connection: keep-alive\r\n"
  19140. "Transfer-Encoding: chunked\r\n"
  19141. "\r\n"
  19142. "5\r\nhello\r\n0\r\n\r\n"}) {
  19143. with_single_response(response, [&](Client &cli) {
  19144. cli.set_keep_alive(true);
  19145. auto res = cli.Get("/");
  19146. ASSERT_TRUE(res) << response;
  19147. EXPECT_EQ("hello", res->body);
  19148. EXPECT_FALSE(cli.is_socket_open()) << response;
  19149. });
  19150. }
  19151. }
  19152. // A payload max length of 0 means no limit, however the body is framed.
  19153. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19154. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19155. "Transfer-Encoding: chunked\r\n"
  19156. "\r\n"
  19157. "5\r\nhello\r\n0\r\n\r\n",
  19158. "HTTP/1.1 200 OK\r\n"
  19159. "Connection: close\r\n"
  19160. "\r\n"
  19161. "hello"}) {
  19162. with_single_response(response, [&](Client &cli) {
  19163. cli.set_payload_max_length(0);
  19164. auto res = cli.Get("/");
  19165. ASSERT_TRUE(res) << response;
  19166. EXPECT_EQ("hello", res->body) << response;
  19167. });
  19168. }
  19169. }
  19170. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19171. Server svr;
  19172. svr.set_payload_max_length(0);
  19173. svr.Post("/echo", [](const Request &req, Response &res) {
  19174. res.set_content(req.body, "text/plain");
  19175. });
  19176. auto port = svr.bind_to_any_port(HOST);
  19177. thread t = thread([&] { svr.listen_after_bind(); });
  19178. auto se = detail::scope_exit([&] {
  19179. svr.stop();
  19180. t.join();
  19181. ASSERT_FALSE(svr.is_running());
  19182. });
  19183. svr.wait_until_ready();
  19184. Client cli(HOST, port);
  19185. auto res = cli.Post(
  19186. "/echo",
  19187. [](size_t /*offset*/, DataSink &sink) {
  19188. sink.write("hello", 5);
  19189. sink.done();
  19190. return true;
  19191. },
  19192. "text/plain");
  19193. ASSERT_TRUE(res);
  19194. EXPECT_EQ(StatusCode::OK_200, res->status);
  19195. EXPECT_EQ("hello", res->body);
  19196. }
  19197. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19198. TEST_F(OpenStreamTest, Gzip) {
  19199. Client cli("127.0.0.1", port_);
  19200. auto handle = cli.open_stream("GET", "/compressible", {},
  19201. {{"Accept-Encoding", "gzip"}});
  19202. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19203. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19204. }
  19205. #endif
  19206. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19207. TEST_F(OpenStreamTest, Brotli) {
  19208. Client cli("127.0.0.1", port_);
  19209. auto handle =
  19210. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19211. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19212. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19213. }
  19214. #endif
  19215. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19216. TEST_F(OpenStreamTest, Zstd) {
  19217. Client cli("127.0.0.1", port_);
  19218. auto handle = cli.open_stream("GET", "/compressible", {},
  19219. {{"Accept-Encoding", "zstd"}});
  19220. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19221. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19222. }
  19223. #endif
  19224. #ifdef CPPHTTPLIB_SSL_ENABLED
  19225. class SSLOpenStreamTest : public ::testing::Test {
  19226. protected:
  19227. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19228. void SetUp() override {
  19229. svr_.Get("/hello", [](const Request &, Response &res) {
  19230. res.set_content("Hello SSL World!", "text/plain");
  19231. });
  19232. svr_.Get("/chunked", [](const Request &, Response &res) {
  19233. res.set_chunked_content_provider("text/plain",
  19234. [](size_t offset, DataSink &sink) {
  19235. if (offset < 15) {
  19236. sink.write("chunk", 5);
  19237. return true;
  19238. }
  19239. sink.done();
  19240. return true;
  19241. });
  19242. });
  19243. svr_.Post("/echo", [](const Request &req, Response &res) {
  19244. res.set_content(req.body, req.get_header_value("Content-Type"));
  19245. });
  19246. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19247. std::string body = req.body;
  19248. res.set_chunked_content_provider(
  19249. "text/plain", [body](size_t offset, DataSink &sink) {
  19250. if (offset < body.size()) {
  19251. sink.write(body.data() + offset, body.size() - offset);
  19252. }
  19253. sink.done();
  19254. return true;
  19255. });
  19256. });
  19257. port_ = svr_.bind_to_any_port("127.0.0.1");
  19258. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19259. svr_.wait_until_ready();
  19260. }
  19261. void TearDown() override {
  19262. svr_.stop();
  19263. if (thread_.joinable()) thread_.join();
  19264. }
  19265. SSLServer svr_;
  19266. std::thread thread_;
  19267. int port_ = 0;
  19268. };
  19269. TEST_F(SSLOpenStreamTest, Basic) {
  19270. SSLClient cli("127.0.0.1", port_);
  19271. cli.enable_server_certificate_verification(false);
  19272. auto handle = cli.open_stream("GET", "/hello");
  19273. ASSERT_TRUE(handle.is_valid());
  19274. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19275. }
  19276. TEST_F(SSLOpenStreamTest, Chunked) {
  19277. SSLClient cli("127.0.0.1", port_);
  19278. cli.enable_server_certificate_verification(false);
  19279. auto handle = cli.open_stream("GET", "/chunked");
  19280. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19281. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19282. "Transfer-Encoding") == "chunked");
  19283. auto body = read_all(handle);
  19284. EXPECT_EQ("chunkchunkchunk", body);
  19285. }
  19286. TEST_F(SSLOpenStreamTest, Post) {
  19287. SSLClient cli("127.0.0.1", port_);
  19288. cli.enable_server_certificate_verification(false);
  19289. auto handle =
  19290. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19291. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19292. EXPECT_EQ(200, handle.response->status);
  19293. auto body = read_all(handle);
  19294. EXPECT_EQ("Hello SSL POST", body);
  19295. }
  19296. TEST_F(SSLOpenStreamTest, PostChunked) {
  19297. SSLClient cli("127.0.0.1", port_);
  19298. cli.enable_server_certificate_verification(false);
  19299. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19300. "Chunked SSL Data", "text/plain");
  19301. ASSERT_TRUE(handle.is_valid());
  19302. EXPECT_EQ(200, handle.response->status);
  19303. auto body = read_all(handle);
  19304. EXPECT_EQ("Chunked SSL Data", body);
  19305. }
  19306. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19307. // Content-Length is terminated by the server closing the connection. When the
  19308. // SSL peer sends a close_notify after the body, the client must treat it as a
  19309. // clean EOF and return a successful response rather than an error.
  19310. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19311. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19312. ASSERT_TRUE(svr.is_valid());
  19313. svr.set_keep_alive_max_count(1);
  19314. const std::string expected_body = "Hello from connection-close response!";
  19315. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19316. res.set_content_provider("text/plain",
  19317. [&](size_t offset, DataSink &sink) -> bool {
  19318. if (offset < expected_body.size()) {
  19319. sink.write(expected_body.data() + offset,
  19320. expected_body.size() - offset);
  19321. }
  19322. sink.done();
  19323. return true;
  19324. });
  19325. });
  19326. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19327. auto se = detail::scope_exit([&] {
  19328. svr.stop();
  19329. listen_thread.join();
  19330. ASSERT_FALSE(svr.is_running());
  19331. });
  19332. svr.wait_until_ready();
  19333. SSLClient cli(HOST, PORT);
  19334. cli.enable_server_certificate_verification(false);
  19335. auto res = cli.Get("/no-content-length");
  19336. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19337. EXPECT_EQ(StatusCode::OK_200, res->status);
  19338. EXPECT_EQ(expected_body, res->body);
  19339. }
  19340. #endif // CPPHTTPLIB_SSL_ENABLED
  19341. //==============================================================================
  19342. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19343. // results for various scenarios.
  19344. //==============================================================================
  19345. TEST(ParityTest, GetVsOpenStream) {
  19346. Server svr;
  19347. const std::string path = "/parity";
  19348. const std::string content = "Parity test content: hello world";
  19349. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19350. res.set_content(content, "text/plain");
  19351. });
  19352. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19353. auto se = detail::scope_exit([&] {
  19354. svr.stop();
  19355. t.join();
  19356. ASSERT_FALSE(svr.is_running());
  19357. });
  19358. svr.wait_until_ready();
  19359. Client cli(HOST, PORT);
  19360. // Non-stream path
  19361. auto r1 = cli.Get(path);
  19362. ASSERT_TRUE(r1);
  19363. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19364. // Stream path
  19365. auto h = cli.open_stream("GET", path);
  19366. ASSERT_TRUE(h.is_valid());
  19367. EXPECT_EQ(r1->body, read_all(h));
  19368. }
  19369. // Helper to compress data with provided compressor type T
  19370. template <typename Compressor>
  19371. static std::string compress_payload_for_parity(const std::string &in) {
  19372. std::string out;
  19373. Compressor compressor;
  19374. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19375. [&](const char *data, size_t n) {
  19376. out.append(data, n);
  19377. return true;
  19378. });
  19379. EXPECT_TRUE(ok);
  19380. return out;
  19381. }
  19382. // Helper function for compression parity tests
  19383. template <typename Compressor>
  19384. static void test_compression_parity(const std::string &original,
  19385. const std::string &path,
  19386. const std::string &encoding) {
  19387. const std::string compressed =
  19388. compress_payload_for_parity<Compressor>(original);
  19389. Server svr;
  19390. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19391. res.set_content(compressed, "application/octet-stream");
  19392. res.set_header("Content-Encoding", encoding);
  19393. });
  19394. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19395. auto se = detail::scope_exit([&] {
  19396. svr.stop();
  19397. t.join();
  19398. ASSERT_FALSE(svr.is_running());
  19399. });
  19400. svr.wait_until_ready();
  19401. Client cli(HOST, PORT);
  19402. // Non-streaming
  19403. {
  19404. auto res = cli.Get(path);
  19405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19406. EXPECT_EQ(StatusCode::OK_200, res->status);
  19407. EXPECT_EQ(original, res->body);
  19408. }
  19409. // Streaming
  19410. {
  19411. auto h = cli.open_stream("GET", path);
  19412. ASSERT_TRUE(h.is_valid());
  19413. EXPECT_EQ(original, read_all(h));
  19414. }
  19415. }
  19416. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19417. TEST(ParityTest, Gzip) {
  19418. test_compression_parity<detail::gzip_compressor>(
  19419. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19420. }
  19421. #endif
  19422. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19423. TEST(ParityTest, Brotli) {
  19424. test_compression_parity<detail::brotli_compressor>(
  19425. "Hello, brotli parity test payload", "/parity-br", "br");
  19426. }
  19427. #endif
  19428. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19429. TEST(ParityTest, Zstd) {
  19430. test_compression_parity<detail::zstd_compressor>(
  19431. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19432. }
  19433. #endif
  19434. //==============================================================================
  19435. // New Stream API Tests
  19436. //==============================================================================
  19437. inline std::string read_body(httplib::stream::Result &result) {
  19438. std::string body;
  19439. while (result.next()) {
  19440. body.append(result.data(), result.size());
  19441. }
  19442. return body;
  19443. }
  19444. TEST(ClientConnectionTest, Basic) {
  19445. httplib::ClientConnection conn;
  19446. EXPECT_FALSE(conn.is_open());
  19447. conn.sock = 1;
  19448. EXPECT_TRUE(conn.is_open());
  19449. httplib::ClientConnection conn2(std::move(conn));
  19450. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19451. conn2.sock = INVALID_SOCKET;
  19452. }
  19453. // Unified test server for all stream::* tests
  19454. class StreamApiTest : public ::testing::Test {
  19455. protected:
  19456. void SetUp() override {
  19457. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19458. res.set_content("Hello World!", "text/plain");
  19459. });
  19460. svr_.Get("/echo-params",
  19461. [](const httplib::Request &req, httplib::Response &res) {
  19462. std::string r;
  19463. for (const auto &p : req.params) {
  19464. if (!r.empty()) r += "&";
  19465. r += p.first + "=" + p.second;
  19466. }
  19467. res.set_content(r, "text/plain");
  19468. });
  19469. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19470. res.set_content(req.body, req.get_header_value("Content-Type"));
  19471. });
  19472. svr_.Post("/echo-headers",
  19473. [](const httplib::Request &req, httplib::Response &res) {
  19474. std::string r;
  19475. for (const auto &h : req.headers)
  19476. r += h.first + ": " + h.second + "\n";
  19477. res.set_content(r, "text/plain");
  19478. });
  19479. svr_.Post("/echo-params",
  19480. [](const httplib::Request &req, httplib::Response &res) {
  19481. std::string r = "params:";
  19482. for (const auto &p : req.params)
  19483. r += p.first + "=" + p.second + ";";
  19484. res.set_content(r + " body:" + req.body, "text/plain");
  19485. });
  19486. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19487. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19488. });
  19489. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19490. res.set_content("PUT:" + req.body, "text/plain");
  19491. });
  19492. svr_.Patch("/echo",
  19493. [](const httplib::Request &req, httplib::Response &res) {
  19494. res.set_content("PATCH:" + req.body, "text/plain");
  19495. });
  19496. svr_.Delete(
  19497. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19498. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19499. "text/plain");
  19500. });
  19501. svr_.Get("/head-test",
  19502. [](const httplib::Request &, httplib::Response &res) {
  19503. res.set_content("body for HEAD", "text/plain");
  19504. });
  19505. svr_.Options("/options",
  19506. [](const httplib::Request &, httplib::Response &res) {
  19507. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19508. });
  19509. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19510. svr_.wait_until_ready();
  19511. }
  19512. void TearDown() override {
  19513. svr_.stop();
  19514. if (thread_.joinable()) thread_.join();
  19515. }
  19516. httplib::Server svr_;
  19517. std::thread thread_;
  19518. };
  19519. // stream::Get tests
  19520. TEST_F(StreamApiTest, GetBasic) {
  19521. httplib::Client cli(HOST, PORT);
  19522. auto result = httplib::stream::Get(cli, "/hello");
  19523. ASSERT_TRUE(result.is_valid());
  19524. EXPECT_EQ(200, result.status());
  19525. EXPECT_EQ("Hello World!", read_body(result));
  19526. }
  19527. TEST_F(StreamApiTest, GetWithParams) {
  19528. httplib::Client cli(HOST, PORT);
  19529. httplib::Params params{{"foo", "bar"}};
  19530. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19531. ASSERT_TRUE(result.is_valid());
  19532. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19533. }
  19534. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19535. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19536. httplib::Client cli(HOST, PORT);
  19537. cli.set_payload_max_length(0);
  19538. auto result = httplib::stream::Get(cli, "/hello");
  19539. ASSERT_TRUE(result.is_valid());
  19540. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19541. EXPECT_EQ("Hello World!", read_body(result));
  19542. }
  19543. #endif
  19544. TEST_F(StreamApiTest, GetConnectionError) {
  19545. httplib::Client cli(HOST, 9999);
  19546. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19547. }
  19548. TEST_F(StreamApiTest, Get404) {
  19549. httplib::Client cli(HOST, PORT);
  19550. auto result = httplib::stream::Get(cli, "/nonexistent");
  19551. EXPECT_TRUE(result.is_valid());
  19552. EXPECT_EQ(404, result.status());
  19553. }
  19554. // stream::Post tests
  19555. TEST_F(StreamApiTest, PostBasic) {
  19556. httplib::Client cli(HOST, PORT);
  19557. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19558. "application/json");
  19559. ASSERT_TRUE(result.is_valid());
  19560. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19561. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19562. }
  19563. TEST_F(StreamApiTest, PostWithHeaders) {
  19564. httplib::Client cli(HOST, PORT);
  19565. httplib::Headers headers{{"X-Custom", "value"}};
  19566. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19567. "text/plain");
  19568. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19569. }
  19570. TEST_F(StreamApiTest, PostWithParams) {
  19571. httplib::Client cli(HOST, PORT);
  19572. httplib::Params params{{"k", "v"}};
  19573. auto result =
  19574. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19575. auto body = read_body(result);
  19576. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19577. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19578. }
  19579. TEST_F(StreamApiTest, PostLarge) {
  19580. httplib::Client cli(HOST, PORT);
  19581. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19582. size_t total = 0;
  19583. while (result.next()) {
  19584. total += result.size();
  19585. }
  19586. EXPECT_EQ(100u * 1024u, total);
  19587. }
  19588. // stream::Put/Patch tests
  19589. TEST_F(StreamApiTest, PutAndPatch) {
  19590. httplib::Client cli(HOST, PORT);
  19591. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19592. EXPECT_EQ("PUT:test", read_body(put));
  19593. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19594. EXPECT_EQ("PATCH:test", read_body(patch));
  19595. }
  19596. // stream::Delete tests
  19597. TEST_F(StreamApiTest, Delete) {
  19598. httplib::Client cli(HOST, PORT);
  19599. auto del1 = httplib::stream::Delete(cli, "/resource");
  19600. EXPECT_EQ("Deleted", read_body(del1));
  19601. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19602. EXPECT_EQ("Deleted:data", read_body(del2));
  19603. }
  19604. // stream::Head/Options tests
  19605. TEST_F(StreamApiTest, HeadAndOptions) {
  19606. httplib::Client cli(HOST, PORT);
  19607. auto head = httplib::stream::Head(cli, "/head-test");
  19608. EXPECT_TRUE(head.is_valid());
  19609. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19610. auto opts = httplib::stream::Options(cli, "/options");
  19611. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19612. }
  19613. // SSL stream::* tests
  19614. #ifdef CPPHTTPLIB_SSL_ENABLED
  19615. class SSLStreamApiTest : public ::testing::Test {
  19616. protected:
  19617. void SetUp() override {
  19618. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19619. res.set_content("Hello SSL!", "text/plain");
  19620. });
  19621. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19622. res.set_content(req.body, "text/plain");
  19623. });
  19624. port_ = svr_.bind_to_any_port("127.0.0.1");
  19625. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19626. svr_.wait_until_ready();
  19627. }
  19628. void TearDown() override {
  19629. svr_.stop();
  19630. if (thread_.joinable()) thread_.join();
  19631. }
  19632. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19633. std::thread thread_;
  19634. int port_ = 0;
  19635. };
  19636. TEST_F(SSLStreamApiTest, GetAndPost) {
  19637. httplib::SSLClient cli("127.0.0.1", port_);
  19638. cli.enable_server_certificate_verification(false);
  19639. auto get = httplib::stream::Get(cli, "/hello");
  19640. EXPECT_EQ("Hello SSL!", read_body(get));
  19641. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19642. EXPECT_EQ("test", read_body(post));
  19643. }
  19644. #endif
  19645. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19646. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19647. // BodyReader
  19648. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19649. // Test that read timeout during streaming is detected
  19650. // Use a large content-length response where server delays mid-stream
  19651. Server svr;
  19652. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19653. // Send a large response with delay in the middle
  19654. res.set_content_provider(
  19655. 1000, // content_length
  19656. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19657. if (offset < 100) {
  19658. // Send first 100 bytes immediately
  19659. std::string data(100, 'A');
  19660. sink.write(data.c_str(), data.size());
  19661. return true;
  19662. }
  19663. // Then delay longer than client timeout
  19664. std::this_thread::sleep_for(std::chrono::seconds(3));
  19665. std::string data(900, 'B');
  19666. sink.write(data.c_str(), data.size());
  19667. return true;
  19668. });
  19669. });
  19670. auto port = 8091;
  19671. std::thread t([&]() { svr.listen("localhost", port); });
  19672. svr.wait_until_ready();
  19673. Client cli("localhost", port);
  19674. cli.set_read_timeout(1, 0); // 1 second timeout
  19675. auto handle = cli.open_stream("GET", "/slow-stream");
  19676. ASSERT_TRUE(handle.is_valid());
  19677. char buf[256];
  19678. ssize_t total = 0;
  19679. ssize_t n;
  19680. bool got_error = false;
  19681. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19682. total += n;
  19683. }
  19684. if (n < 0) {
  19685. got_error = true;
  19686. // Should be timeout or read error
  19687. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19688. handle.get_read_error() == Error::Read)
  19689. << "Actual error: " << to_string(handle.get_read_error());
  19690. }
  19691. // Either we got an error, or we got less data than expected
  19692. EXPECT_TRUE(got_error || total < 1000)
  19693. << "Expected timeout but got all " << total << " bytes";
  19694. svr.stop();
  19695. t.join();
  19696. }
  19697. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19698. // Test connection closed detection via BodyReader
  19699. Server svr;
  19700. std::atomic<bool> close_now{false};
  19701. svr.Get("/will-close", [&](const Request &, Response &res) {
  19702. res.set_content_provider(
  19703. 10000, // Large content_length that we won't fully send
  19704. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19705. if (offset < 100) {
  19706. std::string data(100, 'X');
  19707. sink.write(data.c_str(), data.size());
  19708. return true;
  19709. }
  19710. // Wait for signal then abort
  19711. while (!close_now) {
  19712. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19713. }
  19714. return false; // Abort - server will close connection
  19715. });
  19716. });
  19717. auto port = 8092;
  19718. std::thread t([&]() { svr.listen("localhost", port); });
  19719. svr.wait_until_ready();
  19720. Client cli("localhost", port);
  19721. auto handle = cli.open_stream("GET", "/will-close");
  19722. ASSERT_TRUE(handle.is_valid());
  19723. char buf[256];
  19724. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19725. EXPECT_GT(n, 0) << "First read should succeed";
  19726. // Signal server to close
  19727. close_now = true;
  19728. // Keep reading until error or EOF
  19729. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19730. // Keep reading
  19731. }
  19732. // Should get an error since content_length wasn't satisfied
  19733. if (n < 0) {
  19734. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19735. handle.get_read_error() == Error::Read)
  19736. << "Actual error: " << to_string(handle.get_read_error());
  19737. }
  19738. svr.stop();
  19739. t.join();
  19740. }
  19741. #ifdef CPPHTTPLIB_SSL_ENABLED
  19742. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19743. // Test that read timeout during SSL streaming is detected
  19744. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19745. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19746. res.set_content_provider(
  19747. 1000, "text/plain",
  19748. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19749. if (offset < 100) {
  19750. std::string data(100, 'A');
  19751. sink.write(data.c_str(), data.size());
  19752. return true;
  19753. }
  19754. std::this_thread::sleep_for(std::chrono::seconds(3));
  19755. std::string data(900, 'B');
  19756. sink.write(data.c_str(), data.size());
  19757. return true;
  19758. });
  19759. });
  19760. auto port = 8093;
  19761. std::thread t([&]() { svr.listen("localhost", port); });
  19762. svr.wait_until_ready();
  19763. SSLClient cli("localhost", port);
  19764. cli.enable_server_certificate_verification(false);
  19765. cli.set_read_timeout(1, 0); // 1 second timeout
  19766. auto handle = cli.open_stream("GET", "/slow-stream");
  19767. ASSERT_TRUE(handle.is_valid());
  19768. char buf[256];
  19769. ssize_t total = 0;
  19770. ssize_t n;
  19771. bool got_error = false;
  19772. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19773. total += n;
  19774. }
  19775. if (n < 0) {
  19776. got_error = true;
  19777. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19778. handle.get_read_error() == Error::Read)
  19779. << "Actual error: " << to_string(handle.get_read_error());
  19780. }
  19781. EXPECT_TRUE(got_error || total < 1000)
  19782. << "Expected timeout but got all " << total << " bytes";
  19783. svr.stop();
  19784. t.join();
  19785. }
  19786. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19787. // Test SSL connection closed detection
  19788. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19789. std::atomic<bool> close_now{false};
  19790. svr.Get("/will-close", [&](const Request &, Response &res) {
  19791. res.set_content_provider(
  19792. 10000, "text/plain",
  19793. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19794. if (offset < 100) {
  19795. std::string data(100, 'X');
  19796. sink.write(data.c_str(), data.size());
  19797. return true;
  19798. }
  19799. while (!close_now) {
  19800. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19801. }
  19802. return false;
  19803. });
  19804. });
  19805. auto port = 8094;
  19806. std::thread t([&]() { svr.listen("localhost", port); });
  19807. svr.wait_until_ready();
  19808. SSLClient cli("localhost", port);
  19809. cli.enable_server_certificate_verification(false);
  19810. auto handle = cli.open_stream("GET", "/will-close");
  19811. ASSERT_TRUE(handle.is_valid());
  19812. char buf[256];
  19813. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19814. EXPECT_GT(n, 0);
  19815. // Signal server to close
  19816. close_now = true;
  19817. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19818. // Keep reading
  19819. }
  19820. if (n < 0) {
  19821. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19822. handle.get_read_error() == Error::Read)
  19823. << "Actual error: " << to_string(handle.get_read_error());
  19824. }
  19825. svr.stop();
  19826. t.join();
  19827. }
  19828. #endif
  19829. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19830. using namespace httplib;
  19831. // Create a test file
  19832. const char *fname = "etag_testfile.txt";
  19833. const char *content = "etag-content";
  19834. {
  19835. std::ofstream ofs(fname);
  19836. ofs << content;
  19837. ASSERT_TRUE(ofs.good());
  19838. }
  19839. Server svr;
  19840. svr.set_mount_point("/static", ".");
  19841. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19842. svr.wait_until_ready();
  19843. Client cli(HOST, PORT);
  19844. // First request: should get 200 with ETag header
  19845. auto res1 = cli.Get("/static/etag_testfile.txt");
  19846. ASSERT_TRUE(res1);
  19847. ASSERT_EQ(200, res1->status);
  19848. ASSERT_TRUE(res1->has_header("ETag"));
  19849. std::string etag = res1->get_header_value("ETag");
  19850. EXPECT_FALSE(etag.empty());
  19851. // Verify ETag format: W/"hex-hex"
  19852. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19853. EXPECT_EQ('W', etag[0]);
  19854. EXPECT_EQ('/', etag[1]);
  19855. EXPECT_EQ('"', etag[2]);
  19856. EXPECT_EQ('"', etag.back());
  19857. // Exact match: expect 304 Not Modified
  19858. Headers h2 = {{"If-None-Match", etag}};
  19859. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19860. ASSERT_TRUE(res2);
  19861. EXPECT_EQ(304, res2->status);
  19862. // Wildcard match: expect 304 Not Modified
  19863. Headers h3 = {{"If-None-Match", "*"}};
  19864. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19865. ASSERT_TRUE(res3);
  19866. EXPECT_EQ(304, res3->status);
  19867. // Non-matching ETag: expect 200
  19868. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19869. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19870. ASSERT_TRUE(res4);
  19871. EXPECT_EQ(200, res4->status);
  19872. // Multiple ETags with one matching: expect 304
  19873. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19874. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19875. ASSERT_TRUE(res5);
  19876. EXPECT_EQ(304, res5->status);
  19877. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19878. // that equivalent to the single comma-separated list above, so the match on
  19879. // the second line must still be found.
  19880. Headers h6;
  19881. h6.emplace("If-None-Match", "W/\"other\"");
  19882. h6.emplace("If-None-Match", etag);
  19883. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19884. ASSERT_TRUE(res6);
  19885. EXPECT_EQ(304, res6->status);
  19886. svr.stop();
  19887. t.join();
  19888. std::remove(fname);
  19889. }
  19890. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19891. using namespace httplib;
  19892. Server svr;
  19893. svr.set_mount_point("/static", ".");
  19894. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19895. svr.wait_until_ready();
  19896. Client cli(HOST, PORT);
  19897. // Send If-None-Match: * to a non-existent file
  19898. Headers h = {{"If-None-Match", "*"}};
  19899. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19901. EXPECT_EQ(404, res->status);
  19902. svr.stop();
  19903. t.join();
  19904. }
  19905. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19906. using namespace httplib;
  19907. // Create a test file
  19908. const char *fname = "etag_boundary_testfile.txt";
  19909. const char *content = "boundary-test";
  19910. {
  19911. std::ofstream ofs(fname);
  19912. ofs << content;
  19913. ASSERT_TRUE(ofs.good());
  19914. }
  19915. Server svr;
  19916. svr.set_mount_point("/static", ".");
  19917. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19918. svr.wait_until_ready();
  19919. Client cli(HOST, PORT);
  19920. // Get the actual ETag
  19921. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19922. ASSERT_TRUE(res1);
  19923. ASSERT_EQ(200, res1->status);
  19924. ASSERT_TRUE(res1->has_header("ETag"));
  19925. std::string etag = res1->get_header_value("ETag");
  19926. // Test 1: Very long ETag value (longer than actual ETag)
  19927. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19928. Headers h1 = {{"If-None-Match", "W/"
  19929. "\"very-long-etag-value-that-is-much-longer-"
  19930. "than-the-actual-etag-value\""}};
  19931. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19932. ASSERT_TRUE(res2);
  19933. EXPECT_EQ(200, res2->status); // Should not match
  19934. // Test 2: Long string followed by wildcard
  19935. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19936. // string)
  19937. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19938. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19939. ASSERT_TRUE(res3);
  19940. EXPECT_EQ(304, res3->status); // Should match on "*"
  19941. // Test 3: Wildcard followed by long string
  19942. // Should match on "*" immediately and return 304
  19943. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19944. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19945. ASSERT_TRUE(res4);
  19946. EXPECT_EQ(304, res4->status); // Should match on "*"
  19947. // Test 4: Multiple long non-matching values
  19948. // Should NOT match and return 200 (test that all comparisons are safe)
  19949. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19950. "W/\"second-long-non-matching-value\", "
  19951. "W/\"third-long-non-matching-value\""}};
  19952. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19953. ASSERT_TRUE(res5);
  19954. EXPECT_EQ(200, res5->status); // Should not match
  19955. // Test 5: Single character that is not "*" (edge case)
  19956. Headers h5 = {{"If-None-Match", "X"}};
  19957. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19958. ASSERT_TRUE(res6);
  19959. EXPECT_EQ(200, res6->status); // Should not match
  19960. svr.stop();
  19961. t.join();
  19962. std::remove(fname);
  19963. }
  19964. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19965. using namespace httplib;
  19966. // Create a test file
  19967. const char *fname = "ims_testfile.txt";
  19968. const char *content = "if-modified-since-test";
  19969. {
  19970. std::ofstream ofs(fname);
  19971. ofs << content;
  19972. ASSERT_TRUE(ofs.good());
  19973. }
  19974. Server svr;
  19975. svr.set_mount_point("/static", ".");
  19976. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19977. svr.wait_until_ready();
  19978. Client cli(HOST, PORT);
  19979. // First request: should get 200 with Last-Modified header
  19980. auto res1 = cli.Get("/static/ims_testfile.txt");
  19981. ASSERT_TRUE(res1);
  19982. ASSERT_EQ(200, res1->status);
  19983. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19984. std::string last_modified = res1->get_header_value("Last-Modified");
  19985. EXPECT_FALSE(last_modified.empty());
  19986. // If-Modified-Since with same time: expect 304
  19987. Headers h2 = {{"If-Modified-Since", last_modified}};
  19988. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19989. ASSERT_TRUE(res2);
  19990. EXPECT_EQ(304, res2->status);
  19991. // If-Modified-Since with future time: expect 304
  19992. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19993. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19994. ASSERT_TRUE(res3);
  19995. EXPECT_EQ(304, res3->status);
  19996. // If-Modified-Since with past time: expect 200
  19997. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19998. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19999. ASSERT_TRUE(res4);
  20000. EXPECT_EQ(200, res4->status);
  20001. // If-None-Match takes precedence over If-Modified-Since
  20002. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20003. ASSERT_TRUE(res1->has_header("ETag"));
  20004. std::string etag = res1->get_header_value("ETag");
  20005. Headers h5 = {{"If-None-Match", etag},
  20006. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20007. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20008. ASSERT_TRUE(res5);
  20009. EXPECT_EQ(304, res5->status);
  20010. svr.stop();
  20011. t.join();
  20012. std::remove(fname);
  20013. }
  20014. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20015. using namespace httplib;
  20016. Server svr;
  20017. // Endpoint that returns compressible content
  20018. svr.Get("/compressible", [](const Request &, Response &res) {
  20019. // Return a large enough body to trigger compression
  20020. std::string body(1000, 'a');
  20021. res.set_content(body, "text/plain");
  20022. });
  20023. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20024. svr.wait_until_ready();
  20025. Client cli(HOST, PORT);
  20026. // Request with gzip support: should get Vary header when compressed
  20027. cli.set_compress(true);
  20028. auto res1 = cli.Get("/compressible");
  20029. ASSERT_TRUE(res1);
  20030. EXPECT_EQ(200, res1->status);
  20031. // If Content-Encoding is set, Vary should also be set
  20032. if (res1->has_header("Content-Encoding")) {
  20033. EXPECT_TRUE(res1->has_header("Vary"));
  20034. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20035. }
  20036. // Request without Accept-Encoding header: should not have compression
  20037. Headers h_no_compress;
  20038. auto res2 = cli.Get("/compressible", h_no_compress);
  20039. ASSERT_TRUE(res2);
  20040. EXPECT_EQ(200, res2->status);
  20041. // Verify Vary header is present when compression is applied
  20042. // (the exact behavior depends on server configuration)
  20043. svr.stop();
  20044. t.join();
  20045. }
  20046. TEST(ETagTest, IfRangeWithETag) {
  20047. using namespace httplib;
  20048. // Create a test file with known content
  20049. const char *fname = "if_range_testfile.txt";
  20050. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20051. {
  20052. std::ofstream ofs(fname);
  20053. ofs << content;
  20054. ASSERT_TRUE(ofs.good());
  20055. }
  20056. Server svr;
  20057. svr.set_mount_point("/static", ".");
  20058. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20059. svr.wait_until_ready();
  20060. Client cli(HOST, PORT);
  20061. // First request: get ETag
  20062. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20063. ASSERT_TRUE(res1);
  20064. ASSERT_EQ(200, res1->status);
  20065. ASSERT_TRUE(res1->has_header("ETag"));
  20066. std::string etag = res1->get_header_value("ETag");
  20067. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20068. // Since our server generates weak ETags (W/"..."), If-Range with our
  20069. // ETag should NOT result in partial content - it should return full content.
  20070. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20071. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20072. ASSERT_TRUE(res2);
  20073. // Weak ETag in If-Range -> full content (200), not partial (206)
  20074. EXPECT_EQ(200, res2->status);
  20075. EXPECT_EQ(content, res2->body);
  20076. EXPECT_FALSE(res2->has_header("Content-Range"));
  20077. // Range request with non-matching If-Range (ETag): should get 200 (full
  20078. // content)
  20079. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20080. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20081. ASSERT_TRUE(res3);
  20082. EXPECT_EQ(200, res3->status);
  20083. EXPECT_EQ(content, res3->body);
  20084. EXPECT_FALSE(res3->has_header("Content-Range"));
  20085. // Range request with strong ETag (hypothetical - our server doesn't generate
  20086. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20087. // should return full content)
  20088. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20089. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20090. ASSERT_TRUE(res4);
  20091. EXPECT_EQ(200, res4->status);
  20092. EXPECT_EQ(content, res4->body);
  20093. EXPECT_FALSE(res4->has_header("Content-Range"));
  20094. svr.stop();
  20095. t.join();
  20096. std::remove(fname);
  20097. }
  20098. TEST(ETagTest, IfRangeWithDate) {
  20099. using namespace httplib;
  20100. // Create a test file
  20101. const char *fname = "if_range_date_testfile.txt";
  20102. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20103. {
  20104. std::ofstream ofs(fname);
  20105. ofs << content;
  20106. ASSERT_TRUE(ofs.good());
  20107. }
  20108. Server svr;
  20109. svr.set_mount_point("/static", ".");
  20110. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20111. svr.wait_until_ready();
  20112. Client cli(HOST, PORT);
  20113. // First request: get Last-Modified
  20114. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20115. ASSERT_TRUE(res1);
  20116. ASSERT_EQ(200, res1->status);
  20117. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20118. std::string last_modified = res1->get_header_value("Last-Modified");
  20119. // Range request with matching If-Range (date): should get 206
  20120. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20121. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20122. ASSERT_TRUE(res2);
  20123. EXPECT_EQ(206, res2->status);
  20124. EXPECT_EQ("FGHIJ", res2->body);
  20125. // Range request with old If-Range date: should get 200 (full content)
  20126. Headers h3 = {{"Range", "bytes=5-9"},
  20127. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20128. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20129. ASSERT_TRUE(res3);
  20130. EXPECT_EQ(200, res3->status);
  20131. EXPECT_EQ(content, res3->body);
  20132. // Range request with future If-Range date: should get 206
  20133. Headers h4 = {{"Range", "bytes=0-4"},
  20134. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20135. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20136. ASSERT_TRUE(res4);
  20137. EXPECT_EQ(206, res4->status);
  20138. EXPECT_EQ("ABCDE", res4->body);
  20139. svr.stop();
  20140. t.join();
  20141. std::remove(fname);
  20142. }
  20143. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20144. using namespace httplib;
  20145. const char *fname = "etag_malformed.txt";
  20146. const char *content = "malformed-etag";
  20147. {
  20148. std::ofstream ofs(fname);
  20149. ofs << content;
  20150. ASSERT_TRUE(ofs.good());
  20151. }
  20152. Server svr;
  20153. svr.set_mount_point("/static", ".");
  20154. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20155. svr.wait_until_ready();
  20156. Client cli(HOST, PORT);
  20157. // baseline: should get 200 and an ETag
  20158. auto res1 = cli.Get("/static/etag_malformed.txt");
  20159. ASSERT_TRUE(res1);
  20160. ASSERT_EQ(200, res1->status);
  20161. ASSERT_TRUE(res1->has_header("ETag"));
  20162. // Malformed ETag value (missing quotes) should be treated as non-matching
  20163. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20164. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20165. ASSERT_TRUE(res_bad);
  20166. EXPECT_EQ(200, res_bad->status);
  20167. // Whitespace-only header value should be considered invalid / non-matching
  20168. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20169. "Host: localhost\r\n"
  20170. "If-None-Match: \r\n"
  20171. "Connection: close\r\n"
  20172. "\r\n";
  20173. std::string out;
  20174. ASSERT_TRUE(send_request(5, raw_req, &out));
  20175. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20176. svr.stop();
  20177. t.join();
  20178. std::remove(fname);
  20179. }
  20180. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20181. using namespace httplib;
  20182. const char *fname = "ims_invalid_format.txt";
  20183. const char *content = "ims-bad-format";
  20184. {
  20185. std::ofstream ofs(fname);
  20186. ofs << content;
  20187. ASSERT_TRUE(ofs.good());
  20188. }
  20189. Server svr;
  20190. svr.set_mount_point("/static", ".");
  20191. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20192. svr.wait_until_ready();
  20193. Client cli(HOST, PORT);
  20194. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20195. ASSERT_TRUE(res1);
  20196. ASSERT_EQ(200, res1->status);
  20197. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20198. // If-Modified-Since with invalid format should not result in 304
  20199. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20200. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20201. ASSERT_TRUE(res_bad);
  20202. EXPECT_EQ(200, res_bad->status);
  20203. // If-Range with invalid date format should be treated as mismatch -> full
  20204. // content (200)
  20205. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20206. {"If-Range", "invalid-date"}};
  20207. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20208. ASSERT_TRUE(res_ifrange);
  20209. EXPECT_EQ(200, res_ifrange->status);
  20210. svr.stop();
  20211. t.join();
  20212. std::remove(fname);
  20213. }
  20214. TEST(ETagTest, IfRangeWithMalformedETag) {
  20215. using namespace httplib;
  20216. const char *fname = "ifrange_malformed.txt";
  20217. const std::string content = "0123456789";
  20218. {
  20219. std::ofstream ofs(fname);
  20220. ofs << content;
  20221. ASSERT_TRUE(ofs.good());
  20222. }
  20223. Server svr;
  20224. svr.set_mount_point("/static", ".");
  20225. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20226. svr.wait_until_ready();
  20227. Client cli(HOST, PORT);
  20228. // First request: get ETag
  20229. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20230. ASSERT_TRUE(res1);
  20231. ASSERT_EQ(200, res1->status);
  20232. ASSERT_TRUE(res1->has_header("ETag"));
  20233. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20234. // full content (200)
  20235. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20236. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20237. ASSERT_TRUE(res2);
  20238. EXPECT_EQ(200, res2->status);
  20239. EXPECT_EQ(content, res2->body);
  20240. svr.stop();
  20241. t.join();
  20242. std::remove(fname);
  20243. }
  20244. TEST(ETagTest, ExtremeLargeDateValues) {
  20245. using namespace httplib;
  20246. const char *fname = "ims_extreme_date.txt";
  20247. const char *content = "ims-extreme-date";
  20248. {
  20249. std::ofstream ofs(fname);
  20250. ofs << content;
  20251. ASSERT_TRUE(ofs.good());
  20252. }
  20253. Server svr;
  20254. svr.set_mount_point("/static", ".");
  20255. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20256. svr.wait_until_ready();
  20257. Client cli(HOST, PORT);
  20258. auto res1 = cli.Get(std::string("/static/") + fname);
  20259. ASSERT_TRUE(res1);
  20260. ASSERT_EQ(200, res1->status);
  20261. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20262. // Extremely large year that may overflow date parsing routines.
  20263. Headers h_large_date = {
  20264. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20265. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20266. ASSERT_TRUE(res_bad);
  20267. // Expect server to treat this as invalid/mismatch and return full content
  20268. EXPECT_EQ(200, res_bad->status);
  20269. // If-Range with extremely large date should be treated as mismatch -> full
  20270. // content (200)
  20271. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20272. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20273. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20274. ASSERT_TRUE(res_ifrange);
  20275. EXPECT_EQ(200, res_ifrange->status);
  20276. svr.stop();
  20277. t.join();
  20278. std::remove(fname);
  20279. }
  20280. TEST(ETagTest, NegativeFileModificationTime) {
  20281. using namespace httplib;
  20282. const char *fname = "ims_negative_mtime.txt";
  20283. const std::string content = "negative-mtime";
  20284. {
  20285. std::ofstream ofs(fname);
  20286. ofs << content;
  20287. ASSERT_TRUE(ofs.good());
  20288. }
  20289. // Try to set file mtime to a negative value. This may fail on some
  20290. // platforms/filesystems; if it fails, the test will still verify server
  20291. // behaves safely by performing a regular conditional request.
  20292. #if defined(__APPLE__) || defined(__linux__)
  20293. bool set_negative = false;
  20294. do {
  20295. struct timeval times[2];
  20296. // access time: now
  20297. times[0].tv_sec = time(nullptr);
  20298. times[0].tv_usec = 0;
  20299. // modification time: negative (e.g., -1)
  20300. times[1].tv_sec = -1;
  20301. times[1].tv_usec = 0;
  20302. if (utimes(fname, times) == 0) { set_negative = true; }
  20303. } while (0);
  20304. #else
  20305. bool set_negative = false;
  20306. #endif
  20307. Server svr;
  20308. svr.set_mount_point("/static", ".");
  20309. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20310. svr.wait_until_ready();
  20311. Client cli(HOST, PORT);
  20312. auto res1 = cli.Get(std::string("/static/") + fname);
  20313. ASSERT_TRUE(res1);
  20314. ASSERT_EQ(200, res1->status);
  20315. bool has_last_modified = res1->has_header("Last-Modified");
  20316. std::string last_modified;
  20317. if (has_last_modified) {
  20318. last_modified = res1->get_header_value("Last-Modified");
  20319. }
  20320. if (set_negative) {
  20321. // If we successfully set a negative mtime, ensure server returns a
  20322. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20323. // with an old date and ensure server handles it without crash.
  20324. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20325. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20326. ASSERT_TRUE(res2);
  20327. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20328. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20329. } else {
  20330. // Could not set negative mtime on this platform; fall back to verifying
  20331. // that normal invalid/malformed dates are treated safely (non-304).
  20332. Headers h_bad_date = {
  20333. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20334. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20335. ASSERT_TRUE(res_bad);
  20336. EXPECT_EQ(200, res_bad->status);
  20337. }
  20338. svr.stop();
  20339. t.join();
  20340. std::remove(fname);
  20341. }
  20342. //==============================================================================
  20343. // Integration Tests with Server
  20344. //==============================================================================
  20345. class SSEIntegrationTest : public ::testing::Test {
  20346. protected:
  20347. void SetUp() override {
  20348. stop_server_.store(false);
  20349. events_.clear();
  20350. server_ = httplib::detail::make_unique<Server>();
  20351. setup_server();
  20352. start_server();
  20353. }
  20354. void TearDown() override {
  20355. stop_server_.store(true);
  20356. event_cv_.notify_all();
  20357. server_->stop();
  20358. if (server_thread_.joinable()) { server_thread_.join(); }
  20359. }
  20360. void setup_server() {
  20361. // Simple SSE endpoint
  20362. server_->Get("/events", [this](const Request &req, Response &res) {
  20363. auto last_id = req.get_header_value("Last-Event-ID");
  20364. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20365. res.set_chunked_content_provider(
  20366. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20367. std::unique_lock<std::mutex> lock(event_mutex_);
  20368. if (event_cv_.wait_for(
  20369. lock, std::chrono::milliseconds(200), [this] {
  20370. return !events_.empty() || stop_server_.load();
  20371. })) {
  20372. if (stop_server_.load()) { return false; }
  20373. if (!events_.empty()) {
  20374. std::string event = events_.front();
  20375. events_.erase(events_.begin());
  20376. sink.write(event.data(), event.size());
  20377. return true;
  20378. }
  20379. }
  20380. return !stop_server_.load();
  20381. });
  20382. });
  20383. // Endpoint that returns error
  20384. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20385. res.status = 500;
  20386. res.set_content("Internal Server Error", "text/plain");
  20387. });
  20388. // Endpoint for custom event types
  20389. server_->Get("/custom-events", [](const Request &, Response &res) {
  20390. res.set_chunked_content_provider(
  20391. "text/event-stream", [](size_t offset, DataSink &sink) {
  20392. if (offset == 0) {
  20393. std::string event = "event: update\ndata: updated\n\n"
  20394. "event: delete\ndata: deleted\n\n";
  20395. sink.write(event.data(), event.size());
  20396. }
  20397. return false; // End stream after sending
  20398. });
  20399. });
  20400. }
  20401. void start_server() {
  20402. port_ = server_->bind_to_any_port(HOST);
  20403. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20404. // Wait for server to start
  20405. while (!server_->is_running()) {
  20406. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20407. }
  20408. }
  20409. int get_port() const { return port_; }
  20410. void send_event(const std::string &event) {
  20411. std::lock_guard<std::mutex> lock(event_mutex_);
  20412. events_.push_back(event);
  20413. event_cv_.notify_all();
  20414. }
  20415. std::unique_ptr<Server> server_;
  20416. std::thread server_thread_;
  20417. std::mutex event_mutex_;
  20418. std::condition_variable event_cv_;
  20419. std::vector<std::string> events_;
  20420. std::atomic<bool> stop_server_{false};
  20421. std::string last_received_event_id_;
  20422. int port_ = 0;
  20423. };
  20424. //==============================================================================
  20425. // SSE Parsing Tests
  20426. //==============================================================================
  20427. class SSEParsingTest : public SSEIntegrationTest {
  20428. protected:
  20429. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20430. // A trailing sentinel event tells when the whole stream has been parsed.
  20431. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20432. auto body = stream + "event: end\ndata: end\n\n";
  20433. server_->Get("/parse", [body](const Request &, Response &res) {
  20434. res.set_content(body, "text/event-stream");
  20435. });
  20436. return collect("/parse");
  20437. }
  20438. // Runs SSEClient against path until an "end" event arrives and returns the
  20439. // messages dispatched before it
  20440. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20441. Client client(HOST, get_port());
  20442. sse::SSEClient sse(client, path);
  20443. std::mutex mutex;
  20444. std::condition_variable cv;
  20445. std::vector<sse::SSEMessage> messages;
  20446. auto done = false;
  20447. sse.on_message([&](const sse::SSEMessage &msg) {
  20448. std::lock_guard<std::mutex> lock(mutex);
  20449. // Ignore a replay from a reconnect that races with stop()
  20450. if (!done) { messages.push_back(msg); }
  20451. });
  20452. sse.on_event("end", [&](const sse::SSEMessage &) {
  20453. std::lock_guard<std::mutex> lock(mutex);
  20454. done = true;
  20455. cv.notify_all();
  20456. });
  20457. sse.set_reconnect_interval(100);
  20458. sse.start_async();
  20459. {
  20460. std::unique_lock<std::mutex> lock(mutex);
  20461. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20462. }
  20463. sse.stop();
  20464. EXPECT_TRUE(done);
  20465. return messages;
  20466. }
  20467. };
  20468. TEST_F(SSEParsingTest, SingleLineData) {
  20469. auto msgs = parse("data: hello\n\n");
  20470. ASSERT_EQ(msgs.size(), 1u);
  20471. EXPECT_EQ(msgs[0].data, "hello");
  20472. EXPECT_EQ(msgs[0].event, "message");
  20473. }
  20474. TEST_F(SSEParsingTest, MultiLineData) {
  20475. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20476. ASSERT_EQ(msgs.size(), 1u);
  20477. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20478. }
  20479. TEST_F(SSEParsingTest, CustomEventType) {
  20480. auto msgs = parse("event: update\ndata: payload\n\n");
  20481. ASSERT_EQ(msgs.size(), 1u);
  20482. EXPECT_EQ(msgs[0].event, "update");
  20483. EXPECT_EQ(msgs[0].data, "payload");
  20484. }
  20485. TEST_F(SSEParsingTest, EventIdHandling) {
  20486. auto msgs = parse("id: 12345\ndata: test\n\n");
  20487. ASSERT_EQ(msgs.size(), 1u);
  20488. EXPECT_EQ(msgs[0].id, "12345");
  20489. }
  20490. TEST_F(SSEParsingTest, EmptyEventId) {
  20491. auto msgs = parse("id:\ndata: test\n\n");
  20492. ASSERT_EQ(msgs.size(), 1u);
  20493. EXPECT_EQ(msgs[0].id, "");
  20494. }
  20495. TEST_F(SSEParsingTest, CommentsIgnored) {
  20496. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20497. ASSERT_EQ(msgs.size(), 1u);
  20498. EXPECT_EQ(msgs[0].data, "hello");
  20499. EXPECT_EQ(msgs[0].event, "message");
  20500. }
  20501. TEST_F(SSEParsingTest, ColonInValue) {
  20502. auto msgs = parse("data: hello:world:test\n\n");
  20503. ASSERT_EQ(msgs.size(), 1u);
  20504. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20505. }
  20506. TEST_F(SSEParsingTest, FieldNameOnly) {
  20507. // A line without a colon is a field name with an empty value
  20508. auto msgs = parse("data\n\n");
  20509. ASSERT_EQ(msgs.size(), 1u);
  20510. EXPECT_EQ(msgs[0].data, "");
  20511. }
  20512. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20513. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20514. ASSERT_EQ(msgs.size(), 1u);
  20515. EXPECT_EQ(msgs[0].event, "update");
  20516. EXPECT_EQ(msgs[0].data, "hello");
  20517. }
  20518. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20519. auto msgs = parse("data\r\n\r\n");
  20520. ASSERT_EQ(msgs.size(), 1u);
  20521. EXPECT_EQ(msgs[0].data, "");
  20522. }
  20523. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20524. auto msgs = parse("event: update\rdata: hello\r\r");
  20525. ASSERT_EQ(msgs.size(), 1u);
  20526. EXPECT_EQ(msgs[0].event, "update");
  20527. EXPECT_EQ(msgs[0].data, "hello");
  20528. }
  20529. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20530. // Chunk boundaries fall inside every \r\n and right before the first one
  20531. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20532. "\n\r", "\nevent: end\ndata: end\n\n"};
  20533. server_->Get("/split", [chunks](const Request &, Response &res) {
  20534. auto i = std::make_shared<size_t>(0);
  20535. res.set_chunked_content_provider(
  20536. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20537. if (*i == chunks.size()) {
  20538. sink.done();
  20539. } else {
  20540. sink.write(chunks[*i].data(), chunks[*i].size());
  20541. (*i)++;
  20542. }
  20543. return true;
  20544. });
  20545. });
  20546. auto msgs = collect("/split");
  20547. ASSERT_EQ(msgs.size(), 1u);
  20548. EXPECT_EQ(msgs[0].event, "update");
  20549. EXPECT_EQ(msgs[0].data, "hello");
  20550. }
  20551. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20552. // Only a BOM at the start of the stream is ignored
  20553. auto msgs = parse("\xEF\xBB\xBF"
  20554. "data: first\n\n"
  20555. "\xEF\xBB\xBF"
  20556. "data: second\n\n");
  20557. ASSERT_EQ(msgs.size(), 1u);
  20558. EXPECT_EQ(msgs[0].data, "first");
  20559. }
  20560. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20561. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20562. ASSERT_EQ(msgs.size(), 1u);
  20563. EXPECT_EQ(msgs[0].data, "hello");
  20564. EXPECT_EQ(msgs[0].event, "message");
  20565. }
  20566. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20567. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20568. ASSERT_EQ(msgs.size(), 2u);
  20569. EXPECT_EQ(msgs[0].data, "hello");
  20570. EXPECT_EQ(msgs[1].data, "hello");
  20571. }
  20572. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20573. // An event without data is not dispatched, and its type must not leak
  20574. // into the next event
  20575. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20576. ASSERT_EQ(msgs.size(), 1u);
  20577. EXPECT_EQ(msgs[0].event, "message");
  20578. EXPECT_EQ(msgs[0].data, "hello");
  20579. }
  20580. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20581. // The first connection sends only an id; the second echoes back the
  20582. // Last-Event-ID it was reconnected with
  20583. std::atomic<int> connection_count{0};
  20584. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20585. if (connection_count++ == 0) {
  20586. res.set_content("id: 42\n\n", "text/event-stream");
  20587. } else {
  20588. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20589. "\n\nevent: end\ndata: end\n\n",
  20590. "text/event-stream");
  20591. }
  20592. });
  20593. auto msgs = collect("/id-only");
  20594. ASSERT_EQ(msgs.size(), 1u);
  20595. EXPECT_EQ(msgs[0].data, "42");
  20596. }
  20597. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20598. // The first connection sets an id and then clears it with an empty one; the
  20599. // second reports whether it was reconnected with a Last-Event-ID
  20600. std::atomic<int> connection_count{0};
  20601. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20602. if (connection_count++ == 0) {
  20603. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20604. "text/event-stream");
  20605. } else {
  20606. res.set_content(
  20607. std::string("data: ") +
  20608. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20609. "\n\nevent: end\ndata: end\n\n",
  20610. "text/event-stream");
  20611. }
  20612. });
  20613. auto msgs = collect("/id-clear");
  20614. ASSERT_EQ(msgs.size(), 3u);
  20615. EXPECT_EQ(msgs[0].id, "1");
  20616. EXPECT_EQ(msgs[1].id, "");
  20617. EXPECT_EQ(msgs[2].data, "not sent");
  20618. }
  20619. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20620. // The first connection sets an id and then sends ids that cannot be carried
  20621. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20622. // with
  20623. std::atomic<int> connection_count{0};
  20624. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20625. if (connection_count++ == 0) {
  20626. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20627. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20628. "text/event-stream");
  20629. } else {
  20630. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20631. "\n\nevent: end\ndata: end\n\n",
  20632. "text/event-stream");
  20633. }
  20634. });
  20635. auto msgs = collect("/id-unsendable");
  20636. ASSERT_EQ(msgs.size(), 1u);
  20637. EXPECT_EQ(msgs[0].data, "42");
  20638. }
  20639. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20640. auto msgs = parse("event: notification\nid: evt-42\n"
  20641. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20642. ASSERT_EQ(msgs.size(), 1u);
  20643. EXPECT_EQ(msgs[0].event, "notification");
  20644. EXPECT_EQ(msgs[0].id, "evt-42");
  20645. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20646. }
  20647. TEST(SSEMessageTest, Clear) {
  20648. sse::SSEMessage msg;
  20649. msg.event = "custom";
  20650. msg.data = "some data";
  20651. msg.id = "123";
  20652. msg.clear();
  20653. EXPECT_EQ(msg.event, "message");
  20654. EXPECT_EQ(msg.data, "");
  20655. EXPECT_EQ(msg.id, "");
  20656. }
  20657. //==============================================================================
  20658. // SSE Integration Tests
  20659. //==============================================================================
  20660. // Test: Successful connection and on_open callback
  20661. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20662. // Add a simple endpoint that sends one event and closes
  20663. server_->Get("/simple-event", [](const Request &, Response &res) {
  20664. res.set_chunked_content_provider(
  20665. "text/event-stream", [](size_t offset, DataSink &sink) {
  20666. if (offset == 0) {
  20667. std::string event = "data: hello\n\n";
  20668. sink.write(event.data(), event.size());
  20669. }
  20670. return false; // Close stream after sending
  20671. });
  20672. });
  20673. Client client("localhost", get_port());
  20674. sse::SSEClient sse(client, "/simple-event");
  20675. std::atomic<bool> open_called{false};
  20676. std::atomic<bool> message_received{false};
  20677. sse.on_open([&open_called]() { open_called.store(true); });
  20678. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20679. if (msg.data == "hello") { message_received.store(true); }
  20680. });
  20681. sse.set_reconnect_interval(100);
  20682. sse.set_max_reconnect_attempts(1);
  20683. // Start async
  20684. sse.start_async();
  20685. // Wait for message to be processed
  20686. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20687. sse.stop();
  20688. EXPECT_TRUE(open_called.load());
  20689. EXPECT_TRUE(message_received.load());
  20690. }
  20691. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20692. // A data line that never ends.
  20693. server_->Get("/endless-line", [](const Request &, Response &res) {
  20694. res.set_chunked_content_provider(
  20695. "text/event-stream", [](size_t offset, DataSink &sink) {
  20696. if (offset == 0) { sink.write("data: ", 6); }
  20697. std::string chunk(64 * 1024, 'A');
  20698. return sink.write(chunk.data(), chunk.size());
  20699. });
  20700. });
  20701. Client client("localhost", get_port());
  20702. sse::SSEClient sse(client, "/endless-line");
  20703. std::atomic<bool> too_long{false};
  20704. sse.on_error([&](Error err) {
  20705. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20706. });
  20707. sse.set_max_reconnect_attempts(1);
  20708. sse.start_async();
  20709. for (int i = 0; i < 500 && !too_long; i++) {
  20710. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20711. }
  20712. sse.stop();
  20713. EXPECT_TRUE(too_long);
  20714. }
  20715. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  20716. // Far more in all than the client's payload limit below.
  20717. server_->Get("/many-events", [](const Request &, Response &res) {
  20718. res.set_chunked_content_provider(
  20719. "text/event-stream", [](size_t offset, DataSink &sink) {
  20720. if (offset == 0) {
  20721. std::string events;
  20722. for (int i = 0; i < 1000; i++) {
  20723. events += "data: message\n\n";
  20724. }
  20725. sink.write(events.data(), events.size());
  20726. }
  20727. return false;
  20728. });
  20729. });
  20730. Client client("localhost", get_port());
  20731. client.set_payload_max_length(1024);
  20732. sse::SSEClient sse(client, "/many-events");
  20733. std::atomic<int> messages{0};
  20734. std::atomic<bool> too_large{false};
  20735. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  20736. sse.on_error([&](Error err) {
  20737. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  20738. });
  20739. sse.set_max_reconnect_attempts(1);
  20740. sse.start_async();
  20741. for (int i = 0; i < 500 && messages < 1000; i++) {
  20742. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20743. }
  20744. sse.stop();
  20745. EXPECT_GE(messages.load(), 1000);
  20746. EXPECT_FALSE(too_large);
  20747. }
  20748. // Test: on_message callback
  20749. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20750. // Endpoint that sends multiple events then closes
  20751. server_->Get("/multi-event", [](const Request &, Response &res) {
  20752. res.set_chunked_content_provider(
  20753. "text/event-stream", [](size_t offset, DataSink &sink) {
  20754. if (offset == 0) {
  20755. std::string events = "data: message1\n\ndata: message2\n\n";
  20756. sink.write(events.data(), events.size());
  20757. }
  20758. return false;
  20759. });
  20760. });
  20761. Client client("localhost", get_port());
  20762. sse::SSEClient sse(client, "/multi-event");
  20763. std::vector<std::string> received_messages;
  20764. std::mutex messages_mutex;
  20765. sse.on_message([&](const sse::SSEMessage &msg) {
  20766. std::lock_guard<std::mutex> lock(messages_mutex);
  20767. received_messages.push_back(msg.data);
  20768. });
  20769. sse.set_reconnect_interval(100);
  20770. sse.set_max_reconnect_attempts(1);
  20771. sse.start_async();
  20772. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20773. sse.stop();
  20774. std::lock_guard<std::mutex> lock(messages_mutex);
  20775. EXPECT_GE(received_messages.size(), 2u);
  20776. if (received_messages.size() >= 2) {
  20777. EXPECT_EQ(received_messages[0], "message1");
  20778. EXPECT_EQ(received_messages[1], "message2");
  20779. }
  20780. }
  20781. // Test: on_event for specific types
  20782. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20783. Client client("localhost", get_port());
  20784. sse::SSEClient sse(client, "/custom-events");
  20785. std::atomic<bool> update_received{false};
  20786. std::atomic<bool> delete_received{false};
  20787. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20788. if (msg.data == "updated") { update_received.store(true); }
  20789. });
  20790. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20791. if (msg.data == "deleted") { delete_received.store(true); }
  20792. });
  20793. sse.set_max_reconnect_attempts(1);
  20794. sse.start_async();
  20795. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20796. sse.stop();
  20797. EXPECT_TRUE(update_received.load());
  20798. EXPECT_TRUE(delete_received.load());
  20799. }
  20800. // Test: on_error callback on connection failure
  20801. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20802. // Connect to a non-existent port
  20803. Client client("localhost", 59999);
  20804. sse::SSEClient sse(client, "/events");
  20805. std::atomic<bool> error_called{false};
  20806. Error received_error = Error::Success;
  20807. sse.on_error([&](Error err) {
  20808. error_called.store(true);
  20809. received_error = err;
  20810. });
  20811. sse.set_reconnect_interval(50);
  20812. sse.set_max_reconnect_attempts(1);
  20813. sse.start_async();
  20814. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20815. sse.stop();
  20816. EXPECT_TRUE(error_called.load());
  20817. EXPECT_NE(received_error, Error::Success);
  20818. }
  20819. // Test: Last-Event-ID header sent on reconnect
  20820. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20821. // Endpoint that sends event with ID
  20822. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20823. res.set_chunked_content_provider(
  20824. "text/event-stream", [](size_t offset, DataSink &sink) {
  20825. if (offset == 0) {
  20826. std::string event = "id: evt-123\ndata: test\n\n";
  20827. sink.write(event.data(), event.size());
  20828. }
  20829. return false;
  20830. });
  20831. });
  20832. Client client("localhost", get_port());
  20833. sse::SSEClient sse(client, "/event-with-id");
  20834. std::atomic<bool> id_received{false};
  20835. sse.on_message([&](const sse::SSEMessage &msg) {
  20836. if (!msg.id.empty()) { id_received.store(true); }
  20837. });
  20838. sse.set_reconnect_interval(100);
  20839. sse.set_max_reconnect_attempts(1);
  20840. sse.start_async();
  20841. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20842. sse.stop();
  20843. EXPECT_TRUE(id_received.load());
  20844. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20845. }
  20846. // Test: Manual stop
  20847. TEST_F(SSEIntegrationTest, ManualStop) {
  20848. // Endpoint that sends one event and stays open briefly
  20849. std::atomic<bool> handler_running{true};
  20850. server_->Get("/stay-open", [&handler_running](const Request &,
  20851. Response &res) {
  20852. res.set_chunked_content_provider(
  20853. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20854. if (offset == 0) {
  20855. std::string event = "data: connected\n\n";
  20856. sink.write(event.data(), event.size());
  20857. }
  20858. // Keep connection open while handler_running is true
  20859. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20860. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20861. }
  20862. return false;
  20863. });
  20864. });
  20865. Client client("localhost", get_port());
  20866. sse::SSEClient sse(client, "/stay-open");
  20867. std::atomic<bool> connected{false};
  20868. sse.on_open([&connected]() { connected.store(true); });
  20869. sse.set_reconnect_interval(100);
  20870. sse.set_max_reconnect_attempts(1);
  20871. sse.start_async();
  20872. // Wait for connection to establish
  20873. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20874. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20875. }
  20876. EXPECT_TRUE(connected.load());
  20877. EXPECT_TRUE(sse.is_connected());
  20878. // Signal handler to stop
  20879. handler_running.store(false);
  20880. // Stop SSE client
  20881. sse.stop();
  20882. EXPECT_FALSE(sse.is_connected());
  20883. }
  20884. // Test: SSEClient with custom headers
  20885. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20886. // Setup a server endpoint that checks for custom header
  20887. std::atomic<bool> header_received{false};
  20888. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20889. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20890. header_received.store(true);
  20891. }
  20892. res.set_chunked_content_provider("text/event-stream",
  20893. [](size_t, DataSink &) { return false; });
  20894. });
  20895. Client client("localhost", get_port());
  20896. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20897. sse::SSEClient sse(client, "/header-check", headers);
  20898. sse.set_max_reconnect_attempts(1);
  20899. sse.start_async();
  20900. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20901. sse.stop();
  20902. EXPECT_TRUE(header_received.load());
  20903. }
  20904. // Test: Reconnect interval configuration
  20905. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20906. Client client("localhost", get_port());
  20907. sse::SSEClient sse(client, "/events");
  20908. auto &result = sse.set_reconnect_interval(500);
  20909. // Builder pattern should return reference to self
  20910. EXPECT_EQ(&result, &sse);
  20911. }
  20912. // Test: Max reconnect attempts
  20913. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20914. // Connect to non-existent port to force reconnects
  20915. Client client("localhost", 59998);
  20916. sse::SSEClient sse(client, "/events");
  20917. std::atomic<int> error_count{0};
  20918. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20919. sse.set_reconnect_interval(50);
  20920. sse.set_max_reconnect_attempts(2);
  20921. auto start = std::chrono::steady_clock::now();
  20922. sse.start(); // Blocking call
  20923. auto end = std::chrono::steady_clock::now();
  20924. // Should have stopped after 2 failed attempts
  20925. EXPECT_GE(error_count.load(), 2);
  20926. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20927. auto duration =
  20928. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20929. #ifdef _WIN32
  20930. // Windows is much slower for socket connection failures
  20931. EXPECT_LT(duration.count(), 7000);
  20932. #else
  20933. EXPECT_LT(duration.count(), 1000);
  20934. #endif
  20935. }
  20936. // Test: Multi-line data in integration
  20937. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20938. // Endpoint with multi-line data
  20939. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20940. res.set_chunked_content_provider(
  20941. "text/event-stream", [](size_t offset, DataSink &sink) {
  20942. if (offset == 0) {
  20943. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20944. sink.write(event.data(), event.size());
  20945. }
  20946. return false;
  20947. });
  20948. });
  20949. Client client("localhost", get_port());
  20950. sse::SSEClient sse(client, "/multiline-data");
  20951. std::string received_data;
  20952. std::mutex data_mutex;
  20953. sse.on_message([&](const sse::SSEMessage &msg) {
  20954. std::lock_guard<std::mutex> lock(data_mutex);
  20955. received_data = msg.data;
  20956. });
  20957. sse.set_reconnect_interval(100);
  20958. sse.set_max_reconnect_attempts(1);
  20959. sse.start_async();
  20960. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20961. sse.stop();
  20962. std::lock_guard<std::mutex> lock(data_mutex);
  20963. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20964. }
  20965. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20966. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20967. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20968. DataSink &sink) {
  20969. if (offset == 0) {
  20970. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20971. sink.write(events.data(), events.size());
  20972. }
  20973. return false;
  20974. });
  20975. });
  20976. Client client("localhost", get_port());
  20977. sse::SSEClient sse(client, "/empty-data-lines");
  20978. std::mutex mutex;
  20979. std::condition_variable cv;
  20980. std::vector<std::string> received;
  20981. sse.on_message([&](const sse::SSEMessage &msg) {
  20982. std::lock_guard<std::mutex> lock(mutex);
  20983. received.push_back(msg.data);
  20984. cv.notify_all();
  20985. });
  20986. sse.set_max_reconnect_attempts(1);
  20987. sse.start_async();
  20988. {
  20989. std::unique_lock<std::mutex> lock(mutex);
  20990. cv.wait_for(lock, std::chrono::seconds(2),
  20991. [&] { return received.size() >= 3; });
  20992. }
  20993. sse.stop();
  20994. ASSERT_GE(received.size(), 3u);
  20995. EXPECT_EQ(received[0], "");
  20996. EXPECT_EQ(received[1], "\nhello");
  20997. EXPECT_EQ(received[2], "");
  20998. }
  20999. // Test: Auto-reconnect after server disconnection
  21000. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21001. std::atomic<int> connection_count{0};
  21002. std::atomic<int> message_count{0};
  21003. // Endpoint that sends one event and closes, forcing reconnect
  21004. server_->Get("/reconnect-test",
  21005. [&connection_count](const Request &, Response &res) {
  21006. connection_count.fetch_add(1);
  21007. res.set_chunked_content_provider(
  21008. "text/event-stream", [](size_t offset, DataSink &sink) {
  21009. if (offset == 0) {
  21010. std::string event = "data: hello\n\n";
  21011. sink.write(event.data(), event.size());
  21012. }
  21013. return false; // Close connection after sending
  21014. });
  21015. });
  21016. Client client("localhost", get_port());
  21017. sse::SSEClient sse(client, "/reconnect-test");
  21018. sse.on_message([&message_count](const sse::SSEMessage &) {
  21019. message_count.fetch_add(1);
  21020. });
  21021. sse.set_reconnect_interval(100);
  21022. sse.set_max_reconnect_attempts(3);
  21023. sse.start_async();
  21024. // Wait long enough for multiple reconnects
  21025. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21026. sse.stop();
  21027. // Should have connected multiple times (initial + reconnects)
  21028. EXPECT_GE(connection_count.load(), 2);
  21029. // Should have received messages from multiple connections
  21030. EXPECT_GE(message_count.load(), 2);
  21031. }
  21032. // Test: A retry field that is not all ASCII digits is ignored
  21033. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21034. std::atomic<int> connection_count{0};
  21035. server_->Get("/bad-retry",
  21036. [&connection_count](const Request &, Response &res) {
  21037. connection_count.fetch_add(1);
  21038. res.set_chunked_content_provider(
  21039. "text/event-stream", [](size_t offset, DataSink &sink) {
  21040. if (offset == 0) {
  21041. std::string event = "retry: -1\ndata: hello\n\n";
  21042. sink.write(event.data(), event.size());
  21043. }
  21044. return false;
  21045. });
  21046. });
  21047. Client client("localhost", get_port());
  21048. sse::SSEClient sse(client, "/bad-retry");
  21049. sse.set_reconnect_interval(10000);
  21050. sse.start_async();
  21051. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21052. sse.stop();
  21053. EXPECT_EQ(connection_count.load(), 1);
  21054. }
  21055. // Test: A retry field of all ASCII digits sets the reconnection time
  21056. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21057. std::mutex mutex;
  21058. std::condition_variable cv;
  21059. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21060. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21061. {
  21062. std::lock_guard<std::mutex> lock(mutex);
  21063. connected_at.push_back(std::chrono::steady_clock::now());
  21064. cv.notify_all();
  21065. }
  21066. res.set_chunked_content_provider(
  21067. "text/event-stream", [](size_t offset, DataSink &sink) {
  21068. if (offset == 0) {
  21069. std::string event = "retry: 0\ndata: hello\n\n";
  21070. sink.write(event.data(), event.size());
  21071. }
  21072. return false;
  21073. });
  21074. });
  21075. Client client("localhost", get_port());
  21076. sse::SSEClient sse(client, "/zero-retry");
  21077. sse.set_reconnect_interval(10000);
  21078. sse.start_async();
  21079. {
  21080. std::unique_lock<std::mutex> lock(mutex);
  21081. cv.wait_for(lock, std::chrono::seconds(5),
  21082. [&] { return connected_at.size() >= 2; });
  21083. }
  21084. sse.stop();
  21085. // The server-supplied interval is applied, but never below 100ms, so
  21086. // "retry: 0" does not cause a busy reconnect loop
  21087. std::lock_guard<std::mutex> lock(mutex);
  21088. ASSERT_GE(connected_at.size(), 2u);
  21089. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21090. connected_at[1] - connected_at[0])
  21091. .count();
  21092. EXPECT_GE(interval_ms, 100);
  21093. }
  21094. // Test: Last-Event-ID sent on reconnect
  21095. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21096. std::atomic<int> connection_count{0};
  21097. std::vector<std::string> received_last_event_ids;
  21098. std::mutex id_mutex;
  21099. // Endpoint that checks Last-Event-ID header and sends event with ID
  21100. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21101. int conn = connection_count.fetch_add(1);
  21102. // Capture the Last-Event-ID header from each connection
  21103. {
  21104. std::lock_guard<std::mutex> lock(id_mutex);
  21105. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21106. }
  21107. res.set_chunked_content_provider(
  21108. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21109. if (offset == 0) {
  21110. std::string event =
  21111. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21112. sink.write(event.data(), event.size());
  21113. }
  21114. return false;
  21115. });
  21116. });
  21117. Client client("localhost", get_port());
  21118. sse::SSEClient sse(client, "/reconnect-with-id");
  21119. sse.set_reconnect_interval(100);
  21120. sse.set_max_reconnect_attempts(3);
  21121. sse.start_async();
  21122. // Wait for at least 2 connections
  21123. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21124. sse.stop();
  21125. // Verify behavior
  21126. std::lock_guard<std::mutex> lock(id_mutex);
  21127. EXPECT_GE(received_last_event_ids.size(), 2u);
  21128. // First connection should have no Last-Event-ID
  21129. if (!received_last_event_ids.empty()) {
  21130. EXPECT_EQ(received_last_event_ids[0], "");
  21131. }
  21132. // Second connection should have Last-Event-ID from first connection
  21133. if (received_last_event_ids.size() >= 2) {
  21134. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21135. }
  21136. }
  21137. // Test: set_headers updates headers used on reconnect
  21138. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21139. std::vector<std::string> received_tokens;
  21140. std::mutex token_mutex;
  21141. // Endpoint that captures Authorization header
  21142. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21143. {
  21144. std::lock_guard<std::mutex> lock(token_mutex);
  21145. received_tokens.push_back(req.get_header_value("Authorization"));
  21146. }
  21147. res.set_chunked_content_provider(
  21148. "text/event-stream", [](size_t offset, DataSink &sink) {
  21149. if (offset == 0) {
  21150. std::string event = "data: hello\n\n";
  21151. sink.write(event.data(), event.size());
  21152. }
  21153. return false; // Close connection to trigger reconnect
  21154. });
  21155. });
  21156. Client client("localhost", get_port());
  21157. Headers headers = {{"Authorization", "Bearer old-token"}};
  21158. sse::SSEClient sse(client, "/auth-check", headers);
  21159. // Update headers on each successful connection
  21160. sse.on_open(
  21161. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21162. sse.set_reconnect_interval(100);
  21163. sse.set_max_reconnect_attempts(3);
  21164. sse.start_async();
  21165. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21166. sse.stop();
  21167. std::lock_guard<std::mutex> lock(token_mutex);
  21168. ASSERT_GE(received_tokens.size(), 2u);
  21169. // First connection uses original header
  21170. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21171. // Second connection uses updated header from set_headers
  21172. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21173. }
  21174. // Test: 401 allows reconnection (so on_error can refresh headers)
  21175. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21176. std::atomic<int> connection_count{0};
  21177. // Endpoint: returns 401 on first attempt, 200 on second
  21178. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21179. int conn = connection_count.fetch_add(1);
  21180. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21181. res.status = StatusCode::Unauthorized_401;
  21182. res.set_content("Unauthorized", "text/plain");
  21183. return;
  21184. }
  21185. res.set_chunked_content_provider(
  21186. "text/event-stream", [](size_t offset, DataSink &sink) {
  21187. if (offset == 0) {
  21188. std::string event = "data: authenticated\n\n";
  21189. sink.write(event.data(), event.size());
  21190. }
  21191. return false;
  21192. });
  21193. });
  21194. Client client("localhost", get_port());
  21195. Headers headers = {{"Authorization", "Bearer expired"}};
  21196. sse::SSEClient sse(client, "/auth-retry", headers);
  21197. std::atomic<bool> message_received{false};
  21198. // Refresh token on error
  21199. sse.on_error(
  21200. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21201. sse.on_message([&](const sse::SSEMessage &msg) {
  21202. if (msg.data == "authenticated") { message_received.store(true); }
  21203. });
  21204. sse.set_reconnect_interval(100);
  21205. sse.set_max_reconnect_attempts(3);
  21206. sse.start_async();
  21207. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21208. sse.stop();
  21209. // Should have reconnected after 401 and succeeded with new token
  21210. EXPECT_GE(connection_count.load(), 2);
  21211. EXPECT_TRUE(message_received.load());
  21212. }
  21213. TEST(Issue2318Test, EmptyHostString) {
  21214. {
  21215. httplib::Client cli_empty("", PORT);
  21216. auto res = cli_empty.Get("/");
  21217. ASSERT_FALSE(res);
  21218. EXPECT_EQ(httplib::Error::Connection, res.error());
  21219. }
  21220. {
  21221. httplib::Client cli(" ", PORT);
  21222. auto res = cli.Get("/");
  21223. ASSERT_FALSE(res);
  21224. EXPECT_EQ(httplib::Error::Connection, res.error());
  21225. }
  21226. }
  21227. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21228. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21229. Server svr;
  21230. // Set a small payload limit (1KB)
  21231. svr.set_payload_max_length(1024);
  21232. svr.Post("/test", [&](const Request &req, Response &res) {
  21233. res.set_content("Body size: " + std::to_string(req.body.size()),
  21234. "text/plain");
  21235. });
  21236. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21237. auto se = detail::scope_exit([&] {
  21238. svr.stop();
  21239. listen_thread.join();
  21240. });
  21241. svr.wait_until_ready();
  21242. // Create data that compresses well but exceeds limit when decompressed
  21243. // 8KB of repeated null bytes compresses to a very small size
  21244. std::string original_data(8 * 1024, '\0');
  21245. // Compress the data using gzip
  21246. std::string compressed_data;
  21247. detail::gzip_compressor compressor;
  21248. compressor.compress(original_data.data(), original_data.size(), true,
  21249. [&](const char *data, size_t size) {
  21250. compressed_data.append(data, size);
  21251. return true;
  21252. });
  21253. // Verify compression worked (compressed should be much smaller)
  21254. ASSERT_LT(compressed_data.size(), original_data.size());
  21255. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21256. // Send compressed data with Content-Encoding: gzip
  21257. Client cli(HOST, PORT);
  21258. Headers headers = {{"Content-Encoding", "gzip"}};
  21259. auto res =
  21260. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21261. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21263. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21264. }
  21265. #endif
  21266. // ============================================================================
  21267. // OpenSSL-Specific Tests
  21268. // ============================================================================
  21269. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21270. X509 *readCertificate(const std::string &strFileName) {
  21271. std::ifstream inStream(strFileName);
  21272. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21273. std::istreambuf_iterator<char>());
  21274. if (strCertPEM.empty()) return (nullptr);
  21275. BIO *pbCert = BIO_new(BIO_s_mem());
  21276. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21277. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21278. BIO_free(pbCert);
  21279. return (pCert);
  21280. }
  21281. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21282. std::ifstream inStream(strFileName);
  21283. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21284. std::istreambuf_iterator<char>());
  21285. if (strPrivateKeyPEM.empty()) return (nullptr);
  21286. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21287. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21288. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21289. BIO_free(pbPrivKey);
  21290. return (pPrivateKey);
  21291. }
  21292. TEST(BindServerTest, UpdateCerts) {
  21293. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21294. int port = svr.bind_to_any_port("0.0.0.0");
  21295. ASSERT_TRUE(svr.is_valid());
  21296. ASSERT_TRUE(port > 0);
  21297. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21298. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21299. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21300. ASSERT_TRUE(cert != nullptr);
  21301. ASSERT_TRUE(ca_cert != nullptr);
  21302. ASSERT_TRUE(key != nullptr);
  21303. X509_STORE *cert_store = X509_STORE_new();
  21304. X509_STORE_add_cert(cert_store, ca_cert);
  21305. // svr.update_certs(cert, key, cert_store); // deprecated
  21306. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21307. CLIENT_CA_CERT_FILE);
  21308. ASSERT_TRUE(svr.is_valid());
  21309. svr.stop();
  21310. X509_STORE_free(cert_store);
  21311. X509_free(cert);
  21312. X509_free(ca_cert);
  21313. EVP_PKEY_free(key);
  21314. }
  21315. // Test that update_certs() updates client CA list correctly
  21316. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21317. // Start with file-based constructor
  21318. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21319. ASSERT_TRUE(svr.is_valid());
  21320. // Initially no client CA list should be set
  21321. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21322. ASSERT_TRUE(ssl_ctx != nullptr);
  21323. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21324. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21325. EXPECT_EQ(0, count_before);
  21326. // Now update with client CA (PEM string)
  21327. std::string cert_pem, key_pem, ca_pem;
  21328. read_file(SERVER_CERT_FILE, cert_pem);
  21329. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21330. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21331. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21332. ASSERT_TRUE(svr.is_valid());
  21333. // Now client CA list should be set
  21334. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21335. ASSERT_TRUE(ca_list_after != nullptr);
  21336. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21337. }
  21338. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21339. // Test that the file-path SSLServer constructor properly sets the client CA
  21340. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21341. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21342. ASSERT_TRUE(svr.is_valid());
  21343. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21344. ASSERT_TRUE(ssl_ctx != nullptr);
  21345. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21346. ASSERT_TRUE(ca_list != nullptr);
  21347. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21348. }
  21349. #endif
  21350. // ============================================================================
  21351. // MbedTLS-Specific Tests
  21352. // ============================================================================
  21353. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21354. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21355. using namespace httplib::tls;
  21356. // Track if callback was invoked
  21357. bool callback_invoked = false;
  21358. // The callback receives void* ctx which is actually MbedTlsContext*
  21359. // We can access the mbedtls_ssl_config via the context
  21360. auto setup_callback = [&callback_invoked](void *ctx) {
  21361. callback_invoked = true;
  21362. // Cast to MbedTlsContext* to access the ssl config
  21363. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21364. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21365. // Use static variables to hold certificate data (simplified for test)
  21366. static mbedtls_x509_crt own_cert;
  21367. static mbedtls_pk_context own_key;
  21368. static mbedtls_x509_crt ca_chain;
  21369. static bool initialized = false;
  21370. if (!initialized) {
  21371. mbedtls_x509_crt_init(&own_cert);
  21372. mbedtls_pk_init(&own_key);
  21373. mbedtls_x509_crt_init(&ca_chain);
  21374. // Load server certificate
  21375. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21376. return false;
  21377. }
  21378. // Load server private key.
  21379. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21380. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21381. #if MBEDTLS_VERSION_MAJOR == 3
  21382. ,
  21383. mbedtls_ctr_drbg_random, nullptr
  21384. #endif
  21385. ) != 0) {
  21386. return false;
  21387. }
  21388. // Load CA chain for client verification
  21389. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21390. return false;
  21391. }
  21392. initialized = true;
  21393. }
  21394. // Configure the SSL config
  21395. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21396. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21397. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21398. // Set minimum TLS version using mbedTLS native API
  21399. #if MBEDTLS_VERSION_MAJOR >= 3
  21400. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21401. #else
  21402. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21403. MBEDTLS_SSL_MINOR_VERSION_3);
  21404. #endif
  21405. return true;
  21406. };
  21407. SSLServer svr(setup_callback);
  21408. ASSERT_TRUE(svr.is_valid());
  21409. ASSERT_TRUE(callback_invoked);
  21410. svr.Get("/test", [&](const Request &req, Response &res) {
  21411. res.set_content("test", "text/plain");
  21412. auto cert = req.peer_cert();
  21413. ASSERT_TRUE(static_cast<bool>(cert));
  21414. auto common_name = cert.subject_cn();
  21415. EXPECT_EQ("Common Name", common_name);
  21416. });
  21417. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21418. auto se = detail::scope_exit([&] {
  21419. svr.stop();
  21420. t.join();
  21421. ASSERT_FALSE(svr.is_running());
  21422. });
  21423. svr.wait_until_ready();
  21424. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21425. cli.enable_server_certificate_verification(false);
  21426. cli.set_connection_timeout(30);
  21427. auto res = cli.Get("/test");
  21428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21429. ASSERT_EQ(StatusCode::OK_200, res->status);
  21430. }
  21431. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21432. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21433. // keep-alive SSL session, which reads through that config in
  21434. // mbedtls_ssl_close_notify.
  21435. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21436. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21437. ASSERT_TRUE(svr.is_valid());
  21438. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21439. res.set_content("test", "text/plain");
  21440. });
  21441. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21442. auto se = detail::scope_exit([&] {
  21443. svr.stop();
  21444. t.join();
  21445. ASSERT_FALSE(svr.is_running());
  21446. });
  21447. svr.wait_until_ready();
  21448. {
  21449. SSLClient cli(HOST, PORT);
  21450. cli.enable_server_certificate_verification(false);
  21451. cli.set_keep_alive(true);
  21452. auto res = cli.Get("/test");
  21453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21454. ASSERT_EQ(StatusCode::OK_200, res->status);
  21455. // cli is destructed here with the keep-alive SSL session still open.
  21456. }
  21457. }
  21458. #endif
  21459. // WebSocket Tests
  21460. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21461. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21462. // defining the meaning of these bits has been negotiated.
  21463. auto make_frame = [](uint8_t first_byte) {
  21464. std::string frame;
  21465. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21466. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21467. frame += "Hello";
  21468. return frame;
  21469. };
  21470. // RSV1 set (0x40)
  21471. {
  21472. detail::BufferStream strm;
  21473. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21474. ws::Opcode opcode;
  21475. std::string payload;
  21476. bool fin;
  21477. EXPECT_EQ(
  21478. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21479. ws::impl::FrameRead::Fail);
  21480. }
  21481. // RSV2 set (0x20)
  21482. {
  21483. detail::BufferStream strm;
  21484. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21485. ws::Opcode opcode;
  21486. std::string payload;
  21487. bool fin;
  21488. EXPECT_EQ(
  21489. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21490. ws::impl::FrameRead::Fail);
  21491. }
  21492. // RSV3 set (0x10)
  21493. {
  21494. detail::BufferStream strm;
  21495. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21496. ws::Opcode opcode;
  21497. std::string payload;
  21498. bool fin;
  21499. EXPECT_EQ(
  21500. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21501. ws::impl::FrameRead::Fail);
  21502. }
  21503. // No RSV bits set - should succeed
  21504. {
  21505. detail::BufferStream strm;
  21506. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21507. ws::Opcode opcode;
  21508. std::string payload;
  21509. bool fin;
  21510. EXPECT_EQ(
  21511. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21512. ws::impl::FrameRead::Ok);
  21513. EXPECT_EQ(ws::Opcode::Text, opcode);
  21514. EXPECT_EQ("Hello", payload);
  21515. EXPECT_TRUE(fin);
  21516. }
  21517. }
  21518. TEST(WebSocketTest, ControlFrameValidation) {
  21519. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21520. // payload length <= 125.
  21521. // Ping with FIN=0 - must be rejected
  21522. {
  21523. detail::BufferStream strm;
  21524. std::string frame;
  21525. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21526. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21527. strm.write(frame.data(), frame.size());
  21528. ws::Opcode opcode;
  21529. std::string payload;
  21530. bool fin;
  21531. EXPECT_EQ(
  21532. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21533. ws::impl::FrameRead::Fail);
  21534. }
  21535. // Close with FIN=0 - must be rejected
  21536. {
  21537. detail::BufferStream strm;
  21538. std::string frame;
  21539. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21540. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21541. strm.write(frame.data(), frame.size());
  21542. ws::Opcode opcode;
  21543. std::string payload;
  21544. bool fin;
  21545. EXPECT_EQ(
  21546. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21547. ws::impl::FrameRead::Fail);
  21548. }
  21549. // Ping with payload_len=126 (extended length) - must be rejected
  21550. {
  21551. detail::BufferStream strm;
  21552. std::string frame;
  21553. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21554. frame += static_cast<char>(126); // payload_len=126 (>125)
  21555. frame += static_cast<char>(0x00); // extended length high byte
  21556. frame += static_cast<char>(126); // extended length low byte
  21557. frame += std::string(126, 'x');
  21558. strm.write(frame.data(), frame.size());
  21559. ws::Opcode opcode;
  21560. std::string payload;
  21561. bool fin;
  21562. EXPECT_EQ(
  21563. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21564. ws::impl::FrameRead::Fail);
  21565. }
  21566. // Ping with FIN=1 and payload_len=125 - should succeed
  21567. {
  21568. detail::BufferStream strm;
  21569. std::string frame;
  21570. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21571. frame += static_cast<char>(125); // payload_len=125
  21572. frame += std::string(125, 'x');
  21573. strm.write(frame.data(), frame.size());
  21574. ws::Opcode opcode;
  21575. std::string payload;
  21576. bool fin;
  21577. EXPECT_EQ(
  21578. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21579. ws::impl::FrameRead::Ok);
  21580. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21581. EXPECT_EQ(125u, payload.size());
  21582. EXPECT_TRUE(fin);
  21583. }
  21584. }
  21585. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21586. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21587. // length MUST be 0.
  21588. // MSB set - must be rejected
  21589. {
  21590. detail::BufferStream strm;
  21591. std::string frame;
  21592. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21593. frame += static_cast<char>(127); // 64-bit extended length
  21594. frame += static_cast<char>(0x80); // MSB set (invalid)
  21595. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21596. strm.write(frame.data(), frame.size());
  21597. ws::Opcode opcode;
  21598. std::string payload;
  21599. bool fin;
  21600. EXPECT_EQ(
  21601. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21602. ws::impl::FrameRead::Fail);
  21603. }
  21604. // MSB clear - should pass length parsing (will be rejected by max_len,
  21605. // but that's a different check; use a small length to verify)
  21606. {
  21607. detail::BufferStream strm;
  21608. std::string frame;
  21609. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21610. frame += static_cast<char>(127); // 64-bit extended length
  21611. frame += std::string(7, '\0'); // high bytes = 0
  21612. frame += static_cast<char>(0x03); // length = 3
  21613. frame += "abc";
  21614. strm.write(frame.data(), frame.size());
  21615. ws::Opcode opcode;
  21616. std::string payload;
  21617. bool fin;
  21618. EXPECT_EQ(
  21619. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21620. ws::impl::FrameRead::Ok);
  21621. EXPECT_EQ(ws::Opcode::Text, opcode);
  21622. EXPECT_EQ("abc", payload);
  21623. }
  21624. }
  21625. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21626. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21627. // Valid UTF-8
  21628. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21629. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21630. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21631. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21632. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21633. // Invalid UTF-8
  21634. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21635. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21636. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21637. EXPECT_FALSE(
  21638. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21639. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21640. }
  21641. TEST(WebSocketTest, ConnectAndDisconnect) {
  21642. Server svr;
  21643. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21644. std::string msg;
  21645. while (ws.read(msg)) {}
  21646. });
  21647. auto port = svr.bind_to_any_port(HOST);
  21648. std::thread t([&]() { svr.listen_after_bind(); });
  21649. svr.wait_until_ready();
  21650. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21651. auto res = client.connect();
  21652. ASSERT_TRUE(res);
  21653. EXPECT_EQ(Error::Success, res.error());
  21654. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21655. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21656. EXPECT_TRUE(client.is_open());
  21657. client.close();
  21658. EXPECT_FALSE(client.is_open());
  21659. svr.stop();
  21660. t.join();
  21661. }
  21662. TEST(WebSocketTest, ValidURL) {
  21663. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21664. EXPECT_TRUE(ws1.is_valid());
  21665. ws::WebSocketClient ws2("ws://example.com/path");
  21666. EXPECT_TRUE(ws2.is_valid());
  21667. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21668. EXPECT_TRUE(ws3.is_valid());
  21669. #ifdef CPPHTTPLIB_SSL_ENABLED
  21670. ws::WebSocketClient wss1("wss://example.com/path");
  21671. EXPECT_TRUE(wss1.is_valid());
  21672. ws::WebSocketClient wss2("wss://example.com:443/path");
  21673. EXPECT_TRUE(wss2.is_valid());
  21674. #endif
  21675. }
  21676. TEST(WebSocketTest, InvalidURL) {
  21677. // No scheme
  21678. ws::WebSocketClient ws1("localhost:8080/path");
  21679. EXPECT_FALSE(ws1.is_valid());
  21680. // No path
  21681. ws::WebSocketClient ws2("ws://localhost:8080");
  21682. EXPECT_FALSE(ws2.is_valid());
  21683. // Empty string
  21684. ws::WebSocketClient ws3("");
  21685. EXPECT_FALSE(ws3.is_valid());
  21686. // Missing host
  21687. ws::WebSocketClient ws4("ws://:8080/path");
  21688. EXPECT_FALSE(ws4.is_valid());
  21689. // Port number overflow — should not crash
  21690. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21691. EXPECT_FALSE(ws5.is_valid());
  21692. // Port out of range
  21693. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21694. EXPECT_FALSE(ws6.is_valid());
  21695. }
  21696. TEST(WebSocketTest, UnsupportedScheme) {
  21697. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21698. ws::WebSocketClient ws1("http://localhost:8080/path");
  21699. EXPECT_FALSE(ws1.is_valid());
  21700. ws::WebSocketClient ws2("https://localhost:8080/path");
  21701. EXPECT_FALSE(ws2.is_valid());
  21702. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21703. EXPECT_FALSE(ws3.is_valid());
  21704. #else
  21705. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21706. std::invalid_argument);
  21707. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21708. std::invalid_argument);
  21709. #endif
  21710. }
  21711. TEST(WebSocketTest, ConnectWhenInvalid) {
  21712. ws::WebSocketClient ws("not a valid url");
  21713. EXPECT_FALSE(ws.is_valid());
  21714. auto res = ws.connect();
  21715. EXPECT_FALSE(res);
  21716. EXPECT_EQ(Error::Connection, res.error());
  21717. EXPECT_EQ(-1, res.status());
  21718. }
  21719. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21720. // Grab a port that is free, then close it again so nothing listens there
  21721. Server svr;
  21722. auto port = svr.bind_to_any_port(HOST);
  21723. svr.stop();
  21724. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21725. auto res = client.connect();
  21726. ASSERT_FALSE(res);
  21727. EXPECT_EQ(Error::Connection, res.error());
  21728. EXPECT_EQ(-1, res.status());
  21729. }
  21730. TEST(WebSocketTest, DefaultPort) {
  21731. ws::WebSocketClient ws1("ws://example.com/path");
  21732. EXPECT_TRUE(ws1.is_valid());
  21733. // ws:// defaults to port 80 (verified by successful parse)
  21734. #ifdef CPPHTTPLIB_SSL_ENABLED
  21735. ws::WebSocketClient ws2("wss://example.com/path");
  21736. EXPECT_TRUE(ws2.is_valid());
  21737. // wss:// defaults to port 443 (verified by successful parse)
  21738. #endif
  21739. }
  21740. TEST(WebSocketTest, IPv6LiteralAddress) {
  21741. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21742. EXPECT_TRUE(ws1.is_valid());
  21743. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21744. EXPECT_TRUE(ws2.is_valid());
  21745. }
  21746. TEST(WebSocketTest, ComplexPath) {
  21747. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21748. EXPECT_TRUE(ws1.is_valid());
  21749. ws::WebSocketClient ws2("ws://localhost:8080/");
  21750. EXPECT_TRUE(ws2.is_valid());
  21751. }
  21752. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21753. Server svr;
  21754. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21755. std::string msg;
  21756. while (ws.read(msg)) {}
  21757. });
  21758. auto port = svr.bind_to_any_port(HOST);
  21759. std::thread t([&]() { svr.listen_after_bind(); });
  21760. svr.wait_until_ready();
  21761. auto another_host = "example.com";
  21762. auto wrong_ip = "192.0.2.1";
  21763. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21764. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21765. ASSERT_TRUE(client.connect());
  21766. EXPECT_TRUE(client.is_open());
  21767. client.close();
  21768. svr.stop();
  21769. t.join();
  21770. }
  21771. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21772. Server svr;
  21773. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21774. std::string msg;
  21775. while (ws.read(msg)) {}
  21776. });
  21777. auto port = svr.bind_to_any_port(HOST);
  21778. std::thread t([&]() { svr.listen_after_bind(); });
  21779. svr.wait_until_ready();
  21780. auto wrong_ip = "192.0.2.1";
  21781. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21782. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21783. client.set_connection_timeout(1);
  21784. client.set_read_timeout(1);
  21785. client.set_write_timeout(1);
  21786. EXPECT_FALSE(client.connect());
  21787. EXPECT_FALSE(client.is_open());
  21788. svr.stop();
  21789. t.join();
  21790. }
  21791. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21792. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21793. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21794. // (RFC 6761) is only a map key and the Host header value.
  21795. auto host = "target.invalid";
  21796. Server svr;
  21797. std::string received_host;
  21798. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21799. received_host = req.get_header_value("Host");
  21800. std::string msg;
  21801. while (ws.read(msg)) {}
  21802. });
  21803. auto port = svr.bind_to_any_port(HOST);
  21804. std::thread t([&]() { svr.listen_after_bind(); });
  21805. // ASSERT_* below returns from the test body, which would leave t joinable
  21806. // and make ~thread call std::terminate.
  21807. auto se = detail::scope_exit([&] {
  21808. svr.stop();
  21809. if (t.joinable()) { t.join(); }
  21810. });
  21811. svr.wait_until_ready();
  21812. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21813. std::to_string(port) + "/ws");
  21814. client.set_hostname_addr_map({{host, HOST}});
  21815. ASSERT_TRUE(client.connect());
  21816. EXPECT_TRUE(client.is_open());
  21817. client.close();
  21818. svr.stop();
  21819. t.join();
  21820. // The mapping only redirects the connection; the identity stays host_.
  21821. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21822. }
  21823. class WebSocketIntegrationTest : public ::testing::Test {
  21824. protected:
  21825. void SetUp() override {
  21826. server_ = httplib::detail::make_unique<Server>();
  21827. setup_server();
  21828. start_server();
  21829. }
  21830. void TearDown() override {
  21831. server_->stop();
  21832. if (server_thread_.joinable()) { server_thread_.join(); }
  21833. }
  21834. void setup_server() {
  21835. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21836. std::string msg;
  21837. ws::ReadResult ret;
  21838. while ((ret = ws.read(msg))) {
  21839. if (ret == ws::Binary) {
  21840. ws.send(msg.data(), msg.size());
  21841. } else {
  21842. ws.send(msg);
  21843. }
  21844. }
  21845. });
  21846. server_->WebSocket("/ws-echo-string",
  21847. [](const Request &, ws::WebSocket &ws) {
  21848. std::string msg;
  21849. while (ws.read(msg)) {
  21850. ws.send("echo: " + msg);
  21851. }
  21852. });
  21853. server_->WebSocket(
  21854. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21855. // Echo back request metadata
  21856. ws.send("path:" + req.path);
  21857. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21858. std::string msg;
  21859. while (ws.read(msg)) {}
  21860. });
  21861. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21862. std::string msg;
  21863. ws.read(msg); // wait for a message
  21864. ws.close();
  21865. });
  21866. server_->WebSocket("/ws-close-status",
  21867. [](const Request &, ws::WebSocket &ws) {
  21868. std::string msg;
  21869. ws.read(msg); // wait for a message
  21870. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21871. });
  21872. server_->WebSocket(
  21873. "/ws-subprotocol",
  21874. [](const Request &, ws::WebSocket &ws) {
  21875. std::string msg;
  21876. while (ws.read(msg)) {
  21877. ws.send(msg);
  21878. }
  21879. },
  21880. [](const std::vector<std::string> &protocols) -> std::string {
  21881. for (const auto &p : protocols) {
  21882. if (p == "graphql-ws") { return p; }
  21883. }
  21884. return "";
  21885. });
  21886. server_->WebSocket(
  21887. "/ws-subprotocol-unoffered",
  21888. [](const Request &, ws::WebSocket &ws) {
  21889. std::string msg;
  21890. while (ws.read(msg)) {
  21891. ws.send(msg);
  21892. }
  21893. },
  21894. [](const std::vector<std::string> &) -> std::string {
  21895. return "admin";
  21896. });
  21897. }
  21898. void start_server() {
  21899. port_ = server_->bind_to_any_port(HOST);
  21900. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21901. server_->wait_until_ready();
  21902. }
  21903. std::unique_ptr<Server> server_;
  21904. std::thread server_thread_;
  21905. int port_ = 0;
  21906. };
  21907. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21908. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21909. "/ws-echo");
  21910. ASSERT_TRUE(client.connect());
  21911. ASSERT_TRUE(client.is_open());
  21912. ASSERT_TRUE(client.send("Hello WebSocket"));
  21913. std::string msg;
  21914. EXPECT_EQ(ws::Text, client.read(msg));
  21915. EXPECT_EQ("Hello WebSocket", msg);
  21916. client.close();
  21917. }
  21918. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21919. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21920. "/ws-echo");
  21921. ASSERT_TRUE(client.connect());
  21922. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21923. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21924. std::string msg;
  21925. EXPECT_EQ(ws::Binary, client.read(msg));
  21926. EXPECT_EQ(binary_data, msg);
  21927. client.close();
  21928. }
  21929. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21930. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21931. "/ws-echo");
  21932. ASSERT_TRUE(client.connect());
  21933. for (int i = 0; i < 10; i++) {
  21934. auto text = "message " + std::to_string(i);
  21935. ASSERT_TRUE(client.send(text));
  21936. std::string msg;
  21937. ASSERT_TRUE(client.read(msg));
  21938. EXPECT_EQ(text, msg);
  21939. }
  21940. client.close();
  21941. }
  21942. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21943. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21944. "/ws-close");
  21945. ASSERT_TRUE(client.connect());
  21946. // Send a message to trigger the server to close
  21947. ASSERT_TRUE(client.send("trigger close"));
  21948. // The server will close, so read should return false
  21949. std::string msg;
  21950. EXPECT_FALSE(client.read(msg));
  21951. EXPECT_FALSE(client.is_open());
  21952. }
  21953. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21954. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21955. "/ws-echo");
  21956. ASSERT_TRUE(client.connect());
  21957. // 128KB message
  21958. std::string large_data(128 * 1024, 'X');
  21959. ASSERT_TRUE(client.send(large_data));
  21960. std::string msg;
  21961. ASSERT_TRUE(client.read(msg));
  21962. EXPECT_EQ(large_data, msg);
  21963. client.close();
  21964. }
  21965. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21966. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21967. "/ws-echo");
  21968. ASSERT_TRUE(client.connect());
  21969. const int num_threads = 4;
  21970. std::vector<std::thread> threads;
  21971. std::atomic<int> send_count{0};
  21972. for (int t = 0; t < num_threads; t++) {
  21973. threads.emplace_back([&client, &send_count, t]() {
  21974. for (int i = 0; i < 5; i++) {
  21975. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21976. if (client.send(text)) { send_count++; }
  21977. }
  21978. });
  21979. }
  21980. for (auto &th : threads) {
  21981. th.join();
  21982. }
  21983. int received = 0;
  21984. std::string msg;
  21985. while (received < send_count.load()) {
  21986. if (!client.read(msg)) { break; }
  21987. received++;
  21988. }
  21989. EXPECT_EQ(send_count.load(), received);
  21990. client.close();
  21991. }
  21992. TEST_F(WebSocketIntegrationTest, ReadString) {
  21993. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21994. "/ws-echo-string");
  21995. ASSERT_TRUE(client.connect());
  21996. ASSERT_TRUE(client.send("hello"));
  21997. std::string msg;
  21998. ASSERT_TRUE(client.read(msg));
  21999. EXPECT_EQ("echo: hello", msg);
  22000. ASSERT_TRUE(client.send("world"));
  22001. ASSERT_TRUE(client.read(msg));
  22002. EXPECT_EQ("echo: world", msg);
  22003. client.close();
  22004. }
  22005. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22006. Headers headers = {{"X-Test-Header", "test-value"}};
  22007. ws::WebSocketClient client(
  22008. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22009. ASSERT_TRUE(client.connect());
  22010. std::string msg;
  22011. ASSERT_TRUE(client.read(msg));
  22012. EXPECT_EQ("path:/ws-request-info", msg);
  22013. ASSERT_TRUE(client.read(msg));
  22014. EXPECT_EQ("header:test-value", msg);
  22015. client.close();
  22016. }
  22017. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22018. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22019. "/ws-echo");
  22020. client.set_read_timeout(1, 0); // 1 second
  22021. ASSERT_TRUE(client.connect());
  22022. // Don't send anything — server echo handler waits for a message, so read()
  22023. // should time out. The connection survives it: nothing was consumed.
  22024. std::string msg;
  22025. EXPECT_EQ(client.read(msg), ws::Timeout);
  22026. EXPECT_TRUE(client.is_open());
  22027. // And it is still usable afterwards.
  22028. EXPECT_TRUE(client.send("after timeout"));
  22029. EXPECT_EQ(client.read(msg), ws::Text);
  22030. EXPECT_EQ(msg, "after timeout");
  22031. }
  22032. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22033. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22034. "/ws-echo");
  22035. client.set_read_timeout(1, 0);
  22036. ASSERT_TRUE(client.connect());
  22037. ASSERT_TRUE(client.send("first"));
  22038. std::string msg;
  22039. ASSERT_EQ(client.read(msg), ws::Text);
  22040. ASSERT_EQ(msg, "first");
  22041. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22042. // not be used with a read timeout: it would reprocess the previous message.
  22043. EXPECT_EQ(client.read(msg), ws::Timeout);
  22044. EXPECT_EQ(msg, "first");
  22045. }
  22046. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22047. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22048. "/ws-echo");
  22049. ASSERT_TRUE(client.connect());
  22050. // Setting it once the connection is open reaches the live stream, not just
  22051. // the seed for the next connect().
  22052. client.set_read_timeout(1, 0);
  22053. std::string msg;
  22054. EXPECT_EQ(client.read(msg), ws::Timeout);
  22055. EXPECT_TRUE(client.is_open());
  22056. }
  22057. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22058. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22059. "/ws-echo");
  22060. client.set_read_timeout(5, 0);
  22061. ASSERT_TRUE(client.connect());
  22062. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22063. // The server should reject it and close the connection.
  22064. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22065. client.send(oversized);
  22066. // The server's read() should have failed due to payload limit,
  22067. // so our read() should return false (connection closed).
  22068. std::string msg;
  22069. EXPECT_FALSE(client.read(msg));
  22070. }
  22071. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22072. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22073. "/ws-echo");
  22074. client.set_read_timeout(10, 0);
  22075. ASSERT_TRUE(client.connect());
  22076. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22077. // This should succeed.
  22078. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22079. ASSERT_TRUE(client.send(at_limit));
  22080. std::string msg;
  22081. ASSERT_TRUE(client.read(msg));
  22082. EXPECT_EQ(at_limit.size(), msg.size());
  22083. client.close();
  22084. }
  22085. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22086. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22087. "/nonexistent");
  22088. auto res = client.connect();
  22089. EXPECT_FALSE(res);
  22090. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22091. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22092. EXPECT_FALSE(client.is_open());
  22093. }
  22094. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22095. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22096. "/ws-echo");
  22097. ASSERT_TRUE(client.connect());
  22098. ASSERT_TRUE(client.send(""));
  22099. std::string msg;
  22100. EXPECT_EQ(ws::Text, client.read(msg));
  22101. EXPECT_EQ("", msg);
  22102. client.close();
  22103. }
  22104. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22105. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22106. "/ws-echo");
  22107. // First connection
  22108. ASSERT_TRUE(client.connect());
  22109. ASSERT_TRUE(client.send("first"));
  22110. std::string msg;
  22111. ASSERT_TRUE(client.read(msg));
  22112. EXPECT_EQ("first", msg);
  22113. client.close();
  22114. EXPECT_FALSE(client.is_open());
  22115. // Reconnect using the same client object
  22116. ASSERT_TRUE(client.connect());
  22117. ASSERT_TRUE(client.is_open());
  22118. ASSERT_TRUE(client.send("second"));
  22119. ASSERT_TRUE(client.read(msg));
  22120. EXPECT_EQ("second", msg);
  22121. client.close();
  22122. }
  22123. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22124. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22125. "/ws-close-status");
  22126. ASSERT_TRUE(client.connect());
  22127. // Trigger the server to close with GoingAway status
  22128. ASSERT_TRUE(client.send("trigger"));
  22129. // read() should return false after receiving the close frame
  22130. std::string msg;
  22131. EXPECT_FALSE(client.read(msg));
  22132. EXPECT_FALSE(client.is_open());
  22133. }
  22134. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22135. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22136. "/ws-echo");
  22137. ASSERT_TRUE(client.connect());
  22138. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22139. EXPECT_FALSE(client.is_open());
  22140. }
  22141. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22142. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22143. ws::WebSocketClient client(
  22144. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22145. ASSERT_TRUE(client.connect());
  22146. // Server should have selected graphql-ws
  22147. EXPECT_EQ("graphql-ws", client.subprotocol());
  22148. client.close();
  22149. }
  22150. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22151. Headers headers;
  22152. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22153. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22154. ws::WebSocketClient client(
  22155. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22156. ASSERT_TRUE(client.connect());
  22157. // The offer on the second field line counts too, so graphql-ws is selected
  22158. EXPECT_EQ("graphql-ws", client.subprotocol());
  22159. client.close();
  22160. }
  22161. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22162. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22163. ws::WebSocketClient client(
  22164. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22165. ASSERT_TRUE(client.connect());
  22166. // Server should not have selected any subprotocol
  22167. EXPECT_TRUE(client.subprotocol().empty());
  22168. client.close();
  22169. }
  22170. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22171. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22172. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22173. "/ws-subprotocol-unoffered",
  22174. headers);
  22175. ASSERT_TRUE(client.connect());
  22176. EXPECT_TRUE(client.subprotocol().empty());
  22177. client.close();
  22178. }
  22179. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22180. // Connect without requesting any subprotocol
  22181. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22182. "/ws-subprotocol");
  22183. ASSERT_TRUE(client.connect());
  22184. EXPECT_TRUE(client.subprotocol().empty());
  22185. client.close();
  22186. }
  22187. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22188. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22189. "/ws-echo");
  22190. client.set_tcp_nodelay(true);
  22191. client.set_connection_timeout(3, 0);
  22192. bool socket_options_called = false;
  22193. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22194. ASSERT_TRUE(client.connect());
  22195. ASSERT_TRUE(client.is_open());
  22196. EXPECT_TRUE(socket_options_called);
  22197. ASSERT_TRUE(client.send("hello"));
  22198. std::string msg;
  22199. auto result = client.read(msg);
  22200. EXPECT_EQ(result, ws::ReadResult::Text);
  22201. EXPECT_EQ(msg, "hello");
  22202. client.close();
  22203. }
  22204. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22205. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22206. "/ws-echo");
  22207. client.set_connection_timeout(std::chrono::seconds(3));
  22208. client.set_write_timeout(std::chrono::seconds(3));
  22209. // A sub-second remainder exercises the seconds/microseconds split.
  22210. client.set_read_timeout(std::chrono::milliseconds(1500));
  22211. ASSERT_TRUE(client.connect());
  22212. auto start = std::chrono::steady_clock::now();
  22213. std::string msg;
  22214. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22215. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22216. std::chrono::steady_clock::now() - start)
  22217. .count();
  22218. // Above 1s so that dropping the microseconds half of the split fails here.
  22219. // Ignoring the setter altogether would not reach this line at all: a client
  22220. // waits forever by default.
  22221. EXPECT_GE(elapsed, 1400);
  22222. EXPECT_LT(elapsed, 30000);
  22223. }
  22224. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22225. Server svr;
  22226. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22227. if (!req.has_header("Authorization")) {
  22228. res.status = StatusCode::Unauthorized_401;
  22229. res.set_content("Unauthorized", "text/plain");
  22230. return Server::HandlerResponse::Handled;
  22231. }
  22232. return Server::HandlerResponse::Unhandled;
  22233. });
  22234. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22235. std::string msg;
  22236. while (ws.read(msg)) {
  22237. ws.send(msg);
  22238. }
  22239. });
  22240. auto port = svr.bind_to_any_port("localhost");
  22241. std::thread t([&]() { svr.listen_after_bind(); });
  22242. svr.wait_until_ready();
  22243. // Without Authorization header - should be rejected before upgrade
  22244. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22245. EXPECT_FALSE(client1.connect());
  22246. // The rejection is framed like any other HTTP response
  22247. {
  22248. Client cli("localhost", port);
  22249. Headers headers = {{"Upgrade", "websocket"},
  22250. {"Connection", "Upgrade"},
  22251. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22252. {"Sec-WebSocket-Version", "13"}};
  22253. auto res = cli.Get("/ws", headers);
  22254. ASSERT_TRUE(res);
  22255. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22256. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22257. EXPECT_EQ("Unauthorized", res->body);
  22258. }
  22259. // With Authorization header - should succeed
  22260. Headers headers = {{"Authorization", "Bearer token123"}};
  22261. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22262. headers);
  22263. ASSERT_TRUE(client2.connect());
  22264. ASSERT_TRUE(client2.send("hello"));
  22265. std::string msg;
  22266. ASSERT_TRUE(client2.read(msg));
  22267. EXPECT_EQ("hello", msg);
  22268. client2.close();
  22269. svr.stop();
  22270. t.join();
  22271. }
  22272. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22273. Server svr;
  22274. std::atomic<int> pre_request_calls{0};
  22275. std::atomic<bool> route_matched{false};
  22276. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22277. pre_request_calls++;
  22278. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22279. if (req.get_header_value("Authorization") != "Bearer token123") {
  22280. res.status = StatusCode::Unauthorized_401;
  22281. res.set_content("Unauthorized", "text/plain");
  22282. return Server::HandlerResponse::Handled;
  22283. }
  22284. return Server::HandlerResponse::Unhandled;
  22285. });
  22286. std::atomic<bool> handler_called{false};
  22287. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22288. handler_called = true;
  22289. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22290. });
  22291. auto port = svr.bind_to_any_port("localhost");
  22292. std::thread t([&]() { svr.listen_after_bind(); });
  22293. svr.wait_until_ready();
  22294. // Without Authorization header - should be rejected before upgrade
  22295. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22296. "/ws/1");
  22297. EXPECT_FALSE(client1.connect());
  22298. EXPECT_FALSE(handler_called);
  22299. EXPECT_EQ(1, pre_request_calls);
  22300. EXPECT_TRUE(route_matched);
  22301. // The rejection is an ordinary HTTP response, not a protocol switch
  22302. {
  22303. Client cli("localhost", port);
  22304. Headers headers = {{"Upgrade", "websocket"},
  22305. {"Connection", "Upgrade"},
  22306. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22307. {"Sec-WebSocket-Version", "13"}};
  22308. auto res = cli.Get("/ws/1", headers);
  22309. ASSERT_TRUE(res);
  22310. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22311. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22312. EXPECT_EQ("Unauthorized", res->body);
  22313. }
  22314. EXPECT_FALSE(handler_called);
  22315. // With Authorization header - should succeed
  22316. Headers headers = {{"Authorization", "Bearer token123"}};
  22317. ws::WebSocketClient client2(
  22318. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22319. ASSERT_TRUE(client2.connect());
  22320. std::string msg;
  22321. ASSERT_TRUE(client2.read(msg));
  22322. EXPECT_EQ("/ws/:id 2", msg);
  22323. EXPECT_TRUE(handler_called);
  22324. client2.close();
  22325. svr.stop();
  22326. t.join();
  22327. }
  22328. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22329. Server svr;
  22330. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22331. // A read timeout is how a handler gets control back. Without it, a handler
  22332. // parked in read() can never write on the connection it is reading.
  22333. ws.set_read_timeout(std::chrono::milliseconds(100));
  22334. std::string msg;
  22335. while (ws.is_open()) {
  22336. auto r = ws.read(msg);
  22337. if (r == httplib::ws::Timeout) {
  22338. ws.send("tick");
  22339. continue;
  22340. }
  22341. if (r == httplib::ws::Fail) { break; }
  22342. ws.send(msg);
  22343. }
  22344. });
  22345. auto port = svr.bind_to_any_port("localhost");
  22346. std::thread t([&]() { svr.listen_after_bind(); });
  22347. svr.wait_until_ready();
  22348. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22349. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22350. ASSERT_TRUE(client.connect());
  22351. // The client sends nothing, so anything it receives came out of the
  22352. // handler's timeout path.
  22353. std::string msg;
  22354. ASSERT_EQ(client.read(msg), ws::Text);
  22355. EXPECT_EQ("tick", msg);
  22356. client.close();
  22357. svr.stop();
  22358. t.join();
  22359. }
  22360. // Stream::read may return fewer bytes than asked for. This is that contract at
  22361. // its worst -- one byte per call -- which is what a frame header straddling a
  22362. // read buffer's boundary looks like to the frame parser.
  22363. class WsByteAtATimeStream : public Stream {
  22364. public:
  22365. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22366. bool is_readable() const override { return true; }
  22367. bool wait_readable() const override { return true; }
  22368. bool wait_writable() const override { return true; }
  22369. ssize_t read(char *ptr, size_t size) override {
  22370. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22371. *ptr = data_[pos_++];
  22372. return 1;
  22373. }
  22374. ssize_t write(const char *, size_t size) override {
  22375. return static_cast<ssize_t>(size);
  22376. }
  22377. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22378. ip = "127.0.0.1";
  22379. port = 0;
  22380. }
  22381. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22382. ip = "127.0.0.1";
  22383. port = 0;
  22384. }
  22385. socket_t socket() const override { return INVALID_SOCKET; }
  22386. time_t duration() const override { return 0; }
  22387. private:
  22388. std::string data_;
  22389. size_t pos_ = 0;
  22390. };
  22391. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22392. // The payload uses the 16-bit extended length, so the header, the length
  22393. // and the mask key are all multi-byte fields here. Each used to be read
  22394. // with a single read() call, which fails as soon as one is split. The
  22395. // payload is also a little over one read chunk, so it is read in two.
  22396. std::string body;
  22397. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22398. body += static_cast<char>(i % 251);
  22399. }
  22400. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22401. std::string frame;
  22402. frame += static_cast<char>(0x81); // FIN + Text
  22403. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22404. frame += static_cast<char>(body.size() >> 8);
  22405. frame += static_cast<char>(body.size() & 0xff);
  22406. for (size_t i = 0; i < 4; i++) {
  22407. frame += static_cast<char>(mask[i]);
  22408. }
  22409. for (size_t i = 0; i < body.size(); i++) {
  22410. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22411. }
  22412. WsByteAtATimeStream strm(frame);
  22413. ws::Opcode opcode;
  22414. std::string payload;
  22415. bool fin = false;
  22416. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22417. /*expect_masked=*/true, body.size()),
  22418. ws::impl::FrameRead::Ok);
  22419. EXPECT_TRUE(fin);
  22420. EXPECT_EQ(opcode, ws::Opcode::Text);
  22421. EXPECT_EQ(payload, body);
  22422. }
  22423. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22424. std::string body(2000, 'x');
  22425. std::string frame;
  22426. frame += static_cast<char>(0x82); // FIN + Binary
  22427. frame += static_cast<char>(126); // 16-bit length follows
  22428. frame += static_cast<char>(body.size() >> 8);
  22429. frame += static_cast<char>(body.size() & 0xff);
  22430. frame += body;
  22431. detail::BufferStream strm;
  22432. strm.write(frame.data(), frame.size());
  22433. ws::Opcode opcode;
  22434. std::string payload;
  22435. bool fin;
  22436. EXPECT_EQ(
  22437. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22438. ws::impl::FrameRead::Ok);
  22439. EXPECT_EQ(body, payload);
  22440. }
  22441. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22442. // The header announces the largest payload allowed, and only 3 bytes of it
  22443. // ever arrive.
  22444. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22445. std::string frame;
  22446. frame += static_cast<char>(0x82); // FIN + Binary
  22447. frame += static_cast<char>(127); // 64-bit length follows
  22448. for (int shift = 56; shift >= 0; shift -= 8) {
  22449. frame += static_cast<char>((len >> shift) & 0xff);
  22450. }
  22451. frame += "abc";
  22452. detail::BufferStream strm;
  22453. strm.write(frame.data(), frame.size());
  22454. ws::Opcode opcode;
  22455. std::string payload;
  22456. bool fin;
  22457. EXPECT_EQ(
  22458. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22459. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22460. ws::impl::FrameRead::Fail);
  22461. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22462. }
  22463. TEST(WebSocketTest, QueryStringInHandshake) {
  22464. Server svr;
  22465. std::mutex mtx;
  22466. std::string received_target;
  22467. std::string received_token;
  22468. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22469. {
  22470. std::lock_guard<std::mutex> lock(mtx);
  22471. received_target = req.target;
  22472. if (req.has_param("token")) {
  22473. received_token = req.get_param_value("token");
  22474. }
  22475. }
  22476. std::string msg;
  22477. while (ws.read(msg)) {
  22478. ws.send(msg);
  22479. }
  22480. });
  22481. auto port = svr.bind_to_any_port("localhost");
  22482. std::thread t([&]() { svr.listen_after_bind(); });
  22483. svr.wait_until_ready();
  22484. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22485. "/ws?token=ABC&session=123");
  22486. ASSERT_TRUE(client.connect());
  22487. // Round-trip ensures the handler has run and captured the request.
  22488. ASSERT_TRUE(client.send("hello"));
  22489. std::string msg;
  22490. ASSERT_TRUE(client.read(msg));
  22491. EXPECT_EQ("hello", msg);
  22492. client.close();
  22493. {
  22494. std::lock_guard<std::mutex> lock(mtx);
  22495. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22496. EXPECT_EQ("ABC", received_token);
  22497. }
  22498. svr.stop();
  22499. t.join();
  22500. }
  22501. // Run a handshake against a throwaway server and hand the request the server
  22502. // received back to the caller, so tests can assert on the headers the client
  22503. // actually put on the wire.
  22504. static void capture_websocket_handshake_request(
  22505. const Headers &client_headers,
  22506. std::function<void(const Request &, int port)> verify) {
  22507. Server svr;
  22508. std::mutex mtx;
  22509. Request received;
  22510. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22511. {
  22512. std::lock_guard<std::mutex> lock(mtx);
  22513. received = req;
  22514. }
  22515. std::string msg;
  22516. while (ws.read(msg)) {
  22517. ws.send(msg);
  22518. }
  22519. });
  22520. auto port = svr.bind_to_any_port("localhost");
  22521. std::thread t([&]() { svr.listen_after_bind(); });
  22522. auto se = detail::scope_exit([&] {
  22523. svr.stop();
  22524. t.join();
  22525. });
  22526. svr.wait_until_ready();
  22527. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22528. client_headers);
  22529. ASSERT_TRUE(client.connect());
  22530. ASSERT_TRUE(client.send("hello"));
  22531. std::string msg;
  22532. ASSERT_TRUE(client.read(msg));
  22533. client.close();
  22534. {
  22535. std::lock_guard<std::mutex> lock(mtx);
  22536. verify(received, port);
  22537. }
  22538. }
  22539. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22540. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22541. // Non-default port must be present in the Host header. Default ports
  22542. // (80/443) are omitted; that logic is covered by
  22543. // MakeHostAndPortStringTest.
  22544. EXPECT_EQ("localhost:" + std::to_string(port),
  22545. req.get_header_value("Host"));
  22546. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22547. req.get_header_value("User-Agent"));
  22548. EXPECT_FALSE(req.has_header("Accept"));
  22549. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22550. EXPECT_FALSE(req.has_header("Content-Length"));
  22551. });
  22552. }
  22553. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22554. capture_websocket_handshake_request(
  22555. {{"Host", "example.com"},
  22556. {"User-Agent", "custom-agent"},
  22557. {"X-Custom", "value"}},
  22558. [](const Request &req, int) {
  22559. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22560. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22561. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22562. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22563. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22564. });
  22565. }
  22566. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22567. capture_websocket_handshake_request(
  22568. {{"Upgrade", "bogus"},
  22569. {"Connection", "close"},
  22570. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22571. {"Sec-WebSocket-Version", "8"}},
  22572. [](const Request &req, int) {
  22573. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22574. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22575. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22576. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22577. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22578. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22579. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22580. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22581. req.get_header_value("Sec-WebSocket-Key"));
  22582. });
  22583. }
  22584. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22585. // A header the client refuses to send must abort the handshake before any
  22586. // part of it reaches the wire; a lone request line would otherwise sit in
  22587. // the peer's buffer as a truncated request.
  22588. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22589. ASSERT_NE(INVALID_SOCKET, srv);
  22590. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22591. sockaddr_in addr{};
  22592. addr.sin_family = AF_INET;
  22593. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22594. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22595. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22596. ASSERT_EQ(0, ::listen(srv, 1));
  22597. sockaddr_in bound{};
  22598. socklen_t bound_len = sizeof(bound);
  22599. ASSERT_EQ(
  22600. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22601. auto port = ntohs(bound.sin_port);
  22602. ssize_t received = -1;
  22603. std::thread t([&] {
  22604. // Bound every blocking call so a regression fails the test with a bad
  22605. // value instead of hanging the suite.
  22606. fd_set rfds;
  22607. FD_ZERO(&rfds);
  22608. FD_SET(srv, &rfds);
  22609. timeval tv{5, 0};
  22610. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22611. 0) {
  22612. return;
  22613. }
  22614. sockaddr_in cli_addr{};
  22615. socklen_t cli_len = sizeof(cli_addr);
  22616. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22617. if (cli == INVALID_SOCKET) { return; }
  22618. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22619. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22620. char buf[4096];
  22621. received = ::recv(cli, buf, sizeof(buf), 0);
  22622. });
  22623. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22624. // connect() has already shut the socket down by the time it returns false,
  22625. // so the peer sees EOF without waiting for the client to be destroyed.
  22626. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22627. {{"X-Bad", "a\r\nInjected: 1"}});
  22628. EXPECT_FALSE(client.connect());
  22629. t.join();
  22630. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22631. EXPECT_EQ(0, received);
  22632. }
  22633. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22634. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22635. // contains "upgrade" as a substring is a different token and must not
  22636. // start a WebSocket handshake.
  22637. auto make_request = [](const std::vector<std::string> &connection_values) {
  22638. Request req;
  22639. req.method = "GET";
  22640. req.headers.emplace("Upgrade", "websocket");
  22641. for (const auto &value : connection_values) {
  22642. req.headers.emplace("Connection", value);
  22643. }
  22644. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22645. req.headers.emplace("Sec-WebSocket-Version", "13");
  22646. return req;
  22647. };
  22648. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22649. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22650. EXPECT_TRUE(
  22651. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22652. EXPECT_TRUE(
  22653. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22654. EXPECT_TRUE(
  22655. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22656. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22657. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22658. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22659. EXPECT_FALSE(
  22660. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22661. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22662. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22663. }
  22664. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22665. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22666. // asks recipients to match each protocol-name case-insensitively, and RFC
  22667. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22668. // client naming websocket alongside another protocol, or on a second field
  22669. // line, is offering websocket; a value that merely contains "websocket" as a
  22670. // substring is a different protocol name and is not.
  22671. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22672. Request req;
  22673. req.method = "GET";
  22674. for (const auto &value : upgrade_values) {
  22675. req.headers.emplace("Upgrade", value);
  22676. }
  22677. req.headers.emplace("Connection", "Upgrade");
  22678. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22679. req.headers.emplace("Sec-WebSocket-Version", "13");
  22680. return req;
  22681. };
  22682. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22683. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22684. EXPECT_TRUE(
  22685. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22686. EXPECT_TRUE(
  22687. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22688. EXPECT_TRUE(
  22689. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22690. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22691. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22692. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22693. EXPECT_FALSE(
  22694. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22695. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22696. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22697. }
  22698. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22699. Server svr;
  22700. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22701. auto port = svr.bind_to_any_port("localhost");
  22702. std::thread t([&]() { svr.listen_after_bind(); });
  22703. auto se = detail::scope_exit([&] {
  22704. svr.stop();
  22705. t.join();
  22706. });
  22707. svr.wait_until_ready();
  22708. Headers headers = {{"Upgrade", "websocket"},
  22709. {"Connection", "notupgrade"},
  22710. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22711. {"Sec-WebSocket-Version", "13"}};
  22712. Client cli("localhost", port);
  22713. auto res = cli.Get("/ws", headers);
  22714. // The route exists only as a WebSocket route, so a request that fails the
  22715. // handshake check falls through to ordinary routing.
  22716. ASSERT_TRUE(res);
  22717. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22718. }
  22719. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22720. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22721. // Connection value is the only thing left for the client to reject.
  22722. Server svr;
  22723. svr.Get("/ws", [](const Request &req, Response &res) {
  22724. res.status = StatusCode::SwitchingProtocol_101;
  22725. res.set_header("Upgrade", "websocket");
  22726. res.set_header("Connection", "notupgrade");
  22727. res.set_header("Sec-WebSocket-Accept",
  22728. detail::websocket_accept_key(
  22729. req.get_header_value("Sec-WebSocket-Key")));
  22730. });
  22731. auto port = svr.bind_to_any_port("localhost");
  22732. std::thread t([&]() { svr.listen_after_bind(); });
  22733. auto se = detail::scope_exit([&] {
  22734. svr.stop();
  22735. t.join();
  22736. });
  22737. svr.wait_until_ready();
  22738. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22739. auto res = client.connect();
  22740. EXPECT_FALSE(res);
  22741. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22742. EXPECT_FALSE(client.is_open());
  22743. }
  22744. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22745. Server svr;
  22746. svr.Get("/ws", [](const Request &req, Response &res) {
  22747. res.status = StatusCode::SwitchingProtocol_101;
  22748. res.set_header("Upgrade", "websocket");
  22749. res.set_header("Connection", "Upgrade");
  22750. res.set_header("Sec-WebSocket-Accept",
  22751. detail::websocket_accept_key(
  22752. req.get_header_value("Sec-WebSocket-Key")));
  22753. res.set_header("Sec-WebSocket-Protocol", "admin");
  22754. });
  22755. auto port = svr.bind_to_any_port("localhost");
  22756. std::thread t([&]() { svr.listen_after_bind(); });
  22757. auto se = detail::scope_exit([&] {
  22758. svr.stop();
  22759. t.join();
  22760. });
  22761. svr.wait_until_ready();
  22762. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22763. // Server selects a subprotocol the client never offered
  22764. {
  22765. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22766. ws::WebSocketClient client(url, headers);
  22767. auto res = client.connect();
  22768. EXPECT_FALSE(res);
  22769. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22770. EXPECT_FALSE(client.is_open());
  22771. EXPECT_TRUE(client.subprotocol().empty());
  22772. }
  22773. // Client offered none but the server named one anyway
  22774. {
  22775. ws::WebSocketClient client(url);
  22776. auto res = client.connect();
  22777. EXPECT_FALSE(res);
  22778. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22779. EXPECT_FALSE(client.is_open());
  22780. EXPECT_TRUE(client.subprotocol().empty());
  22781. }
  22782. }
  22783. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22784. // The socket path doubles as the URL host, so it must not contain '/'.
  22785. const char *shard = getenv("GTEST_SHARD_INDEX");
  22786. const std::string sock_path =
  22787. shard ? std::string("httplib-ws-") + shard + ".sock"
  22788. : std::string("httplib-ws.sock");
  22789. std::remove(sock_path.c_str());
  22790. Server svr;
  22791. std::mutex mtx;
  22792. std::string received_host;
  22793. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22794. {
  22795. std::lock_guard<std::mutex> lock(mtx);
  22796. received_host = req.get_header_value("Host");
  22797. }
  22798. std::string msg;
  22799. while (ws.read(msg)) {
  22800. ws.send(msg);
  22801. }
  22802. });
  22803. svr.set_address_family(AF_UNIX);
  22804. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22805. auto se = detail::scope_exit([&] {
  22806. svr.stop();
  22807. t.join();
  22808. std::remove(sock_path.c_str());
  22809. });
  22810. svr.wait_until_ready();
  22811. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22812. client.set_address_family(AF_UNIX);
  22813. ASSERT_TRUE(client.connect());
  22814. ASSERT_TRUE(client.send("hello"));
  22815. std::string msg;
  22816. ASSERT_TRUE(client.read(msg));
  22817. client.close();
  22818. {
  22819. std::lock_guard<std::mutex> lock(mtx);
  22820. // There is no host:port for a Unix socket, so the same "localhost"
  22821. // placeholder the HTTP client uses is expected.
  22822. EXPECT_EQ("localhost", received_host);
  22823. }
  22824. }
  22825. // Two threads must never parse WebSocket frames from the same stream.
  22826. // close() used to read the peer's Close reply with its own frame read, so it
  22827. // raced a reader thread that was in the middle of a payload: the payload loop
  22828. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22829. // so bytes taken by close() were replaced with bytes from further along the
  22830. // stream. The message kept its length and silently changed content.
  22831. //
  22832. // The raw peer below sends a frame header plus part of the payload, waits for
  22833. // the handler to call close(), and only then sends the rest. Whichever thread
  22834. // would win the race for those bytes, the message must arrive intact, because
  22835. // close() must not touch the stream while read() owns it.
  22836. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22837. #ifndef _WIN32
  22838. signal(SIGPIPE, SIG_IGN);
  22839. #endif
  22840. const size_t payload_len = 120; // fits the 7-bit length field
  22841. const size_t prefix_len = 8;
  22842. const int attempts = 8;
  22843. std::string expected(payload_len, '\0');
  22844. for (size_t i = 0; i < payload_len; i++) {
  22845. expected[i] = static_cast<char>('a' + i % 26);
  22846. }
  22847. std::atomic<bool> peer_stalled{false};
  22848. std::atomic<bool> handler_done{false};
  22849. std::mutex received_mutex;
  22850. std::vector<std::string> received;
  22851. // Bound every wait, so a regression fails the test instead of hanging the
  22852. // suite.
  22853. auto wait_for = [](const std::atomic<bool> &flag) {
  22854. for (int i = 0; i < 500 && !flag; i++) {
  22855. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22856. }
  22857. };
  22858. Server svr;
  22859. svr.set_websocket_ping_interval(0);
  22860. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22861. std::thread reader([&]() {
  22862. std::string msg;
  22863. while (ws.read(msg)) {
  22864. std::lock_guard<std::mutex> guard(received_mutex);
  22865. received.push_back(msg);
  22866. }
  22867. });
  22868. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22869. // inside read_websocket_frame() when close() runs.
  22870. wait_for(peer_stalled);
  22871. ws.close();
  22872. reader.join();
  22873. handler_done = true;
  22874. });
  22875. auto port = svr.bind_to_any_port("127.0.0.1");
  22876. std::thread t([&]() { svr.listen_after_bind(); });
  22877. auto se = detail::scope_exit([&] {
  22878. svr.stop();
  22879. t.join();
  22880. });
  22881. svr.wait_until_ready();
  22882. auto send_bytes = [](socket_t s, const std::string &data) {
  22883. #ifdef _WIN32
  22884. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22885. #else
  22886. auto n = ::send(s, data.data(), data.size(), 0);
  22887. #endif
  22888. return n == static_cast<decltype(n)>(data.size());
  22889. };
  22890. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22891. // Every length used here fits the 7-bit length field.
  22892. auto masked_header = [](uint8_t first_byte, size_t len) {
  22893. std::string h;
  22894. h += static_cast<char>(first_byte);
  22895. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22896. h.append(4, '\0'); // mask key
  22897. return h;
  22898. };
  22899. for (int attempt = 0; attempt < attempts; attempt++) {
  22900. peer_stalled = false;
  22901. handler_done = false;
  22902. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22903. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22904. auto se_sock = detail::scope_exit([&] {
  22905. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22906. });
  22907. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22908. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22909. sockaddr_in addr{};
  22910. addr.sin_family = AF_INET;
  22911. addr.sin_port = htons(static_cast<uint16_t>(port));
  22912. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22913. ASSERT_EQ(
  22914. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22915. << "attempt " << attempt;
  22916. ASSERT_TRUE(send_bytes(sock,
  22917. "GET /ws HTTP/1.1\r\n"
  22918. "Host: 127.0.0.1\r\n"
  22919. "Upgrade: websocket\r\n"
  22920. "Connection: Upgrade\r\n"
  22921. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22922. "Sec-WebSocket-Version: 13\r\n"
  22923. "\r\n"))
  22924. << "attempt " << attempt;
  22925. std::string response;
  22926. while (response.find("\r\n\r\n") == std::string::npos) {
  22927. char buf[512];
  22928. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22929. if (n <= 0) { break; }
  22930. response.append(buf, static_cast<size_t>(n));
  22931. }
  22932. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22933. << "attempt " << attempt;
  22934. // Send the header of a Binary message but only the first prefix_len bytes
  22935. // of its payload, leaving the reader thread stalled inside the payload.
  22936. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22937. expected.substr(0, prefix_len)))
  22938. << "attempt " << attempt;
  22939. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22940. peer_stalled = true;
  22941. // Let close() send its Close frame and park in its own read before the
  22942. // rest of the payload arrives, so both threads are waiting for it.
  22943. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22944. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22945. close_frame += static_cast<char>(0x03); // status 1000
  22946. close_frame += static_cast<char>(0xE8);
  22947. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22948. << "attempt " << attempt;
  22949. // Closing the peer releases the reader thread even on the buggy path,
  22950. // where it waits for bytes another thread already consumed.
  22951. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22952. detail::close_socket(sock);
  22953. sock = INVALID_SOCKET;
  22954. wait_for(handler_done);
  22955. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22956. }
  22957. std::lock_guard<std::mutex> guard(received_mutex);
  22958. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22959. << "a message in flight when close() ran was dropped";
  22960. for (size_t i = 0; i < received.size(); i++) {
  22961. EXPECT_EQ(expected, received[i]) << "message " << i;
  22962. }
  22963. }
  22964. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  22965. // returning the socket, or INVALID_SOCKET.
  22966. static socket_t connect_raw_websocket(int port, const std::string &path) {
  22967. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22968. if (sock == INVALID_SOCKET) { return sock; }
  22969. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22970. sockaddr_in addr{};
  22971. addr.sin_family = AF_INET;
  22972. addr.sin_port = htons(static_cast<uint16_t>(port));
  22973. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22974. std::string req = "GET " + path +
  22975. " HTTP/1.1\r\n"
  22976. "Host: 127.0.0.1\r\n"
  22977. "Upgrade: websocket\r\n"
  22978. "Connection: Upgrade\r\n"
  22979. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22980. "Sec-WebSocket-Version: 13\r\n"
  22981. "\r\n";
  22982. std::string res;
  22983. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  22984. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  22985. static_cast<int>(req.size())) {
  22986. char c;
  22987. while (res.find("\r\n\r\n") == std::string::npos &&
  22988. ::recv(sock, &c, 1, 0) == 1) {
  22989. res += c;
  22990. }
  22991. }
  22992. if (res.find(" 101 ") == std::string::npos) {
  22993. detail::close_socket(sock);
  22994. return INVALID_SOCKET;
  22995. }
  22996. return sock;
  22997. }
  22998. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  22999. // The payload must fit the 7-bit length field.
  23000. static std::string masked_frame(uint8_t first_byte,
  23001. const std::string &payload) {
  23002. std::string f;
  23003. f += static_cast<char>(first_byte);
  23004. f += static_cast<char>(0x80 | payload.size());
  23005. f.append(4, '\0');
  23006. return f + payload;
  23007. }
  23008. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23009. std::atomic<bool> done{false};
  23010. std::string received;
  23011. Server svr;
  23012. svr.set_websocket_ping_interval(0);
  23013. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23014. std::string msg;
  23015. if (ws.read(msg) == ws::Binary) { received = msg; }
  23016. done = true;
  23017. });
  23018. auto port = svr.bind_to_any_port("127.0.0.1");
  23019. std::thread t([&]() { svr.listen_after_bind(); });
  23020. auto se = detail::scope_exit([&] {
  23021. svr.stop();
  23022. t.join();
  23023. });
  23024. svr.wait_until_ready();
  23025. auto sock = connect_raw_websocket(port, "/ws");
  23026. ASSERT_NE(INVALID_SOCKET, sock);
  23027. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23028. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23029. masked_frame(0x89, "p") + // FIN + Ping
  23030. masked_frame(0x80, "lo"); // FIN + Continuation
  23031. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23032. for (int i = 0; i < 500 && !done; i++) {
  23033. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23034. }
  23035. ASSERT_TRUE(done);
  23036. EXPECT_EQ("Hello", received);
  23037. // The Ping between the fragments is answered with a Pong.
  23038. char pong[3];
  23039. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23040. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23041. }
  23042. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23043. Server svr;
  23044. svr.set_websocket_ping_interval(0);
  23045. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23046. std::string msg;
  23047. while (ws.read(msg)) {}
  23048. });
  23049. auto port = svr.bind_to_any_port("127.0.0.1");
  23050. std::thread t([&]() { svr.listen_after_bind(); });
  23051. auto se = detail::scope_exit([&] {
  23052. svr.stop();
  23053. t.join();
  23054. });
  23055. svr.wait_until_ready();
  23056. // Each Close payload and the reply it should get: an echo when valid, 1002
  23057. // otherwise.
  23058. std::vector<std::pair<std::string, std::string>> cases = {
  23059. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23060. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23061. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23062. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23063. };
  23064. // Also between the fragments of a message.
  23065. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23066. for (const auto &c : cases) {
  23067. auto sock = connect_raw_websocket(port, "/ws");
  23068. ASSERT_NE(INVALID_SOCKET, sock);
  23069. auto frames = prefix + masked_frame(0x88, c.first);
  23070. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23071. std::string reply;
  23072. char buf[256];
  23073. while (reply.size() < 2 + c.second.size()) {
  23074. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23075. if (n <= 0) { break; }
  23076. reply.append(buf, static_cast<size_t>(n));
  23077. }
  23078. detail::close_socket(sock);
  23079. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23080. c.second,
  23081. reply);
  23082. }
  23083. }
  23084. }
  23085. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23086. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23087. protected:
  23088. void SetUp() override {
  23089. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23090. SERVER_PRIVATE_KEY_FILE);
  23091. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23092. std::string msg;
  23093. ws::ReadResult ret;
  23094. while ((ret = ws.read(msg))) {
  23095. if (ret == ws::Binary) {
  23096. ws.send(msg.data(), msg.size());
  23097. } else {
  23098. ws.send(msg);
  23099. }
  23100. }
  23101. });
  23102. port_ = server_->bind_to_any_port(HOST);
  23103. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23104. server_->wait_until_ready();
  23105. }
  23106. void TearDown() override {
  23107. server_->stop();
  23108. if (server_thread_.joinable()) { server_thread_.join(); }
  23109. }
  23110. std::unique_ptr<SSLServer> server_;
  23111. std::thread server_thread_;
  23112. int port_ = 0;
  23113. };
  23114. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23115. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23116. {
  23117. ws::WebSocketClient client(url);
  23118. client.enable_server_certificate_verification(false);
  23119. auto calls = 0;
  23120. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23121. calls++;
  23122. return false;
  23123. });
  23124. EXPECT_FALSE(client.connect());
  23125. EXPECT_GT(calls, 0);
  23126. }
  23127. {
  23128. ws::WebSocketClient client(url);
  23129. client.enable_server_certificate_verification(false);
  23130. client.set_session_verifier([](tls::session_t) {
  23131. return SSLVerifierResponse::CertificateRejected;
  23132. });
  23133. EXPECT_FALSE(client.connect());
  23134. }
  23135. {
  23136. ws::WebSocketClient client(url);
  23137. client.enable_server_certificate_verification(false);
  23138. client.set_session_verifier([](tls::session_t) {
  23139. return SSLVerifierResponse::CertificateAccepted;
  23140. });
  23141. EXPECT_TRUE(client.connect());
  23142. }
  23143. }
  23144. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23145. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23146. "/ws-echo");
  23147. client.enable_server_certificate_verification(false);
  23148. ASSERT_TRUE(client.connect());
  23149. ASSERT_TRUE(client.is_open());
  23150. ASSERT_TRUE(client.send("Hello WSS"));
  23151. std::string msg;
  23152. EXPECT_EQ(ws::Text, client.read(msg));
  23153. EXPECT_EQ("Hello WSS", msg);
  23154. client.close();
  23155. }
  23156. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23157. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23158. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23159. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23160. // client (without calling close() first) is the only path that runs
  23161. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23162. // bug exactly.
  23163. //
  23164. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23165. // when linked against an instrumented libssl; run under Valgrind to catch it
  23166. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23167. // suite (the freed session otherwise stalls on the close handshake) — this test
  23168. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23169. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23170. {
  23171. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23172. "/ws-echo");
  23173. client.enable_server_certificate_verification(false);
  23174. client.set_read_timeout(2, 0);
  23175. client.set_write_timeout(2, 0);
  23176. ASSERT_TRUE(client.connect());
  23177. ASSERT_TRUE(client.is_open());
  23178. ASSERT_TRUE(client.send("still open"));
  23179. // Intentionally do NOT call client.close(): leaving scope runs
  23180. // shutdown_and_close() with the WebSocket still open, which must send the
  23181. // close frame while the TLS session is still alive.
  23182. }
  23183. }
  23184. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23185. // shutdown_and_close() at the start of connect(), reproducing the same
  23186. // use-after-free within the test body rather than at scope exit. The second
  23187. // connect must succeed and echo, proving the close handshake ran over a live
  23188. // session. See the note above about memory-tool requirements.
  23189. TEST_F(WebSocketSSLIntegrationTest,
  23190. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23191. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23192. "/ws-echo");
  23193. client.enable_server_certificate_verification(false);
  23194. client.set_read_timeout(2, 0);
  23195. client.set_write_timeout(2, 0);
  23196. ASSERT_TRUE(client.connect());
  23197. ASSERT_TRUE(client.is_open());
  23198. ASSERT_TRUE(client.send("still open"));
  23199. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23200. // the still-open connection, which must not touch a freed TLS session.
  23201. ASSERT_TRUE(client.connect());
  23202. ASSERT_TRUE(client.is_open());
  23203. ASSERT_TRUE(client.send("after reconnect"));
  23204. std::string msg;
  23205. EXPECT_EQ(ws::Text, client.read(msg));
  23206. EXPECT_EQ("after reconnect", msg);
  23207. client.close();
  23208. }
  23209. #endif
  23210. #ifdef CPPHTTPLIB_SSL_ENABLED
  23211. class WebSocketSSLCATest : public ::testing::Test {
  23212. protected:
  23213. void SetUp() override {
  23214. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23215. SERVER_PRIVATE_KEY_FILE);
  23216. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23217. std::string msg;
  23218. while (ws.read(msg)) {
  23219. ws.send(msg);
  23220. }
  23221. });
  23222. port_ = server_->bind_to_any_port("127.0.0.1");
  23223. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23224. server_->wait_until_ready();
  23225. }
  23226. void TearDown() override {
  23227. server_->stop();
  23228. if (server_thread_.joinable()) { server_thread_.join(); }
  23229. }
  23230. std::string url() const {
  23231. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23232. }
  23233. std::unique_ptr<SSLServer> server_;
  23234. std::thread server_thread_;
  23235. int port_ = 0;
  23236. };
  23237. // A custom CA loaded as PEM verifies the server with full certificate
  23238. // verification enabled
  23239. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23240. ws::WebSocketClient client(url());
  23241. std::string cert;
  23242. read_file(SERVER_CERT2_FILE, cert);
  23243. client.load_ca_cert_store(cert.c_str(), cert.size());
  23244. ASSERT_TRUE(client.connect());
  23245. ASSERT_TRUE(client.send("hello"));
  23246. std::string msg;
  23247. EXPECT_EQ(ws::Text, client.read(msg));
  23248. EXPECT_EQ("hello", msg);
  23249. client.close();
  23250. }
  23251. // A custom CA that does not cover the server must fail verification (the
  23252. // custom CA is exclusive; system certs are not loaded alongside it)
  23253. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23254. ws::WebSocketClient client(url());
  23255. std::string cert;
  23256. read_file(CLIENT_CA_CERT_FILE, cert);
  23257. client.load_ca_cert_store(cert.c_str(), cert.size());
  23258. auto res = client.connect();
  23259. ASSERT_FALSE(res);
  23260. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23261. EXPECT_EQ(-1, res.status());
  23262. EXPECT_NE(0u, res.ssl_backend_error());
  23263. }
  23264. // The same CA as a file path rather than PEM in memory
  23265. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23266. ws::WebSocketClient client(url());
  23267. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23268. ASSERT_TRUE(client.connect());
  23269. ASSERT_TRUE(client.send("hello"));
  23270. std::string msg;
  23271. EXPECT_EQ(ws::Text, client.read(msg));
  23272. EXPECT_EQ("hello", msg);
  23273. client.close();
  23274. }
  23275. // ...and a CA file that does not cover the server still fails, so it is the
  23276. // path above that decides the outcome
  23277. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23278. ws::WebSocketClient client(url());
  23279. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23280. ASSERT_FALSE(client.connect());
  23281. }
  23282. // Regression test: reconnecting with a native custom CA store used to reuse
  23283. // a store handle the previous TLS context had already freed (use-after-free
  23284. // under the OpenSSL backend). The context now lives as long as the client.
  23285. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23286. ws::WebSocketClient client(url());
  23287. std::string cert;
  23288. read_file(SERVER_CERT2_FILE, cert);
  23289. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23290. ASSERT_TRUE(client.connect());
  23291. client.close();
  23292. ASSERT_TRUE(client.connect());
  23293. ASSERT_TRUE(client.send("again"));
  23294. std::string msg;
  23295. EXPECT_EQ(ws::Text, client.read(msg));
  23296. EXPECT_EQ("again", msg);
  23297. client.close();
  23298. }
  23299. // Regression test: a certificate with a trusted chain but no identity match
  23300. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23301. // verification entirely for IP hosts, so this connection succeeded there.
  23302. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23303. // chain verification while the identity check must still fail.
  23304. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23305. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23306. ASSERT_TRUE(svr.is_valid());
  23307. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23308. std::string msg;
  23309. while (ws.read(msg)) {
  23310. ws.send(msg);
  23311. }
  23312. });
  23313. auto port = svr.bind_to_any_port("127.0.0.1");
  23314. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23315. auto se = detail::scope_exit([&] {
  23316. svr.stop();
  23317. t.join();
  23318. });
  23319. svr.wait_until_ready();
  23320. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23321. "/echo");
  23322. std::string cert;
  23323. read_file(SERVER_CERT_FILE, cert);
  23324. client.load_ca_cert_store(cert.c_str(), cert.size());
  23325. ASSERT_FALSE(client.connect());
  23326. }
  23327. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23328. // SNI, so nothing binds the host name to the TLS session. These bind the
  23329. // server to "localhost" instead, the only shape that exercises the SNI and
  23330. // hostname-verification path with certificate verification left enabled.
  23331. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23332. protected:
  23333. void Start(const char *cert_file) {
  23334. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23335. SERVER_PRIVATE_KEY_FILE);
  23336. ASSERT_TRUE(server_->is_valid());
  23337. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23338. std::string msg;
  23339. while (ws.read(msg)) {
  23340. ws.send(msg);
  23341. }
  23342. });
  23343. port_ = server_->bind_to_any_port("localhost");
  23344. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23345. server_->wait_until_ready();
  23346. }
  23347. void TearDown() override {
  23348. if (server_) { server_->stop(); }
  23349. if (server_thread_.joinable()) { server_thread_.join(); }
  23350. }
  23351. std::string url() const {
  23352. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23353. }
  23354. std::unique_ptr<SSLServer> server_;
  23355. std::thread server_thread_;
  23356. int port_ = 0;
  23357. };
  23358. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23359. // out and the connection is usable
  23360. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23361. Start(SERVER_CERT2_FILE);
  23362. ws::WebSocketClient client(url());
  23363. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23364. ASSERT_TRUE(client.connect());
  23365. ASSERT_TRUE(client.send("hello"));
  23366. std::string msg;
  23367. EXPECT_EQ(ws::Text, client.read(msg));
  23368. EXPECT_EQ("hello", msg);
  23369. client.close();
  23370. }
  23371. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23372. // while the identity check must still reject "localhost"
  23373. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23374. Start(SERVER_CERT_FILE);
  23375. ws::WebSocketClient client(url());
  23376. client.set_ca_cert_path(SERVER_CERT_FILE);
  23377. auto res = client.connect();
  23378. ASSERT_FALSE(res);
  23379. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23380. EXPECT_EQ(-1, res.status());
  23381. }
  23382. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23383. // disabled: the chain is still checked, only the identity check is skipped
  23384. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23385. Start(SERVER_CERT_FILE);
  23386. ws::WebSocketClient client(url());
  23387. client.set_ca_cert_path(SERVER_CERT_FILE);
  23388. client.enable_server_hostname_verification(false);
  23389. ASSERT_TRUE(client.connect());
  23390. ASSERT_TRUE(client.send("hello"));
  23391. std::string msg;
  23392. EXPECT_EQ(ws::Text, client.read(msg));
  23393. EXPECT_EQ("hello", msg);
  23394. client.close();
  23395. }
  23396. // A CA that did not sign the server certificate fails the chain, even though
  23397. // the name would match
  23398. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23399. Start(SERVER_CERT2_FILE);
  23400. ws::WebSocketClient client(url());
  23401. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23402. ASSERT_FALSE(client.connect());
  23403. }
  23404. // With verification disabled, neither the chain nor the name is checked
  23405. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23406. Start(SERVER_CERT_FILE);
  23407. ws::WebSocketClient client(url());
  23408. client.enable_server_certificate_verification(false);
  23409. ASSERT_TRUE(client.connect());
  23410. ASSERT_TRUE(client.send("hello"));
  23411. std::string msg;
  23412. EXPECT_EQ(ws::Text, client.read(msg));
  23413. EXPECT_EQ("hello", msg);
  23414. client.close();
  23415. }
  23416. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23417. protected:
  23418. void SetUp() override {
  23419. server_ = httplib::detail::make_unique<SSLServer>(
  23420. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23421. ASSERT_TRUE(server_->is_valid());
  23422. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23423. std::string msg;
  23424. while (ws.read(msg)) {
  23425. ws.send(msg);
  23426. }
  23427. });
  23428. port_ = server_->bind_to_any_port("localhost");
  23429. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23430. server_->wait_until_ready();
  23431. }
  23432. void TearDown() override {
  23433. server_->stop();
  23434. if (server_thread_.joinable()) { server_thread_.join(); }
  23435. }
  23436. std::string url() const {
  23437. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23438. }
  23439. void ConnectWithClientCert(const std::string &client_cert_file,
  23440. const std::string &client_private_key_file,
  23441. const char *private_key_password) {
  23442. std::string cert_pem, key_pem;
  23443. read_file(client_cert_file, cert_pem);
  23444. read_file(client_private_key_file, key_pem);
  23445. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23446. key_pem.c_str(), key_pem.size(),
  23447. private_key_password};
  23448. ws::WebSocketClient client(url(), pem);
  23449. ASSERT_TRUE(client.is_valid());
  23450. client.enable_server_certificate_verification(false);
  23451. ASSERT_TRUE(client.connect());
  23452. ASSERT_TRUE(client.send("hello"));
  23453. std::string msg;
  23454. EXPECT_EQ(ws::Text, client.read(msg));
  23455. EXPECT_EQ("hello", msg);
  23456. client.close();
  23457. }
  23458. std::unique_ptr<SSLServer> server_;
  23459. std::thread server_thread_;
  23460. int port_ = 0;
  23461. };
  23462. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23463. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23464. }
  23465. // Control for the tests above: the fixture's server really does require a
  23466. // client certificate, so it is the PEM the constructor installed that decides
  23467. // the outcome.
  23468. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23469. ws::WebSocketClient client(url());
  23470. ASSERT_TRUE(client.is_valid());
  23471. client.enable_server_certificate_verification(false);
  23472. EXPECT_FALSE(client.connect());
  23473. }
  23474. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23475. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23476. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23477. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23478. }
  23479. #endif
  23480. #if !defined(_WIN32)
  23481. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23482. auto secret_dir = std::string("./symlink_test_secret");
  23483. auto served_dir = std::string("./symlink_test_served");
  23484. auto secret_file = secret_dir + "/secret.txt";
  23485. auto symlink_path = served_dir + "/escape";
  23486. // Setup: create directories and files
  23487. mkdir(secret_dir.c_str(), 0755);
  23488. mkdir(served_dir.c_str(), 0755);
  23489. {
  23490. std::ofstream ofs(secret_file);
  23491. ofs << "SECRET_DATA";
  23492. }
  23493. // Create symlink using absolute path so it resolves correctly
  23494. #ifdef PATH_MAX
  23495. char abs_secret[PATH_MAX];
  23496. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23497. #else
  23498. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23499. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23500. ASSERT_NE(nullptr, abs_secret);
  23501. #endif
  23502. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23503. auto se = detail::scope_exit([&] {
  23504. unlink(symlink_path.c_str());
  23505. unlink(secret_file.c_str());
  23506. rmdir(served_dir.c_str());
  23507. rmdir(secret_dir.c_str());
  23508. });
  23509. Server svr;
  23510. svr.set_mount_point("/", served_dir);
  23511. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23512. auto se2 = detail::scope_exit([&] {
  23513. svr.stop();
  23514. listen_thread.join();
  23515. });
  23516. svr.wait_until_ready();
  23517. Client cli("localhost", PORT);
  23518. // Symlink pointing outside base dir should be blocked
  23519. auto res = cli.Get("/escape/secret.txt");
  23520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23521. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23522. }
  23523. #endif
  23524. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23525. // "GET /smuggled" request), reads the first response, and only then sends the
  23526. // embedded request as the body. Returns how many times /smuggled ran.
  23527. //
  23528. // The body is sent AFTER receiving the first response (as in the original
  23529. // PoC) so that the stream_line_reader cannot buffer it together with the
  23530. // headers of the first request.
  23531. static int count_smuggled_requests(const std::string &outer_head,
  23532. std::string &first_response) {
  23533. Server svr;
  23534. svr.set_mount_point("/", "./www");
  23535. std::atomic<int> smuggled_count(0);
  23536. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23537. smuggled_count++;
  23538. res.set_content("oops", "text/plain");
  23539. });
  23540. svr.Post("/post", [&](const Request &req, Response &res) {
  23541. res.set_content(req.body, "text/plain");
  23542. });
  23543. auto port = svr.bind_to_any_port("localhost");
  23544. thread t = thread([&] { svr.listen_after_bind(); });
  23545. auto se = detail::scope_exit([&] {
  23546. svr.stop();
  23547. t.join();
  23548. });
  23549. svr.wait_until_ready();
  23550. auto error = Error::Success;
  23551. auto sock = detail::create_client_socket(
  23552. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23553. /*connection_timeout_sec=*/2, 0,
  23554. /*read_timeout_sec=*/2, 0,
  23555. /*write_timeout_sec=*/2, 0, std::string(), error);
  23556. EXPECT_NE(INVALID_SOCKET, sock);
  23557. if (sock == INVALID_SOCKET) { return -1; }
  23558. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23559. // The "smuggled" request will be sent as the body of the outer request
  23560. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23561. "Host: localhost\r\n"
  23562. "Connection: close\r\n"
  23563. "\r\n";
  23564. auto head = outer_head;
  23565. auto len = std::to_string(smuggled.size());
  23566. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23567. pos = head.find("{len}", pos + len.size())) {
  23568. head.replace(pos, 5, len);
  23569. }
  23570. // Step 1: Send only the outer request headers (no body yet)
  23571. auto sent = send(sock, head.data(), head.size(), 0);
  23572. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23573. // Step 2: Read the first response
  23574. char buf[4096];
  23575. for (;;) {
  23576. auto n = recv(sock, buf, sizeof(buf), 0);
  23577. if (n <= 0) break;
  23578. first_response.append(buf, static_cast<size_t>(n));
  23579. // Stop once we have a complete response (headers + body)
  23580. auto hdr_end = first_response.find("\r\n\r\n");
  23581. if (hdr_end != std::string::npos) {
  23582. // Check for Content-Length to know when the body is complete
  23583. auto cl_pos = first_response.find("Content-Length:");
  23584. if (cl_pos != std::string::npos) {
  23585. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23586. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23587. auto cl = std::stoul(
  23588. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23589. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23590. } else {
  23591. break; // No Content-Length, assume headers-only response
  23592. }
  23593. }
  23594. }
  23595. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23596. // vulnerable server the keep-alive loop reads this as a second request. The
  23597. // server may already have closed the connection, so the result is ignored.
  23598. send(sock, smuggled.data(), smuggled.size(), 0);
  23599. // Half-close so that a server which drained the body sees EOF and closes,
  23600. // instead of the read below waiting for the read timeout.
  23601. #ifdef _WIN32
  23602. ::shutdown(sock, SD_SEND);
  23603. #else
  23604. ::shutdown(sock, SHUT_WR);
  23605. #endif
  23606. // Step 4: Read until the server closes the connection
  23607. for (;;) {
  23608. auto n = recv(sock, buf, sizeof(buf), 0);
  23609. if (n <= 0) break;
  23610. }
  23611. return smuggled_count.load();
  23612. }
  23613. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23614. // A GET request with Content-Length to a static file handler must have its
  23615. // body drained before the keep-alive connection is reused. Otherwise the
  23616. // unread body bytes are interpreted as the next HTTP request.
  23617. std::string first_response;
  23618. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23619. "Host: localhost\r\n"
  23620. "Content-Length: {len}\r\n"
  23621. "\r\n",
  23622. first_response));
  23623. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23624. }
  23625. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23626. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23627. // be answered with 400 and the connection closed. Treating it as "no body"
  23628. // leaves the body to be parsed as the next request.
  23629. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23630. const char *targets[] = {
  23631. "GET /file", // handler that never reads the body
  23632. "GET /not-found", // no handler matches (404)
  23633. "POST /post", // handler that reads the body
  23634. };
  23635. for (auto target : targets) {
  23636. for (auto value : values) {
  23637. std::string first_response;
  23638. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23639. " HTTP/1.1\r\n"
  23640. "Host: localhost\r\n"
  23641. "Content-Length: " +
  23642. value + "\r\n\r\n",
  23643. first_response))
  23644. << target << " with Content-Length: " << value;
  23645. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23646. << target << " with Content-Length: " << value;
  23647. }
  23648. }
  23649. }
  23650. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23651. // A 400 for an unparseable request line leaves the rest of the message
  23652. // unread, so the connection must be closed rather than reused.
  23653. std::string first_response;
  23654. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23655. "Host: localhost\r\n"
  23656. "Content-Length: {len}\r\n"
  23657. "\r\n",
  23658. first_response));
  23659. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23660. }
  23661. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23662. // Same as above for a header block that fails to parse.
  23663. std::string first_response;
  23664. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23665. "Host: localhost\r\n"
  23666. "Bad Header\r\n"
  23667. "Content-Length: {len}\r\n"
  23668. "\r\n",
  23669. first_response));
  23670. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23671. }
  23672. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23673. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23674. // server must not read another request on that connection, even when the
  23675. // request had no body to drain.
  23676. std::string first_response;
  23677. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23678. "Host: localhost\r\n"
  23679. "\r\n",
  23680. first_response));
  23681. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23682. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23683. }
  23684. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23685. // A content reader that stops early leaves the stream inside the body.
  23686. // Draining the whole Content-Length from there, or reading the body again,
  23687. // reads into the next request, and whatever follows is parsed as a request
  23688. // of its own.
  23689. Server svr;
  23690. std::atomic<int> smuggled_count(0);
  23691. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23692. svr.Post("/upload", [](const Request &req, Response &res,
  23693. const ContentReader &content_reader) {
  23694. // Stop at the last chunk, so the whole body has been read however it
  23695. // arrives.
  23696. auto length = req.get_header_value_u64("Content-Length");
  23697. size_t total = 0;
  23698. auto consumed = content_reader([&](const char *, size_t n) {
  23699. total += n;
  23700. return total < length;
  23701. });
  23702. EXPECT_FALSE(consumed);
  23703. if (req.has_param("retry")) {
  23704. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23705. }
  23706. // Replace the 400 the aborted read set, which would close the connection.
  23707. res.set_redirect("/done");
  23708. });
  23709. auto port = svr.bind_to_any_port(HOST);
  23710. thread t = thread([&] { svr.listen_after_bind(); });
  23711. auto se = detail::scope_exit([&] {
  23712. svr.stop();
  23713. t.join();
  23714. });
  23715. svr.wait_until_ready();
  23716. // A front end sees the second request as a POST whose body is the GET. The
  23717. // first body is as long as the POST's headers, so draining it again reads
  23718. // exactly those and leaves the GET to be parsed next.
  23719. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23720. "Host: localhost\r\n"
  23721. "\r\n";
  23722. std::string second_head = "POST /post HTTP/1.1\r\n"
  23723. "Host: localhost\r\n"
  23724. "Content-Length: " +
  23725. std::to_string(inner.size()) +
  23726. "\r\n"
  23727. "\r\n";
  23728. for (auto target : {"/upload", "/upload?retry"}) {
  23729. smuggled_count = 0;
  23730. std::string request = "POST " + std::string(target) +
  23731. " HTTP/1.1\r\n"
  23732. "Host: localhost\r\n"
  23733. "Content-Length: " +
  23734. std::to_string(second_head.size()) +
  23735. "\r\n"
  23736. "\r\n" +
  23737. std::string(second_head.size(), 'A') + second_head +
  23738. inner;
  23739. std::string response;
  23740. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23741. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23742. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23743. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23744. EXPECT_EQ(0, smuggled_count.load()) << target;
  23745. }
  23746. }
  23747. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23748. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23749. // must be rejected with 400 Bad Request.
  23750. Server svr;
  23751. svr.Post("/test", [&](const Request &, Response &res) {
  23752. res.set_content("ok", "text/plain");
  23753. });
  23754. thread t = thread([&] { svr.listen(HOST, PORT); });
  23755. auto se = detail::scope_exit([&] {
  23756. svr.stop();
  23757. t.join();
  23758. ASSERT_FALSE(svr.is_running());
  23759. });
  23760. svr.wait_until_ready();
  23761. // Exact "chunked"
  23762. {
  23763. auto req = "POST /test HTTP/1.1\r\n"
  23764. "Host: localhost\r\n"
  23765. "Content-Length: 5\r\n"
  23766. "Transfer-Encoding: chunked\r\n"
  23767. "Connection: close\r\n"
  23768. "\r\n"
  23769. "hello";
  23770. std::string response;
  23771. ASSERT_TRUE(send_request(1, req, &response));
  23772. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23773. response.substr(0, response.find("\r\n")));
  23774. }
  23775. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23776. {
  23777. auto req = "POST /test HTTP/1.1\r\n"
  23778. "Host: localhost\r\n"
  23779. "Content-Length: 5\r\n"
  23780. "Transfer-Encoding: gzip, chunked\r\n"
  23781. "Connection: close\r\n"
  23782. "\r\n"
  23783. "hello";
  23784. std::string response;
  23785. ASSERT_TRUE(send_request(1, req, &response));
  23786. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23787. response.substr(0, response.find("\r\n")));
  23788. }
  23789. }
  23790. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23791. Server svr;
  23792. svr.Post("/test", [&](const Request &, Response &res) {
  23793. res.set_content("ok", "text/plain");
  23794. });
  23795. thread t = thread([&] { svr.listen(HOST, PORT); });
  23796. auto se = detail::scope_exit([&] {
  23797. svr.stop();
  23798. t.join();
  23799. ASSERT_FALSE(svr.is_running());
  23800. });
  23801. svr.wait_until_ready();
  23802. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23803. // length cannot be determined, so the server must answer 400 and close
  23804. // rather than treat the request as bodyless and leave the body in the
  23805. // socket for the next request to pick up.
  23806. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23807. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23808. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23809. std::string response;
  23810. ASSERT_TRUE(send_request(1, req, &response));
  23811. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23812. response.substr(0, response.find("\r\n")))
  23813. << transfer_encoding;
  23814. }
  23815. // RFC 9110 5.3: the codings may also be split across several
  23816. // Transfer-Encoding lines, which combine in the order they were received.
  23817. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23818. // just like the single-line "chunked, gzip" above.
  23819. {
  23820. auto req = "POST /test HTTP/1.1\r\n"
  23821. "Host: localhost\r\n"
  23822. "Transfer-Encoding: chunked\r\n"
  23823. "Transfer-Encoding: gzip\r\n"
  23824. "\r\n"
  23825. "0\r\n\r\n";
  23826. std::string response;
  23827. ASSERT_TRUE(send_request(1, req, &response));
  23828. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23829. response.substr(0, response.find("\r\n")));
  23830. }
  23831. // A sequence ending in chunked stays valid.
  23832. auto req = "POST /test HTTP/1.1\r\n"
  23833. "Host: localhost\r\n"
  23834. "Transfer-Encoding: gzip, chunked\r\n"
  23835. "Connection: close\r\n"
  23836. "\r\n"
  23837. "0\r\n\r\n";
  23838. std::string response;
  23839. ASSERT_TRUE(send_request(1, req, &response));
  23840. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23841. // ...including when it is spread over several lines.
  23842. auto split_req = "POST /test HTTP/1.1\r\n"
  23843. "Host: localhost\r\n"
  23844. "Transfer-Encoding: gzip\r\n"
  23845. "Transfer-Encoding: chunked\r\n"
  23846. "Connection: close\r\n"
  23847. "\r\n"
  23848. "0\r\n\r\n";
  23849. std::string split_response;
  23850. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23851. EXPECT_EQ("HTTP/1.1 200 OK",
  23852. split_response.substr(0, split_response.find("\r\n")));
  23853. }
  23854. // Regression for issue #2450: a DELETE without Content-Length on a
  23855. // keep-alive connection must not let the post-response drain consume the
  23856. // next request's bytes.
  23857. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23858. Server svr;
  23859. std::atomic<int> delete_count(0);
  23860. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23861. delete_count++;
  23862. res.status = StatusCode::NoContent_204;
  23863. });
  23864. auto port = svr.bind_to_any_port(HOST);
  23865. thread t = thread([&] { svr.listen_after_bind(); });
  23866. auto se = detail::scope_exit([&] {
  23867. svr.stop();
  23868. t.join();
  23869. });
  23870. svr.wait_until_ready();
  23871. auto error = Error::Success;
  23872. auto sock = detail::create_client_socket(
  23873. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23874. /*connection_timeout_sec=*/2, 0,
  23875. /*read_timeout_sec=*/2, 0,
  23876. /*write_timeout_sec=*/2, 0, std::string(), error);
  23877. ASSERT_NE(INVALID_SOCKET, sock);
  23878. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23879. auto send_request_and_read_response = [&](const std::string &req,
  23880. std::string &out) -> bool {
  23881. auto sent = send(sock, req.data(), req.size(), 0);
  23882. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23883. char buf[4096];
  23884. for (;;) {
  23885. auto n = recv(sock, buf, sizeof(buf), 0);
  23886. if (n <= 0) { return !out.empty(); }
  23887. out.append(buf, static_cast<size_t>(n));
  23888. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23889. }
  23890. };
  23891. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23892. "Host: localhost\r\n"
  23893. "\r\n";
  23894. std::string resp1;
  23895. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23896. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23897. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23898. "Host: localhost\r\n"
  23899. "Connection: close\r\n"
  23900. "\r\n";
  23901. std::string resp2;
  23902. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23903. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23904. EXPECT_EQ(2, delete_count.load());
  23905. }
  23906. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23907. Server svr;
  23908. svr.Post("/ingest", [&](const Request &, Response &res,
  23909. const ContentReader &content_reader) {
  23910. auto consumed = content_reader([](const char *, size_t) { return false; });
  23911. EXPECT_FALSE(consumed);
  23912. res.status = StatusCode::Conflict_409;
  23913. res.set_header("Connection", "close");
  23914. });
  23915. auto port = svr.bind_to_any_port(HOST);
  23916. thread t = thread([&] { svr.listen_after_bind(); });
  23917. auto se = detail::scope_exit([&] {
  23918. svr.stop();
  23919. t.join();
  23920. });
  23921. svr.wait_until_ready();
  23922. auto error = Error::Success;
  23923. auto sock = detail::create_client_socket(
  23924. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23925. /*connection_timeout_sec=*/2, 0,
  23926. /*read_timeout_sec=*/1, 0,
  23927. /*write_timeout_sec=*/2, 0, std::string(), error);
  23928. ASSERT_NE(INVALID_SOCKET, sock);
  23929. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23930. std::string request = "POST /ingest HTTP/1.1\r\n"
  23931. "Host: localhost\r\n"
  23932. "Transfer-Encoding: chunked\r\n"
  23933. "\r\n"
  23934. "4\r\n"
  23935. "data\r\n";
  23936. auto sent = send(sock, request.data(), request.size(), 0);
  23937. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23938. std::string response;
  23939. ssize_t received = 0;
  23940. do {
  23941. char buf[4096];
  23942. received = recv(sock, buf, sizeof(buf), 0);
  23943. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23944. } while (received > 0);
  23945. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23946. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23947. EXPECT_EQ(0, received);
  23948. }
  23949. namespace no_proxy_test {
  23950. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23951. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23952. // calling listen().
  23953. class ScopedServer {
  23954. public:
  23955. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23956. ~ScopedServer() {
  23957. svr_.stop();
  23958. if (th_.joinable()) { th_.join(); }
  23959. }
  23960. Server &svr() { return svr_; }
  23961. int port() const { return port_; }
  23962. void listen() {
  23963. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23964. svr_.wait_until_ready();
  23965. }
  23966. private:
  23967. Server svr_;
  23968. std::thread th_;
  23969. int port_ = 0;
  23970. };
  23971. class ProxyAndTargetServers {
  23972. public:
  23973. ProxyAndTargetServers() {
  23974. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23975. proxy_hits_++;
  23976. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23977. res.set_content("via-proxy", "text/plain");
  23978. });
  23979. target_.Get(".*", [this](const Request &req, Response &res) {
  23980. target_hits_++;
  23981. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23982. res.set_content("direct", "text/plain");
  23983. });
  23984. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23985. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23986. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23987. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23988. proxy_mock_.wait_until_ready();
  23989. target_.wait_until_ready();
  23990. }
  23991. ~ProxyAndTargetServers() {
  23992. proxy_mock_.stop();
  23993. target_.stop();
  23994. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23995. if (target_thread_.joinable()) { target_thread_.join(); }
  23996. }
  23997. Server &proxy_mock() { return proxy_mock_; }
  23998. Server &target() { return target_; }
  23999. int proxy_port() const { return proxy_port_; }
  24000. int target_port() const { return target_port_; }
  24001. int proxy_hits() const { return proxy_hits_.load(); }
  24002. int target_hits() const { return target_hits_.load(); }
  24003. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24004. void reset_counters() {
  24005. proxy_hits_ = 0;
  24006. target_hits_ = 0;
  24007. last_had_proxy_authz_ = false;
  24008. }
  24009. private:
  24010. Server proxy_mock_;
  24011. Server target_;
  24012. std::thread proxy_thread_;
  24013. std::thread target_thread_;
  24014. int proxy_port_ = 0;
  24015. int target_port_ = 0;
  24016. std::atomic<int> proxy_hits_{0};
  24017. std::atomic<int> target_hits_{0};
  24018. std::atomic<bool> last_had_proxy_authz_{false};
  24019. };
  24020. inline std::unique_ptr<Client> make_client(const std::string &host,
  24021. ProxyAndTargetServers &s) {
  24022. auto cli = detail::make_unique<Client>(host, s.target_port());
  24023. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24024. cli->set_proxy("127.0.0.1", s.proxy_port());
  24025. return cli;
  24026. }
  24027. } // namespace no_proxy_test
  24028. using no_proxy_test::make_client;
  24029. using no_proxy_test::ProxyAndTargetServers;
  24030. TEST(NoProxyTest, ExactHostnameBypasses) {
  24031. ProxyAndTargetServers s;
  24032. auto cli = make_client("example.com", s);
  24033. cli->set_no_proxy({"example.com"});
  24034. auto res = cli->Get("/");
  24035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24036. EXPECT_EQ(0, s.proxy_hits());
  24037. EXPECT_EQ(1, s.target_hits());
  24038. }
  24039. TEST(NoProxyTest, SubdomainBypasses) {
  24040. ProxyAndTargetServers s;
  24041. auto cli = make_client("foo.example.com", s);
  24042. cli->set_no_proxy({"example.com"});
  24043. auto res = cli->Get("/");
  24044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24045. EXPECT_EQ(0, s.proxy_hits());
  24046. EXPECT_EQ(1, s.target_hits());
  24047. }
  24048. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24049. // Regression guard: "evilexample.com" must not be considered a subdomain
  24050. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24051. // check would let traffic bypass the proxy and leak credentials direct
  24052. // to the attacker host.
  24053. ProxyAndTargetServers s;
  24054. auto cli = make_client("evilexample.com", s);
  24055. cli->set_no_proxy({"example.com"});
  24056. auto res = cli->Get("/");
  24057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24058. EXPECT_GE(s.proxy_hits(), 1);
  24059. EXPECT_EQ(0, s.target_hits());
  24060. }
  24061. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24062. ProxyAndTargetServers s;
  24063. auto cli = make_client("example.com.evil.com", s);
  24064. cli->set_no_proxy({"example.com"});
  24065. auto res = cli->Get("/");
  24066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24067. EXPECT_GE(s.proxy_hits(), 1);
  24068. EXPECT_EQ(0, s.target_hits());
  24069. }
  24070. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24071. ProxyAndTargetServers s;
  24072. auto cli = make_client("example.com", s);
  24073. cli->set_no_proxy({".example.com"});
  24074. auto res = cli->Get("/");
  24075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24076. EXPECT_EQ(0, s.proxy_hits());
  24077. EXPECT_EQ(1, s.target_hits());
  24078. }
  24079. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24080. ProxyAndTargetServers s;
  24081. auto cli = make_client("Example.COM", s);
  24082. cli->set_no_proxy({"EXAMPLE.com"});
  24083. auto res = cli->Get("/");
  24084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24085. EXPECT_EQ(0, s.proxy_hits());
  24086. EXPECT_EQ(1, s.target_hits());
  24087. }
  24088. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24089. ProxyAndTargetServers s;
  24090. auto cli = make_client("example.com.", s);
  24091. cli->set_no_proxy({"example.com"});
  24092. auto res = cli->Get("/");
  24093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24094. EXPECT_EQ(0, s.proxy_hits());
  24095. EXPECT_EQ(1, s.target_hits());
  24096. }
  24097. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24098. // Trailing dots must be normalized on BOTH sides — host and entry.
  24099. // An implementation that only strips the host-side trailing dot would
  24100. // fail to match host "example.com" against entry "example.com." because
  24101. // a literal substring search would compare 11 chars against 12.
  24102. ProxyAndTargetServers s;
  24103. auto cli = make_client("example.com", s);
  24104. cli->set_no_proxy({"example.com."});
  24105. auto res = cli->Get("/");
  24106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24107. EXPECT_EQ(0, s.proxy_hits());
  24108. EXPECT_EQ(1, s.target_hits());
  24109. }
  24110. TEST(NoProxyTest, WildcardBypassesEverything) {
  24111. ProxyAndTargetServers s;
  24112. auto cli = make_client("anything.invalid.test", s);
  24113. cli->set_no_proxy({"*"});
  24114. auto res = cli->Get("/");
  24115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24116. EXPECT_EQ(0, s.proxy_hits());
  24117. EXPECT_EQ(1, s.target_hits());
  24118. }
  24119. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24120. ProxyAndTargetServers s;
  24121. Client cli("127.0.0.1", s.target_port());
  24122. cli.set_proxy("127.0.0.1", s.proxy_port());
  24123. cli.set_no_proxy({"127.0.0.1"});
  24124. auto res = cli.Get("/");
  24125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24126. EXPECT_EQ(0, s.proxy_hits());
  24127. EXPECT_EQ(1, s.target_hits());
  24128. }
  24129. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24130. ProxyAndTargetServers s;
  24131. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24132. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24133. cli.set_proxy("127.0.0.1", s.proxy_port());
  24134. cli.set_no_proxy({"::1"});
  24135. auto res = cli.Get("/");
  24136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24137. EXPECT_EQ(0, s.proxy_hits());
  24138. EXPECT_EQ(1, s.target_hits());
  24139. }
  24140. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24141. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24142. // must still be recognized as IPv6 for CIDR matching. Implementations
  24143. // that detect IPv6 only when the host begins with '[' would parse the
  24144. // host as a hostname and miss the match.
  24145. ProxyAndTargetServers s;
  24146. Client cli("fe80::1", s.target_port());
  24147. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24148. cli.set_proxy("127.0.0.1", s.proxy_port());
  24149. cli.set_no_proxy({"fe80::/10"});
  24150. auto res = cli.Get("/");
  24151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24152. EXPECT_EQ(0, s.proxy_hits());
  24153. EXPECT_EQ(1, s.target_hits());
  24154. }
  24155. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24156. ProxyAndTargetServers s;
  24157. Client cli("::1", s.target_port());
  24158. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24159. cli.set_proxy("127.0.0.1", s.proxy_port());
  24160. cli.set_no_proxy({"[::1]"});
  24161. auto res = cli.Get("/");
  24162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24163. EXPECT_EQ(0, s.proxy_hits());
  24164. EXPECT_EQ(1, s.target_hits());
  24165. }
  24166. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24167. ProxyAndTargetServers s;
  24168. Client cli("fe80::1", s.target_port());
  24169. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24170. cli.set_proxy("127.0.0.1", s.proxy_port());
  24171. cli.set_no_proxy({"[fe80::]/10"});
  24172. auto res = cli.Get("/");
  24173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24174. EXPECT_EQ(0, s.proxy_hits());
  24175. EXPECT_EQ(1, s.target_hits());
  24176. }
  24177. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24178. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24179. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24180. // tricks via address-family conversion.
  24181. ProxyAndTargetServers s;
  24182. Client cli("::ffff:127.0.0.1", s.target_port());
  24183. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24184. cli.set_proxy("127.0.0.1", s.proxy_port());
  24185. cli.set_no_proxy({"127.0.0.1"});
  24186. auto res = cli.Get("/");
  24187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24188. EXPECT_GE(s.proxy_hits(), 1);
  24189. EXPECT_EQ(0, s.target_hits());
  24190. }
  24191. TEST(NoProxyTest, IPv4CidrMatch) {
  24192. ProxyAndTargetServers s;
  24193. Client cli("127.0.0.1", s.target_port());
  24194. cli.set_proxy("127.0.0.1", s.proxy_port());
  24195. cli.set_no_proxy({"127.0.0.0/8"});
  24196. auto res = cli.Get("/");
  24197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24198. EXPECT_EQ(0, s.proxy_hits());
  24199. EXPECT_EQ(1, s.target_hits());
  24200. }
  24201. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24202. ProxyAndTargetServers s;
  24203. Client cli("127.0.0.1", s.target_port());
  24204. cli.set_proxy("127.0.0.1", s.proxy_port());
  24205. cli.set_no_proxy({"10.0.0.0/8"});
  24206. auto res = cli.Get("/");
  24207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24208. EXPECT_GE(s.proxy_hits(), 1);
  24209. EXPECT_EQ(0, s.target_hits());
  24210. }
  24211. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24212. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24213. // IPv4 target matches.
  24214. ProxyAndTargetServers s;
  24215. Client cli("127.0.0.1", s.target_port());
  24216. cli.set_proxy("127.0.0.1", s.proxy_port());
  24217. cli.set_no_proxy({"0.0.0.0/0"});
  24218. auto res = cli.Get("/");
  24219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24220. EXPECT_EQ(0, s.proxy_hits());
  24221. EXPECT_EQ(1, s.target_hits());
  24222. }
  24223. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24224. ProxyAndTargetServers s;
  24225. Client cli("127.0.0.1", s.target_port());
  24226. cli.set_proxy("127.0.0.1", s.proxy_port());
  24227. cli.set_no_proxy({"127.0.0.1"});
  24228. auto res = cli.Get("/");
  24229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24230. EXPECT_EQ(0, s.proxy_hits());
  24231. EXPECT_EQ(1, s.target_hits());
  24232. }
  24233. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24234. ProxyAndTargetServers s;
  24235. Client cli("127.0.0.1", s.target_port());
  24236. cli.set_proxy("127.0.0.1", s.proxy_port());
  24237. cli.set_no_proxy({"127.0.0.0/33"});
  24238. auto res = cli.Get("/");
  24239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24240. EXPECT_GE(s.proxy_hits(), 1);
  24241. EXPECT_EQ(0, s.target_hits());
  24242. }
  24243. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24244. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24245. ProxyAndTargetServers s;
  24246. Client cli("127.0.0.1", s.target_port());
  24247. cli.set_proxy("127.0.0.1", s.proxy_port());
  24248. cli.set_no_proxy({"127.0.0.1/"});
  24249. auto res = cli.Get("/");
  24250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24251. EXPECT_GE(s.proxy_hits(), 1);
  24252. EXPECT_EQ(0, s.target_hits());
  24253. }
  24254. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24255. ProxyAndTargetServers s;
  24256. auto cli = make_client("internal.corp", s);
  24257. cli->set_proxy_basic_auth("u", "p");
  24258. cli->set_no_proxy({"internal.corp"});
  24259. auto res = cli->Get("/");
  24260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24261. EXPECT_EQ(1, s.target_hits());
  24262. EXPECT_EQ(0, s.proxy_hits());
  24263. EXPECT_FALSE(s.last_had_proxy_authz())
  24264. << "Proxy-Authorization must not be sent direct to the target";
  24265. }
  24266. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24267. ProxyAndTargetServers s;
  24268. auto cli = make_client("public.example", s);
  24269. cli->set_proxy_basic_auth("u", "p");
  24270. cli->set_no_proxy({"internal.corp"}); // does not match
  24271. auto res = cli->Get("/");
  24272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24273. EXPECT_GE(s.proxy_hits(), 1);
  24274. EXPECT_TRUE(s.last_had_proxy_authz());
  24275. }
  24276. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24277. std::atomic<int> hits{0};
  24278. std::atomic<int> hits_with_authz{0};
  24279. no_proxy_test::ScopedServer proxy_mock;
  24280. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24281. hits++;
  24282. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24283. if (req.target.find("/redir") != std::string::npos) {
  24284. res.set_redirect("http://other.example/landed");
  24285. } else {
  24286. res.set_content("via-proxy", "text/plain");
  24287. }
  24288. });
  24289. proxy_mock.listen();
  24290. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24291. hits = 0;
  24292. hits_with_authz = 0;
  24293. Client cli("public.example", 80);
  24294. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24295. cli.set_proxy_basic_auth(c.first, c.second);
  24296. cli.set_follow_location(true);
  24297. // The redirect to another host goes through the proxy as well
  24298. auto res = cli.Get("/redir");
  24299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24300. EXPECT_EQ(2, hits.load());
  24301. EXPECT_EQ(2, hits_with_authz.load());
  24302. }
  24303. }
  24304. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24305. ProxyAndTargetServers s;
  24306. auto cli = make_client("anything.test", s);
  24307. auto res = cli->Get("/");
  24308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24309. EXPECT_GE(s.proxy_hits(), 1);
  24310. EXPECT_EQ(0, s.target_hits());
  24311. }
  24312. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24313. ProxyAndTargetServers s;
  24314. auto cli = make_client("example.com", s);
  24315. cli->set_no_proxy({"example.com:8080"});
  24316. auto res = cli->Get("/");
  24317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24318. EXPECT_GE(s.proxy_hits(), 1);
  24319. EXPECT_EQ(0, s.target_hits());
  24320. }
  24321. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24322. ProxyAndTargetServers s;
  24323. auto cli = make_client("anything.test", s);
  24324. cli->set_no_proxy({"", " ", "\t"});
  24325. auto res = cli->Get("/");
  24326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24327. EXPECT_GE(s.proxy_hits(), 1);
  24328. EXPECT_EQ(0, s.target_hits());
  24329. }
  24330. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24331. // An entry with leading/trailing whitespace must still match — env-style
  24332. // values are commonly pasted with stray spaces and an implementation
  24333. // that feeds the raw token directly to inet_pton would fail to match
  24334. // valid CIDRs because of the spaces.
  24335. ProxyAndTargetServers s;
  24336. Client cli("127.0.0.1", s.target_port());
  24337. cli.set_proxy("127.0.0.1", s.proxy_port());
  24338. cli.set_no_proxy({" 127.0.0.0/8 "});
  24339. auto res = cli.Get("/");
  24340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24341. EXPECT_EQ(0, s.proxy_hits());
  24342. EXPECT_EQ(1, s.target_hits());
  24343. }
  24344. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24345. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24346. // go direct and must NOT carry Proxy-Authorization.
  24347. std::atomic<int> proxy_hits{0};
  24348. std::atomic<int> target_hits{0};
  24349. std::atomic<bool> target_saw_authz{false};
  24350. no_proxy_test::ScopedServer proxy_mock, target;
  24351. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24352. proxy_hits++;
  24353. res.status = 302;
  24354. res.set_header("Location", "http://127.0.0.1:" +
  24355. std::to_string(target.port()) + "/landed");
  24356. });
  24357. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24358. target_hits++;
  24359. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24360. res.set_content("direct", "text/plain");
  24361. });
  24362. proxy_mock.listen();
  24363. target.listen();
  24364. Client cli("public.example", target.port());
  24365. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24366. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24367. cli.set_proxy_basic_auth("u", "p");
  24368. cli.set_no_proxy({"127.0.0.1"});
  24369. cli.set_follow_location(true);
  24370. auto res = cli.Get("/redir");
  24371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24372. EXPECT_GE(proxy_hits.load(), 1);
  24373. EXPECT_GE(target_hits.load(), 1);
  24374. EXPECT_FALSE(target_saw_authz.load());
  24375. }
  24376. #ifdef CPPHTTPLIB_SSL_ENABLED
  24377. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24378. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24379. // proxy creds would be sent to the (possibly hostile) origin.
  24380. std::atomic<int> target_hits{0};
  24381. std::atomic<bool> target_saw_proxy_authz{false};
  24382. no_proxy_test::ScopedServer target;
  24383. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24384. target_hits++;
  24385. if (req.has_header("Proxy-Authorization")) {
  24386. target_saw_proxy_authz = true;
  24387. }
  24388. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24389. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24390. "nonce=\"abc\", algorithm=MD5");
  24391. });
  24392. target.listen();
  24393. // The proxy address is set to the target's port: the bypass MUST kick in;
  24394. // if it doesn't, the test still routes "via proxy" to the same server and
  24395. // the Proxy-Authorization assertion below catches the leak.
  24396. Client cli("evil.example", target.port());
  24397. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24398. cli.set_proxy("127.0.0.1", target.port());
  24399. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24400. cli.set_no_proxy({"evil.example"});
  24401. auto res = cli.Get("/x");
  24402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24403. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24404. EXPECT_EQ(1, target_hits.load());
  24405. EXPECT_FALSE(target_saw_proxy_authz.load());
  24406. }
  24407. #endif
  24408. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24409. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24410. std::atomic<int> proxy_hits{0};
  24411. std::atomic<int> bypass_hits{0};
  24412. std::atomic<bool> proxy_saw_c_url{false};
  24413. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24414. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24415. proxy_hits++;
  24416. if (req.path.find("/start") != std::string::npos) {
  24417. res.status = 302;
  24418. res.set_header("Location", "http://127.0.0.1:" +
  24419. std::to_string(bypass_server.port()) +
  24420. "/middle");
  24421. return;
  24422. }
  24423. if (req.path.find("/end") != std::string::npos) {
  24424. proxy_saw_c_url = true;
  24425. res.set_content("c-via-proxy", "text/plain");
  24426. return;
  24427. }
  24428. res.set_content("unexpected", "text/plain");
  24429. });
  24430. // public.example's "advertised" port is arbitrary (the request never lands
  24431. // there — it goes through the proxy), but use a dynamic value to stay
  24432. // friendly with sharded parallel runs.
  24433. int public_port = bypass_server.port();
  24434. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24435. bypass_hits++;
  24436. res.status = 302;
  24437. res.set_header("Location", "http://public.example:" +
  24438. std::to_string(public_port) + "/end");
  24439. });
  24440. proxy_mock.listen();
  24441. bypass_server.listen();
  24442. Client cli("public.example", public_port);
  24443. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24444. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24445. cli.set_no_proxy({"127.0.0.1"});
  24446. cli.set_follow_location(true);
  24447. auto res = cli.Get("/start");
  24448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24449. EXPECT_EQ(StatusCode::OK_200, res->status);
  24450. EXPECT_EQ("c-via-proxy", res->body);
  24451. EXPECT_GE(proxy_hits.load(), 2);
  24452. EXPECT_GE(bypass_hits.load(), 1);
  24453. EXPECT_TRUE(proxy_saw_c_url.load());
  24454. }
  24455. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24456. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24457. // request reconnects to the correct endpoint.
  24458. std::atomic<int> proxy_hits{0};
  24459. std::atomic<int> target_hits{0};
  24460. no_proxy_test::ScopedServer proxy_mock, target;
  24461. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24462. proxy_hits++;
  24463. res.set_content("via-proxy", "text/plain");
  24464. });
  24465. target.svr().Get(".*", [&](const Request &, Response &res) {
  24466. target_hits++;
  24467. res.set_content("direct", "text/plain");
  24468. });
  24469. proxy_mock.listen();
  24470. target.listen();
  24471. Client cli("public.example", target.port());
  24472. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24473. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24474. cli.set_keep_alive(true);
  24475. auto res1 = cli.Get("/a");
  24476. ASSERT_TRUE(res1);
  24477. EXPECT_EQ("via-proxy", res1->body);
  24478. EXPECT_EQ(1, proxy_hits.load());
  24479. EXPECT_EQ(0, target_hits.load());
  24480. cli.set_no_proxy({"public.example"});
  24481. auto res2 = cli.Get("/b");
  24482. ASSERT_TRUE(res2);
  24483. EXPECT_EQ("direct", res2->body);
  24484. EXPECT_EQ(1, proxy_hits.load());
  24485. EXPECT_EQ(1, target_hits.load());
  24486. }
  24487. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24488. namespace proxy_tunnel_test {
  24489. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24490. class ScopedSSLServer {
  24491. public:
  24492. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24493. port_ = svr_.bind_to_any_port("127.0.0.1");
  24494. }
  24495. ~ScopedSSLServer() {
  24496. svr_.stop();
  24497. if (th_.joinable()) { th_.join(); }
  24498. }
  24499. SSLServer &svr() { return svr_; }
  24500. int port() const { return port_; }
  24501. void listen() {
  24502. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24503. svr_.wait_until_ready();
  24504. }
  24505. private:
  24506. SSLServer svr_;
  24507. std::thread th_;
  24508. int port_ = 0;
  24509. };
  24510. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24511. class ScopedConnectProxy {
  24512. public:
  24513. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24514. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24515. if (listen_fd_ < 0) { return; }
  24516. int yes = 1;
  24517. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24518. sockaddr_in a{};
  24519. a.sin_family = AF_INET;
  24520. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24521. a.sin_port = 0;
  24522. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24523. return;
  24524. }
  24525. socklen_t alen = sizeof(a);
  24526. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24527. 0) {
  24528. return;
  24529. }
  24530. port_ = ntohs(a.sin_port);
  24531. if (::listen(listen_fd_, 1) != 0) { return; }
  24532. th_ = std::thread([this] { run(); });
  24533. }
  24534. ~ScopedConnectProxy() {
  24535. stop_ = true;
  24536. if (listen_fd_ >= 0) {
  24537. ::shutdown(listen_fd_, SHUT_RDWR);
  24538. ::close(listen_fd_);
  24539. }
  24540. if (th_.joinable()) { th_.join(); }
  24541. }
  24542. int port() const { return port_; }
  24543. int connect_hits() const { return connect_hits_.load(); }
  24544. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24545. std::string connect_request() const {
  24546. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24547. return connect_request_;
  24548. }
  24549. private:
  24550. void run() {
  24551. while (!stop_.load()) {
  24552. fd_set rfds;
  24553. FD_ZERO(&rfds);
  24554. FD_SET(listen_fd_, &rfds);
  24555. timeval tv{0, 100 * 1000};
  24556. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24557. if (sel <= 0) { continue; }
  24558. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24559. if (client_fd < 0) { continue; }
  24560. std::string req;
  24561. char buf[2048];
  24562. while (req.find("\r\n\r\n") == std::string::npos) {
  24563. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24564. if (n <= 0) { break; }
  24565. req.append(buf, static_cast<size_t>(n));
  24566. }
  24567. if (req.compare(0, 7, "CONNECT") != 0) {
  24568. ::close(client_fd);
  24569. continue;
  24570. }
  24571. connect_hits_++;
  24572. {
  24573. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24574. connect_request_ = req;
  24575. }
  24576. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24577. ::send(client_fd, ok, std::strlen(ok), 0);
  24578. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24579. sockaddr_in o{};
  24580. o.sin_family = AF_INET;
  24581. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24582. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24583. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24584. 0) {
  24585. ::close(client_fd);
  24586. ::close(origin_fd);
  24587. continue;
  24588. }
  24589. auto forward = [](int from, int to) {
  24590. char b[8192];
  24591. for (;;) {
  24592. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24593. if (n <= 0) { break; }
  24594. ssize_t off = 0;
  24595. while (off < n) {
  24596. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24597. if (s <= 0) {
  24598. off = n;
  24599. break;
  24600. }
  24601. off += s;
  24602. }
  24603. }
  24604. ::shutdown(to, SHUT_WR);
  24605. };
  24606. std::thread t1([&] { forward(client_fd, origin_fd); });
  24607. std::thread t2([&] { forward(origin_fd, client_fd); });
  24608. t1.join();
  24609. t2.join();
  24610. ::close(client_fd);
  24611. ::close(origin_fd);
  24612. }
  24613. }
  24614. int forward_port_ = -1;
  24615. int listen_fd_ = -1;
  24616. int port_ = 0;
  24617. std::thread th_;
  24618. std::atomic<bool> stop_{false};
  24619. std::atomic<int> connect_hits_{0};
  24620. mutable std::mutex connect_request_mutex_;
  24621. std::string connect_request_;
  24622. };
  24623. // Sends one request through the CONNECT proxy to the TLS origin with a
  24624. // credential configured for each hop, and checks that each credential reaches
  24625. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24626. // origin's (every header in origin_headers) on the tunnelled request.
  24627. void CredentialsStayWithTheirHop(
  24628. const std::function<void(SSLClient &)> &set_credentials,
  24629. const std::string &scheme,
  24630. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24631. std::atomic<int> origin_hits{0};
  24632. std::atomic<bool> origin_saw_proxy_authz{false};
  24633. std::atomic<bool> origin_saw_headers{false};
  24634. ScopedSSLServer origin;
  24635. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24636. origin_hits++;
  24637. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24638. origin_saw_headers =
  24639. std::all_of(origin_headers.begin(), origin_headers.end(),
  24640. [&](const std::string &h) { return req.has_header(h); });
  24641. res.set_content("ok", "text/plain");
  24642. });
  24643. origin.listen();
  24644. ScopedConnectProxy proxy(origin.port());
  24645. ASSERT_NE(0, proxy.port());
  24646. // Pinned to 127.0.0.1 for the same reason as the test below.
  24647. SSLClient cli("127.0.0.1", origin.port());
  24648. cli.enable_server_certificate_verification(false);
  24649. cli.set_proxy("127.0.0.1", proxy.port());
  24650. set_credentials(cli);
  24651. auto res = cli.Get("/x");
  24652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24653. EXPECT_EQ(StatusCode::OK_200, res->status);
  24654. EXPECT_EQ(1, origin_hits.load());
  24655. EXPECT_EQ(1, proxy.connect_hits());
  24656. EXPECT_TRUE(origin_saw_headers.load());
  24657. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24658. << "Proxy-Authorization must not be sent inside the tunnel";
  24659. auto connect_req = proxy.connect_request();
  24660. EXPECT_NE(std::string::npos,
  24661. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24662. for (const auto &h : origin_headers) {
  24663. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24664. << h << " must not be sent to the proxy on CONNECT";
  24665. }
  24666. }
  24667. } // namespace proxy_tunnel_test
  24668. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24669. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24670. [](SSLClient &cli) {
  24671. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24672. cli.set_basic_auth("origin-user", "origin-pass");
  24673. },
  24674. "Basic");
  24675. }
  24676. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24677. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24678. [](SSLClient &cli) {
  24679. cli.set_proxy_bearer_token_auth("proxy-token");
  24680. cli.set_bearer_token_auth("origin-token");
  24681. },
  24682. "Bearer");
  24683. }
  24684. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24685. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24686. [](SSLClient &cli) {
  24687. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24688. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24689. {"Cookie", "sid=origin-session"},
  24690. {"X-Api-Key", "origin-key"}});
  24691. },
  24692. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24693. }
  24694. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24695. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24696. // retry; otherwise proxy creds would be sent to the origin.
  24697. std::atomic<int> origin_hits{0};
  24698. std::atomic<bool> origin_saw_proxy_authz{false};
  24699. proxy_tunnel_test::ScopedSSLServer origin;
  24700. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24701. origin_hits++;
  24702. if (req.has_header("Proxy-Authorization")) {
  24703. origin_saw_proxy_authz = true;
  24704. }
  24705. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24706. res.set_header("Proxy-Authenticate",
  24707. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24708. "algorithm=MD5");
  24709. });
  24710. origin.listen();
  24711. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24712. ASSERT_NE(0, proxy.port());
  24713. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24714. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24715. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24716. // and answer with its own status, making this test flaky.
  24717. SSLClient cli("127.0.0.1", origin.port());
  24718. cli.enable_server_certificate_verification(false);
  24719. cli.set_proxy("127.0.0.1", proxy.port());
  24720. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24721. auto res = cli.Get("/x");
  24722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24723. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24724. EXPECT_EQ(1, origin_hits.load());
  24725. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24726. EXPECT_EQ(1, proxy.connect_hits());
  24727. }
  24728. #endif