1
0

test.cc 913 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140
  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, silently dropped)
  396. EXPECT_EQ("", decode_path_component("%uD800"));
  397. }
  398. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  399. // A sign or whitespace inside the two-character escape window must not be
  400. // accepted as a valid percent-encoding; the sequence is passed through
  401. // literally, matching decode_uri_component / decode_path_component.
  402. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  403. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  404. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  405. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  406. // Well-formed escapes still decode.
  407. EXPECT_EQ("-", decode_query_component("%2D", false));
  408. EXPECT_EQ("A", decode_query_component("%41", false));
  409. }
  410. TEST(SanitizeFilenameTest, VariousPatterns) {
  411. // Path traversal
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  414. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  415. // Normal and edge cases
  416. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  417. EXPECT_EQ("filename.txt",
  418. httplib::sanitize_filename("/path/to/filename.txt"));
  419. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  420. EXPECT_EQ("", httplib::sanitize_filename(".."));
  421. EXPECT_EQ("", httplib::sanitize_filename(""));
  422. // Null bytes stripped
  423. EXPECT_EQ("safe.txt",
  424. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  425. // Whitespace-only rejected
  426. EXPECT_EQ("", httplib::sanitize_filename(" "));
  427. }
  428. // Forward declaration (see the base64_encode note below): split builds move the
  429. // definition into httplib.cc, so re-declaring it here lets the test link.
  430. namespace httplib {
  431. namespace detail {
  432. bool is_chunked_transfer_encoding(const Headers &headers);
  433. } // namespace detail
  434. } // namespace httplib
  435. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  436. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  437. auto make = [](std::initializer_list<const char *> lines) {
  438. Headers h;
  439. for (auto te : lines) {
  440. if (te) { h.emplace("Transfer-Encoding", te); }
  441. }
  442. return h;
  443. };
  444. // Sole coding, matched case-insensitively.
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  448. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  452. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  457. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  458. // were received, into one list. Headers preserves that order, so the answer
  459. // is decided by the last coding of the last line and the order the lines
  460. // arrived in is significant.
  461. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  464. // The split can fall anywhere in the list.
  465. EXPECT_TRUE(
  466. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  467. EXPECT_FALSE(
  468. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  469. // A trailing line naming no coding leaves the list ending in nothing, so it
  470. // must not inherit the chunked from the line before it.
  471. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  472. }
  473. // Forward declarations (see the base64_encode note below).
  474. namespace httplib {
  475. namespace detail {
  476. bool parse_status_line(const char *line, std::string &version, int &status,
  477. std::string &reason);
  478. std::string file_extension(const std::string &path);
  479. } // namespace detail
  480. } // namespace httplib
  481. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  482. struct {
  483. const char *line;
  484. const char *version;
  485. int status;
  486. const char *reason;
  487. } cases[] = {
  488. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  489. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  490. // The reason phrase may be empty, or left out along with its space.
  491. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  492. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  493. };
  494. for (const auto &c : cases) {
  495. std::string version;
  496. int status = 0;
  497. std::string reason = "unset";
  498. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  499. << c.line;
  500. EXPECT_EQ(c.version, version);
  501. EXPECT_EQ(c.status, status);
  502. EXPECT_EQ(c.reason, reason);
  503. }
  504. }
  505. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  506. const char *lines[] = {
  507. "HTTP/2 200 OK\r\n",
  508. "HTTP/1.2 200 OK\r\n",
  509. "HTTP/1.1 20 OK\r\n",
  510. "HTTP/1.1 2000 OK\r\n",
  511. "HTTP/1.1 2x0 OK\r\n",
  512. "HTTP/1.1 200 OK\r\n",
  513. "HTTP/1.1 200OK\r\n",
  514. "HTTP/1.1 200 O\rK\r\n",
  515. "HTTP/1.1 200 OK",
  516. "HTTP/1.1 200 OK\r\nX",
  517. "",
  518. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  519. "HTTP/1.1 200 OK\n",
  520. #endif
  521. };
  522. for (auto line : lines) {
  523. std::string version;
  524. int status = 0;
  525. std::string reason;
  526. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  527. << line;
  528. }
  529. }
  530. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  531. // Long enough to overflow the stack when matched with std::regex.
  532. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  533. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  538. EXPECT_EQ(200, status);
  539. EXPECT_EQ(long_reason, reason);
  540. }
  541. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  542. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  543. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  544. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  545. EXPECT_EQ("", detail::file_extension("noext"));
  546. EXPECT_EQ("", detail::file_extension("a."));
  547. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  548. EXPECT_EQ("", detail::file_extension("a.b-c"));
  549. // Long enough to overflow the stack when matched with std::regex.
  550. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  551. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  552. }
  553. // Forward declaration: in split builds split.py strips `inline` and moves the
  554. // definition into httplib.cc, so detail::base64_encode is not visible from the
  555. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  556. // in both header-only and split builds.
  557. namespace httplib {
  558. namespace detail {
  559. std::string base64_encode(const std::string &in);
  560. } // namespace detail
  561. } // namespace httplib
  562. TEST(Base64EncodeTest, KnownAnswers) {
  563. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  564. // where the accumulator's top bit is already set before the next shift.
  565. EXPECT_EQ("", detail::base64_encode(""));
  566. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  567. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  568. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  569. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  570. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  571. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  572. // High bytes keep the top bit set across several rounds.
  573. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  574. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  575. }
  576. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  577. string unescapedCharacters = "-_.!~*'()";
  578. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  579. }
  580. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  581. string reservedCharacters = ";,/?:@&=+$";
  582. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  583. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  584. }
  585. TEST(ClientQueryOrder, PreserveOrder) {
  586. // This test reproduces Issue #2259: client may reorder query parameters
  587. // when sending a GET request. The expected behavior is that the client
  588. // preserves the original query string order when the caller supplied it
  589. // as part of the path.
  590. Server svr;
  591. svr.Get("/", [&](const Request &req, Response &res) {
  592. // Echo back the raw target so the test can assert ordering
  593. res.set_content(req.target, "text/plain");
  594. });
  595. std::thread t{[&] { svr.listen(HOST, PORT); }};
  596. auto se = detail::scope_exit([&] {
  597. svr.stop();
  598. t.join();
  599. ASSERT_FALSE(svr.is_running());
  600. });
  601. svr.wait_until_ready();
  602. Client cli(HOST, PORT);
  603. ASSERT_TRUE(cli.is_valid());
  604. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  605. auto res = cli.Get(original);
  606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  607. // Expect the echoed target to exactly match the original path (order
  608. // preserved)
  609. EXPECT_EQ(res->body, original);
  610. }
  611. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  612. string chineseCharacters = U8("中国語");
  613. string russianCharacters = U8("дом");
  614. string brazilianCharacters = U8("óculos");
  615. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  616. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  617. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  618. "%D0%B4%D0%BE%D0%BC");
  619. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  620. }
  621. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  622. string unescapedCharacters = "-_.!~*'()";
  623. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  624. }
  625. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  626. string reservedCharacters = ";,/?:@&=+$";
  627. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  628. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  629. }
  630. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  631. string chineseCharacters = U8("中国語");
  632. string russianCharacters = U8("дом");
  633. string brazilianCharacters = U8("óculos");
  634. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  635. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  636. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  637. "%D0%B4%D0%BE%D0%BC");
  638. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  639. }
  640. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  641. // Issue #2082 use case: encoding path component with ampersand
  642. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  643. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  644. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  645. }
  646. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  647. string unescapedCharacters = "-_.!~*'()";
  648. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  649. }
  650. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  651. string reservedCharacters = ";,/?:@&=+$#";
  652. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  653. }
  654. TEST(EncodeUriTest, TestUTF8Characters) {
  655. string chineseCharacters = U8("中国語");
  656. string russianCharacters = U8("дом");
  657. string brazilianCharacters = U8("óculos");
  658. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  659. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  660. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  661. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  662. }
  663. TEST(EncodeUriTest, TestCompleteUri) {
  664. string uri =
  665. "https://example.com/path/to/resource?query=value&param=test#fragment";
  666. EXPECT_EQ(
  667. httplib::encode_uri(uri),
  668. "https://example.com/path/to/resource?query=value&param=test#fragment");
  669. }
  670. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  671. string uri =
  672. "https://example.com/path with spaces/file name.html?q=hello world";
  673. EXPECT_EQ(httplib::encode_uri(uri),
  674. "https://example.com/path%20with%20spaces/"
  675. "file%20name.html?q=hello%20world");
  676. }
  677. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  678. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  679. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  680. }
  681. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  682. string unescapedCharacters = "-_.!~*'()";
  683. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  684. }
  685. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  686. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  687. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  688. string encodedBrazilian = "%C3%B3culos";
  689. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  690. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  691. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  692. }
  693. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  694. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  695. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  696. "Piri Tommy Villiers - on & on");
  697. }
  698. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  699. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  700. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  701. }
  702. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  703. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  704. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  705. }
  706. TEST(DecodeUriTest, TestUTF8Characters) {
  707. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  708. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  709. string encodedBrazilian = "%C3%B3culos";
  710. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  711. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  712. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  713. }
  714. TEST(DecodeUriTest, TestCompleteUri) {
  715. string encodedUri = "https://example.com/path%20with%20spaces/"
  716. "file%20name.html?q=hello%20world";
  717. EXPECT_EQ(
  718. httplib::decode_uri(encodedUri),
  719. "https://example.com/path with spaces/file name.html?q=hello world");
  720. }
  721. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  722. string original =
  723. "https://example.com/path with spaces/file name.html?q=hello world";
  724. string encoded = httplib::encode_uri(original);
  725. string decoded = httplib::decode_uri(encoded);
  726. EXPECT_EQ(decoded, original);
  727. }
  728. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  729. // decode_uri is the inverse of encode_uri: an escaped reserved character
  730. // stays encoded so it is not promoted into a real delimiter, while
  731. // non-reserved escapes still decode (like JS decodeURI).
  732. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  733. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  734. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  735. "%3F%3A%40%26%3D%2B%24%2C%3B");
  736. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  737. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  738. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  739. "http://example.com/a%2Fb");
  740. // decode_uri_component still decodes the reserved character.
  741. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  742. }
  743. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  744. string original = "Piri Tommy Villiers - on & on";
  745. string encoded = httplib::encode_uri_component(original);
  746. string decoded = httplib::decode_uri_component(encoded);
  747. EXPECT_EQ(decoded, original);
  748. }
  749. TEST(TrimTests, TrimStringTests) {
  750. EXPECT_EQ("abc", detail::trim_copy("abc"));
  751. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  752. EXPECT_TRUE(detail::trim_copy("").empty());
  753. }
  754. TEST(AsciiTest, LocaleIndependentClassification) {
  755. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  756. // which consult the global C locale: std::isalnum(0xC5) can return true
  757. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  758. // helpers must classify every byte by the ASCII grammar alone.
  759. for (int i = 0; i < 256; i++) {
  760. auto c = static_cast<char>(i);
  761. auto is_digit = i >= '0' && i <= '9';
  762. auto is_upper = i >= 'A' && i <= 'Z';
  763. auto is_lower = i >= 'a' && i <= 'z';
  764. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  765. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  766. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  767. << "byte " << i;
  768. }
  769. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  770. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  771. // Non-ASCII bytes must be percent-encoded, never passed through as
  772. // alphanumeric.
  773. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  774. }
  775. TEST(FromCharsTest, Double) {
  776. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  777. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  778. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  779. auto parse = [](const std::string &s, double &v) {
  780. return detail::from_chars(s.data(), s.data() + s.size(), v);
  781. };
  782. double v = -1.0;
  783. // Representative quality values.
  784. EXPECT_EQ(parse("0", v).ec, std::errc{});
  785. EXPECT_DOUBLE_EQ(v, 0.0);
  786. EXPECT_EQ(parse("1", v).ec, std::errc{});
  787. EXPECT_DOUBLE_EQ(v, 1.0);
  788. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  789. EXPECT_DOUBLE_EQ(v, 0.8);
  790. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  791. EXPECT_DOUBLE_EQ(v, 0.001);
  792. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  793. EXPECT_DOUBLE_EQ(v, 1.0);
  794. // A missing integer or fractional part is tolerated.
  795. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  796. EXPECT_DOUBLE_EQ(v, 0.5);
  797. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  798. EXPECT_DOUBLE_EQ(v, 5.0);
  799. // Values outside [0, 1] still parse; the caller range-checks them.
  800. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  801. EXPECT_DOUBLE_EQ(v, 123.456);
  802. // Stops at the first byte that is not part of the number and reports where.
  803. std::string trailing = "0.9, text/html";
  804. auto r = parse(trailing, v);
  805. EXPECT_EQ(r.ec, std::errc{});
  806. EXPECT_DOUBLE_EQ(v, 0.9);
  807. EXPECT_EQ(*r.ptr, ',');
  808. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  809. // outright, and an 'e'/'E' simply ends the number.
  810. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  811. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  812. std::string exp_input = "1.5e3";
  813. r = parse(exp_input, v);
  814. EXPECT_EQ(r.ec, std::errc{});
  815. EXPECT_DOUBLE_EQ(v, 1.5);
  816. EXPECT_EQ(*r.ptr, 'e');
  817. // Invalid inputs.
  818. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  819. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  820. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  821. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  822. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  823. // Pathological but well-formed inputs must stay bounded (no overflow, no
  824. // out-of-bounds table access) and stay within [0, 1] for the caller.
  825. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  826. std::errc{});
  827. EXPECT_DOUBLE_EQ(v, 0.0);
  828. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  829. std::errc{});
  830. EXPECT_GE(v, 0.0);
  831. EXPECT_LE(v, 1.0);
  832. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  833. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  834. }
  835. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  836. // Simple case without quality values
  837. std::vector<std::string> result1;
  838. EXPECT_TRUE(detail::parse_accept_header(
  839. "text/html,application/json,text/plain", result1));
  840. EXPECT_EQ(result1.size(), 3U);
  841. EXPECT_EQ(result1[0], "text/html");
  842. EXPECT_EQ(result1[1], "application/json");
  843. EXPECT_EQ(result1[2], "text/plain");
  844. // With quality values
  845. std::vector<std::string> result2;
  846. EXPECT_TRUE(detail::parse_accept_header(
  847. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  848. EXPECT_EQ(result2.size(), 3U);
  849. EXPECT_EQ(result2[0], "application/json"); // highest q value
  850. EXPECT_EQ(result2[1], "text/html");
  851. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  852. }
  853. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  854. // Mixed with and without quality values
  855. std::vector<std::string> result;
  856. EXPECT_TRUE(detail::parse_accept_header(
  857. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  858. EXPECT_EQ(result.size(), 3U);
  859. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  860. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  861. EXPECT_EQ(result[2], "application/json"); // q=0.5
  862. }
  863. TEST(ParseAcceptHeaderTest, EdgeCases) {
  864. // Empty header
  865. std::vector<std::string> empty_result;
  866. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  867. EXPECT_TRUE(empty_result.empty());
  868. // Single type
  869. std::vector<std::string> single_result;
  870. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  871. EXPECT_EQ(single_result.size(), 1U);
  872. EXPECT_EQ(single_result[0], "application/json");
  873. // Wildcard types
  874. std::vector<std::string> wildcard_result;
  875. EXPECT_TRUE(detail::parse_accept_header(
  876. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  877. EXPECT_EQ(wildcard_result.size(), 3U);
  878. EXPECT_EQ(wildcard_result[0], "application/json");
  879. EXPECT_EQ(wildcard_result[1], "text/*");
  880. EXPECT_EQ(wildcard_result[2], "*/*");
  881. }
  882. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  883. // Common browser Accept header
  884. std::vector<std::string> browser_result;
  885. EXPECT_TRUE(
  886. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  887. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  888. browser_result));
  889. EXPECT_EQ(browser_result.size(), 6U);
  890. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  891. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  892. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  893. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  894. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  895. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  896. // API client header
  897. std::vector<std::string> api_result;
  898. EXPECT_TRUE(detail::parse_accept_header(
  899. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  900. api_result));
  901. EXPECT_EQ(api_result.size(), 3U);
  902. EXPECT_EQ(api_result[0], "application/json");
  903. EXPECT_EQ(api_result[1], "application/xml");
  904. EXPECT_EQ(api_result[2], "text/plain");
  905. }
  906. TEST(ParseAcceptHeaderTest, SpecialCases) {
  907. // Quality value with 3 decimal places
  908. std::vector<std::string> decimal_result;
  909. EXPECT_TRUE(detail::parse_accept_header(
  910. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  911. EXPECT_EQ(decimal_result.size(), 2U);
  912. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  913. EXPECT_EQ(decimal_result[1], "text/html");
  914. // Zero quality (should still be included but with lowest priority)
  915. std::vector<std::string> zero_q_result;
  916. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  917. zero_q_result));
  918. EXPECT_EQ(zero_q_result.size(), 2U);
  919. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  920. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  921. // No spaces around commas
  922. std::vector<std::string> no_space_result;
  923. EXPECT_TRUE(detail::parse_accept_header(
  924. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  925. no_space_result));
  926. EXPECT_EQ(no_space_result.size(), 3U);
  927. EXPECT_EQ(no_space_result[0], "text/html");
  928. EXPECT_EQ(no_space_result[1], "application/json");
  929. EXPECT_EQ(no_space_result[2], "text/plain");
  930. }
  931. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  932. // Quality values always use '.' as the decimal separator, so parsing must
  933. // not depend on the process locale. An embedding application may have
  934. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  935. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  936. std::string saved = cur ? cur : "C";
  937. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  938. "fr_FR.UTF-8"};
  939. bool switched = false;
  940. for (const auto loc : comma_locales) {
  941. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  942. std::localeconv()->decimal_point[0] == ',') {
  943. switched = true;
  944. break;
  945. }
  946. }
  947. if (!switched) {
  948. std::setlocale(LC_NUMERIC, saved.c_str());
  949. GTEST_SKIP() << "no comma-decimal locale available on this host";
  950. }
  951. // The higher-weighted type appears later in the list, so a correct parse
  952. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  953. // sensitive parse reads both weights as 0 and leaves the original order.
  954. std::vector<std::string> result;
  955. EXPECT_TRUE(detail::parse_accept_header(
  956. "application/json;q=0.1,text/html;q=0.9", result));
  957. ASSERT_EQ(result.size(), 2U);
  958. EXPECT_EQ(result[0], "text/html");
  959. EXPECT_EQ(result[1], "application/json");
  960. std::setlocale(LC_NUMERIC, saved.c_str());
  961. }
  962. TEST(ParseAcceptHeaderTest, InvalidCases) {
  963. std::vector<std::string> result;
  964. // Invalid quality value (> 1.0)
  965. EXPECT_FALSE(
  966. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  967. // Invalid quality value (< 0.0)
  968. EXPECT_FALSE(
  969. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  970. // Invalid quality value (not a number)
  971. EXPECT_FALSE(detail::parse_accept_header(
  972. "text/html;q=invalid,application/json", result));
  973. // A valid numeric prefix does not make the entire quality value valid.
  974. EXPECT_FALSE(detail::parse_accept_header(
  975. "text/html;q=0.5junk,application/json", result));
  976. // Empty quality value
  977. EXPECT_FALSE(
  978. detail::parse_accept_header("text/html;q=,application/json", result));
  979. // Invalid media type format (no slash and not wildcard)
  980. EXPECT_FALSE(
  981. detail::parse_accept_header("invalidtype,application/json", result));
  982. // Valid cases should still work
  983. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  984. EXPECT_EQ(result.size(), 1U);
  985. EXPECT_EQ(result[0], "*/*");
  986. EXPECT_TRUE(detail::parse_accept_header("*", result));
  987. EXPECT_EQ(result.size(), 1U);
  988. EXPECT_EQ(result[0], "*");
  989. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  990. EXPECT_EQ(result.size(), 1U);
  991. EXPECT_EQ(result[0], "text/*");
  992. }
  993. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  994. // elements, so a leading, trailing or doubled comma is a legal Accept value
  995. // and must not be answered with 400 Bad Request.
  996. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  997. struct {
  998. const char *value;
  999. std::vector<std::string> expected;
  1000. } cases[] = {
  1001. {",application/json", {"application/json"}},
  1002. {"text/html,", {"text/html"}},
  1003. {"text/html,,*/*", {"text/html", "*/*"}},
  1004. // An empty element may be spelled with whitespace in it
  1005. {"text/html, , application/json", {"text/html", "application/json"}},
  1006. // Nothing but empty elements is an empty list, which means the same
  1007. // thing as no Accept header at all
  1008. {",,,", {}},
  1009. // Quality values still apply across ignored empty elements
  1010. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1011. };
  1012. for (const auto &c : cases) {
  1013. std::vector<std::string> result;
  1014. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1015. << "value: " << c.value;
  1016. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1017. }
  1018. // An invalid entry is still rejected when empty elements surround it
  1019. std::vector<std::string> result;
  1020. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1021. }
  1022. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1023. // or ';' inside one does not end the list element or the parameter. Section
  1024. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1025. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1026. struct {
  1027. const char *value;
  1028. std::vector<std::string> expected;
  1029. } cases[] = {
  1030. {"text/html;profile=\"a,b\",application/json",
  1031. {"text/html", "application/json"}},
  1032. // A "q=" inside a quoted value is not the weight
  1033. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1034. {"text/html", "application/json"}},
  1035. // The weight after a quoted value still applies
  1036. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1037. {"application/json", "text/html"}},
  1038. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1039. {"application/json", "text/html"}},
  1040. {"text/html;profile=\"a\\\"b\",application/json",
  1041. {"text/html", "application/json"}},
  1042. // An escaped backslash does not escape the '"' after it
  1043. {"text/html;profile=\"a\\\\\",application/json",
  1044. {"text/html", "application/json"}},
  1045. };
  1046. for (const auto &c : cases) {
  1047. std::vector<std::string> result;
  1048. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1049. << "value: " << c.value;
  1050. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1051. }
  1052. }
  1053. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1054. Server svr;
  1055. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1056. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1057. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1058. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1059. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1060. res.set_content("ok", "text/plain");
  1061. });
  1062. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1063. EXPECT_TRUE(false);
  1064. res.set_content("bad request", "text/plain");
  1065. });
  1066. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1067. auto se = detail::scope_exit([&] {
  1068. svr.stop();
  1069. listen_thread.join();
  1070. ASSERT_FALSE(svr.is_running());
  1071. });
  1072. svr.wait_until_ready();
  1073. Client cli("localhost", PORT);
  1074. {
  1075. auto res = cli.Get(
  1076. "/accept_ok",
  1077. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1079. EXPECT_EQ(StatusCode::OK_200, res->status);
  1080. }
  1081. {
  1082. auto res = cli.Get("/accept_bad_request",
  1083. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1085. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1086. }
  1087. }
  1088. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1089. Server svr;
  1090. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1091. res.set_content("ok", "text/plain");
  1092. });
  1093. std::atomic<int> start_count{0};
  1094. std::atomic<bool> running_when_called{false};
  1095. svr.set_start_handler([&]() {
  1096. running_when_called = svr.is_running();
  1097. start_count++;
  1098. });
  1099. auto port = svr.bind_to_any_port(HOST);
  1100. std::thread t([&]() { svr.listen_after_bind(); });
  1101. auto se = detail::scope_exit([&] {
  1102. svr.stop();
  1103. t.join();
  1104. ASSERT_FALSE(svr.is_running());
  1105. });
  1106. svr.wait_until_ready();
  1107. // A successful request proves the accept loop is running, which the start
  1108. // handler precedes; so by now the handler must have run exactly once.
  1109. Client cli(HOST, port);
  1110. cli.set_connection_timeout(std::chrono::seconds(5));
  1111. auto res = cli.Get("/");
  1112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1113. EXPECT_EQ(StatusCode::OK_200, res->status);
  1114. EXPECT_EQ(1, start_count.load());
  1115. EXPECT_TRUE(running_when_called.load());
  1116. }
  1117. TEST(DivideTest, DivideStringTests) {
  1118. auto divide = [](const std::string &str, char d) {
  1119. std::string lhs;
  1120. std::string rhs;
  1121. detail::divide(str, d,
  1122. [&](const char *lhs_data, std::size_t lhs_size,
  1123. const char *rhs_data, std::size_t rhs_size) {
  1124. lhs.assign(lhs_data, lhs_size);
  1125. rhs.assign(rhs_data, rhs_size);
  1126. });
  1127. return std::make_pair(std::move(lhs), std::move(rhs));
  1128. };
  1129. {
  1130. const auto res = divide("", '=');
  1131. EXPECT_EQ(res.first, "");
  1132. EXPECT_EQ(res.second, "");
  1133. }
  1134. {
  1135. const auto res = divide("=", '=');
  1136. EXPECT_EQ(res.first, "");
  1137. EXPECT_EQ(res.second, "");
  1138. }
  1139. {
  1140. const auto res = divide(" ", '=');
  1141. EXPECT_EQ(res.first, " ");
  1142. EXPECT_EQ(res.second, "");
  1143. }
  1144. {
  1145. const auto res = divide("a", '=');
  1146. EXPECT_EQ(res.first, "a");
  1147. EXPECT_EQ(res.second, "");
  1148. }
  1149. {
  1150. const auto res = divide("a=", '=');
  1151. EXPECT_EQ(res.first, "a");
  1152. EXPECT_EQ(res.second, "");
  1153. }
  1154. {
  1155. const auto res = divide("=b", '=');
  1156. EXPECT_EQ(res.first, "");
  1157. EXPECT_EQ(res.second, "b");
  1158. }
  1159. {
  1160. const auto res = divide("a=b", '=');
  1161. EXPECT_EQ(res.first, "a");
  1162. EXPECT_EQ(res.second, "b");
  1163. }
  1164. {
  1165. const auto res = divide("a=b=", '=');
  1166. EXPECT_EQ(res.first, "a");
  1167. EXPECT_EQ(res.second, "b=");
  1168. }
  1169. {
  1170. const auto res = divide("a=b=c", '=');
  1171. EXPECT_EQ(res.first, "a");
  1172. EXPECT_EQ(res.second, "b=c");
  1173. }
  1174. }
  1175. TEST(SplitTest, ParseQueryString) {
  1176. string s = "key1=val1&key2=val2&key3=val3";
  1177. Params dic;
  1178. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1179. [&](const char *b, const char *e) {
  1180. string key, val;
  1181. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1182. if (key.empty()) {
  1183. key.assign(b2, e2);
  1184. } else {
  1185. val.assign(b2, e2);
  1186. }
  1187. });
  1188. dic.emplace(key, val);
  1189. });
  1190. EXPECT_EQ("val1", dic.find("key1")->second);
  1191. EXPECT_EQ("val2", dic.find("key2")->second);
  1192. EXPECT_EQ("val3", dic.find("key3")->second);
  1193. }
  1194. TEST(SplitTest, ParseInvalidQueryTests) {
  1195. {
  1196. string s = " ";
  1197. Params dict;
  1198. detail::parse_query_text(s, dict);
  1199. EXPECT_TRUE(dict.empty());
  1200. }
  1201. {
  1202. string s = " = =";
  1203. Params dict;
  1204. detail::parse_query_text(s, dict);
  1205. EXPECT_TRUE(dict.empty());
  1206. }
  1207. }
  1208. TEST(ParseQueryTest, ParseQueryString) {
  1209. {
  1210. std::string s = "key1=val1&key2=val2&key3=val3";
  1211. Params dic;
  1212. detail::parse_query_text(s, dic);
  1213. EXPECT_EQ("val1", dic.find("key1")->second);
  1214. EXPECT_EQ("val2", dic.find("key2")->second);
  1215. EXPECT_EQ("val3", dic.find("key3")->second);
  1216. }
  1217. {
  1218. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1219. Params dic;
  1220. detail::parse_query_text(s, dic);
  1221. EXPECT_EQ("", dic.find("key1")->second);
  1222. EXPECT_EQ("val1", dic.find("key2")->second);
  1223. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1224. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1225. }
  1226. }
  1227. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1228. Params dic;
  1229. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1230. dic.emplace("key1", "val1");
  1231. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1232. dic.emplace("key2", "val2");
  1233. dic.emplace("key3", "val3");
  1234. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1235. }
  1236. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1237. Params params;
  1238. params.emplace("a", "1");
  1239. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1240. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1241. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1242. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1243. // Long enough to overflow the stack when matched with std::regex.
  1244. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1245. EXPECT_EQ("/p?" + long_query + "&a=1",
  1246. append_query_params("/p?" + long_query, params));
  1247. }
  1248. // Joins every entry of a Headers or Params into "key=value " so a whole
  1249. // traversal can be compared in one assertion. Both are instantiations of the
  1250. // same insertion-ordered container, so one helper serves both.
  1251. template <typename Map> static std::string entries_to_string(const Map &m) {
  1252. std::string s;
  1253. for (const auto &entry : m) {
  1254. s += entry.first + "=" + entry.second + " ";
  1255. }
  1256. return s;
  1257. }
  1258. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1259. // Params used to be a std::multimap, which sorted by name and handed the
  1260. // caller's query back alphabetised. A client signing its query string could
  1261. // not reproduce the order it asked for.
  1262. Params dic;
  1263. dic.emplace("zulu", "1");
  1264. dic.emplace("alpha", "2");
  1265. dic.emplace("mike", "3");
  1266. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1267. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1268. }
  1269. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1270. Params dic;
  1271. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1272. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1273. }
  1274. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1275. Request req;
  1276. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1277. req.params);
  1278. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1279. EXPECT_EQ("first", req.get_param_value("tag"));
  1280. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1281. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1282. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1283. EXPECT_EQ("", req.get_param_value("tag", 3));
  1284. }
  1285. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1286. // Params shares its container with Headers, which matches field names
  1287. // case-insensitively. Parameter names must not pick that up.
  1288. Params dic;
  1289. dic.emplace("Key", "upper");
  1290. dic.emplace("key", "lower");
  1291. EXPECT_EQ(2U, dic.size());
  1292. EXPECT_EQ(1U, dic.count("Key"));
  1293. EXPECT_EQ(1U, dic.count("key"));
  1294. EXPECT_EQ("upper", dic.find("Key")->second);
  1295. EXPECT_EQ("lower", dic.find("key")->second);
  1296. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1297. }
  1298. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1299. Server svr;
  1300. std::string order;
  1301. svr.Get("/order", [&](const Request &req, Response &res) {
  1302. order = entries_to_string(req.params);
  1303. res.set_content("ok", "text/plain");
  1304. });
  1305. auto port = svr.bind_to_any_port(HOST);
  1306. thread t = thread([&] { svr.listen_after_bind(); });
  1307. auto se = detail::scope_exit([&] {
  1308. svr.stop();
  1309. t.join();
  1310. ASSERT_FALSE(svr.is_running());
  1311. });
  1312. svr.wait_until_ready();
  1313. Client cli(HOST, port);
  1314. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1315. ASSERT_TRUE(res);
  1316. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1317. }
  1318. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1319. Server svr;
  1320. std::string field_order, file_order;
  1321. svr.Post("/order", [&](const Request &req, Response &res) {
  1322. for (const auto &field : req.form.fields) {
  1323. field_order += field.first + "=" + field.second.content + " ";
  1324. }
  1325. for (const auto &file : req.form.files) {
  1326. file_order += file.first + "=" + file.second.filename + " ";
  1327. }
  1328. res.set_content("ok", "text/plain");
  1329. });
  1330. auto port = svr.bind_to_any_port(HOST);
  1331. thread t = thread([&] { svr.listen_after_bind(); });
  1332. auto se = detail::scope_exit([&] {
  1333. svr.stop();
  1334. t.join();
  1335. ASSERT_FALSE(svr.is_running());
  1336. });
  1337. svr.wait_until_ready();
  1338. UploadFormDataItems items = {
  1339. {"zulu", "1", "", ""},
  1340. {"alpha", "2", "", ""},
  1341. {"mike", "3", "", ""},
  1342. {"zebra", "z", "z.txt", "text/plain"},
  1343. {"apple", "a", "a.txt", "text/plain"},
  1344. };
  1345. Client cli(HOST, port);
  1346. auto res = cli.Post("/order", items);
  1347. ASSERT_TRUE(res);
  1348. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1349. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1350. }
  1351. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1352. Server svr;
  1353. std::vector<std::string> values;
  1354. std::string first, second, out_of_range, order;
  1355. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1356. values = req.form.get_fields("tag");
  1357. first = req.form.get_field("tag", 0);
  1358. second = req.form.get_field("tag", 1);
  1359. out_of_range = req.form.get_field("tag", 2);
  1360. for (const auto &field : req.form.fields) {
  1361. order += field.first + "=" + field.second.content + " ";
  1362. }
  1363. res.set_content("ok", "text/plain");
  1364. });
  1365. auto port = svr.bind_to_any_port(HOST);
  1366. thread t = thread([&] { svr.listen_after_bind(); });
  1367. auto se = detail::scope_exit([&] {
  1368. svr.stop();
  1369. t.join();
  1370. ASSERT_FALSE(svr.is_running());
  1371. });
  1372. svr.wait_until_ready();
  1373. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1374. // not adjacent in the container.
  1375. UploadFormDataItems items = {
  1376. {"tag", "first", "", ""},
  1377. {"other", "x", "", ""},
  1378. {"tag", "second", "", ""},
  1379. };
  1380. Client cli(HOST, port);
  1381. auto res = cli.Post("/repeated", items);
  1382. ASSERT_TRUE(res);
  1383. ASSERT_EQ(2U, values.size());
  1384. EXPECT_EQ("first", values[0]);
  1385. EXPECT_EQ("second", values[1]);
  1386. EXPECT_EQ("first", first);
  1387. EXPECT_EQ("second", second);
  1388. // std::multimap already kept entries sharing a name in insertion order, so
  1389. // everything above passes without this change too. The whole traversal is
  1390. // what tells the two apart: sorting by name would hoist "other" to the front
  1391. // and the two "tag" parts would end up adjacent.
  1392. EXPECT_EQ("tag=first other=x tag=second ", order);
  1393. // Advancing past the last entry of a name used to run off the container;
  1394. // the container's saturating increment makes it return the default instead.
  1395. EXPECT_EQ("", out_of_range);
  1396. }
  1397. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1398. // Server::read_content() keeps a FormFields::iterator alive across the
  1399. // content callbacks that fill the part it points at. The container is
  1400. // vector-backed, so a later emplace can reallocate and invalidate an older
  1401. // iterator; 64 parts grow the vector through seven reallocations, which
  1402. // checks that every part's content still lands in its own entry.
  1403. const size_t part_count = 64;
  1404. // One formula for both the parts sent and the values expected back, so the
  1405. // two cannot drift apart.
  1406. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1407. auto content_of = [](size_t i) {
  1408. return std::string(64, static_cast<char>('a' + (i % 26)));
  1409. };
  1410. Server svr;
  1411. std::vector<std::pair<std::string, std::string>> received;
  1412. svr.Post("/many", [&](const Request &req, Response &res) {
  1413. for (const auto &field : req.form.fields) {
  1414. received.emplace_back(field.first, field.second.content);
  1415. }
  1416. res.set_content("ok", "text/plain");
  1417. });
  1418. auto port = svr.bind_to_any_port(HOST);
  1419. thread t = thread([&] { svr.listen_after_bind(); });
  1420. auto se = detail::scope_exit([&] {
  1421. svr.stop();
  1422. t.join();
  1423. ASSERT_FALSE(svr.is_running());
  1424. });
  1425. svr.wait_until_ready();
  1426. UploadFormDataItems items;
  1427. for (size_t i = 0; i < part_count; i++) {
  1428. items.push_back({name_of(i), content_of(i), "", ""});
  1429. }
  1430. Client cli(HOST, port);
  1431. auto res = cli.Post("/many", items);
  1432. ASSERT_TRUE(res);
  1433. ASSERT_EQ(part_count, received.size());
  1434. for (size_t i = 0; i < part_count; i++) {
  1435. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1436. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1437. }
  1438. }
  1439. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1440. string content_type = "multipart/form-data; boundary=something";
  1441. string boundary;
  1442. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1443. EXPECT_TRUE(ret);
  1444. EXPECT_EQ(boundary, "something");
  1445. }
  1446. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1447. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1448. string boundary;
  1449. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1450. EXPECT_TRUE(ret);
  1451. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1452. }
  1453. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1454. string content_type =
  1455. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1456. string boundary;
  1457. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1458. EXPECT_TRUE(ret);
  1459. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1460. }
  1461. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1462. string content_type =
  1463. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1464. string boundary;
  1465. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1466. EXPECT_TRUE(ret);
  1467. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1468. }
  1469. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1470. const string boundary(70, 'a');
  1471. string content_type = "multipart/form-data; boundary=" + boundary;
  1472. string parsed;
  1473. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1474. EXPECT_TRUE(ret);
  1475. EXPECT_EQ(parsed, boundary);
  1476. }
  1477. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1478. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1479. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1480. string parsed;
  1481. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1482. EXPECT_FALSE(ret);
  1483. }
  1484. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1485. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1486. // is 72 characters on the wire and still valid.
  1487. const string boundary(70, 'a');
  1488. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1489. string parsed;
  1490. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1491. EXPECT_EQ(parsed, boundary);
  1492. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1493. parsed.clear();
  1494. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1495. }
  1496. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1497. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1498. // The parameter parser must not treat that '=' as the key/value separator.
  1499. string content_type =
  1500. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1501. "charset=UTF-8";
  1502. string parsed;
  1503. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1504. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1505. }
  1506. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1507. // A ';' inside the quoted-string is part of the value, not a parameter
  1508. // separator, so it must not truncate the boundary.
  1509. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1510. string parsed;
  1511. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1512. EXPECT_EQ(parsed, "a;b");
  1513. }
  1514. TEST(ParseDispositionParamsTest, QuotedValues) {
  1515. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1516. // ';' and '=' are ordinary characters inside one.
  1517. struct {
  1518. const char *value;
  1519. std::vector<std::pair<const char *, const char *>> expected;
  1520. } cases[] = {
  1521. {"name=\"file1\"; filename=\"a.txt\"",
  1522. {{"name", "file1"}, {"filename", "a.txt"}}},
  1523. // Whitespace around '=' and ';' is still trimmed
  1524. {"name=\"file2\" ;filename = \"a.html\"",
  1525. {{"name", "file2"}, {"filename", "a.html"}}},
  1526. // '=' inside the value used to leave only the text after the last one
  1527. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1528. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1529. {"name=\"x=y\"", {{"name", "x=y"}}},
  1530. // ';' inside the value used to truncate the pair and leave a bogus one
  1531. {"name=\"file3\"; filename=\"a;b.txt\"",
  1532. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1533. // An unquoted value keeps working, and so does filename*
  1534. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1535. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1536. // A parameter with no key is dropped rather than turned into one whose
  1537. // key is the value
  1538. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1539. };
  1540. for (const auto &c : cases) {
  1541. Params params;
  1542. detail::parse_disposition_params(c.value, params);
  1543. for (const auto &kv : c.expected) {
  1544. auto it = params.find(kv.first);
  1545. ASSERT_NE(it, params.end())
  1546. << "value: " << c.value << ", key: " << kv.first;
  1547. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1548. }
  1549. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1550. }
  1551. }
  1552. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1553. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1554. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1555. Server svr;
  1556. std::string field_value, file_name, file_filename;
  1557. bool has_field = false, has_file = false;
  1558. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1559. has_field = req.form.has_field("x=y");
  1560. field_value = req.form.get_field("x=y");
  1561. has_file = req.form.has_file("file1");
  1562. const auto &file = req.form.get_file("file1");
  1563. file_name = file.name;
  1564. file_filename = file.filename;
  1565. res.set_content("ok", "text/plain");
  1566. });
  1567. auto port = svr.bind_to_any_port(HOST);
  1568. thread t = thread([&] { svr.listen_after_bind(); });
  1569. auto se = detail::scope_exit([&] {
  1570. svr.stop();
  1571. t.join();
  1572. ASSERT_FALSE(svr.is_running());
  1573. });
  1574. svr.wait_until_ready();
  1575. UploadFormDataItems items = {
  1576. {"x=y", "field-value", "", ""},
  1577. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1578. };
  1579. Client cli(HOST, port);
  1580. auto res = cli.Post("/quoted", items);
  1581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1582. ASSERT_EQ(StatusCode::OK_200, res->status);
  1583. EXPECT_TRUE(has_field);
  1584. EXPECT_EQ("field-value", field_value);
  1585. EXPECT_TRUE(has_file);
  1586. EXPECT_EQ("file1", file_name);
  1587. EXPECT_EQ("a;b=report.pdf", file_filename);
  1588. }
  1589. TEST(GetHeaderValueTest, DefaultValue) {
  1590. Headers headers = {{"Dummy", "Dummy"}};
  1591. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1592. EXPECT_STREQ("text/plain", val);
  1593. }
  1594. TEST(GetHeaderValueTest, DefaultValueInt) {
  1595. Headers headers = {{"Dummy", "Dummy"}};
  1596. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1597. EXPECT_EQ(100ull, val);
  1598. }
  1599. TEST(GetHeaderValueTest, RegularValue) {
  1600. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1601. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1602. EXPECT_STREQ("text/html", val);
  1603. }
  1604. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1605. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1606. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1607. EXPECT_STREQ("text/html", val);
  1608. }
  1609. TEST(GetHeaderValueTest, SetContent) {
  1610. Response res;
  1611. res.set_content("html", "text/html");
  1612. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1613. res.set_content("text", "text/plain");
  1614. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1615. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1616. }
  1617. TEST(GetHeaderValueTest, RegularValueInt) {
  1618. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1619. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1620. EXPECT_EQ(100ull, val);
  1621. }
  1622. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1623. Headers headers = {{"Content-Length", "x"}};
  1624. auto is_invalid_value = false;
  1625. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1626. is_invalid_value);
  1627. EXPECT_EQ(0ull, val);
  1628. EXPECT_TRUE(is_invalid_value);
  1629. }
  1630. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1631. // An all-digit value that overflows size_t must be reported as invalid, not
  1632. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1633. // a large length to a small one on 32-bit builds, leaving the framing length
  1634. // wrong while is_invalid_value stayed false.
  1635. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1636. auto is_invalid_value = false;
  1637. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1638. is_invalid_value);
  1639. EXPECT_TRUE(is_invalid_value);
  1640. // A well-formed length is unaffected.
  1641. Headers ok = {{"Content-Length", "1234"}};
  1642. is_invalid_value = false;
  1643. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1644. is_invalid_value);
  1645. EXPECT_EQ(1234ull, val);
  1646. EXPECT_FALSE(is_invalid_value);
  1647. }
  1648. TEST(GetHeaderValueTest, Range) {
  1649. {
  1650. Headers headers = {make_range_header({{1, -1}})};
  1651. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1652. EXPECT_STREQ("bytes=1-", val);
  1653. }
  1654. {
  1655. Headers headers = {make_range_header({{-1, 1}})};
  1656. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1657. EXPECT_STREQ("bytes=-1", val);
  1658. }
  1659. {
  1660. Headers headers = {make_range_header({{1, 10}})};
  1661. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1662. EXPECT_STREQ("bytes=1-10", val);
  1663. }
  1664. {
  1665. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1666. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1667. EXPECT_STREQ("bytes=1-10, 100-", val);
  1668. }
  1669. {
  1670. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1671. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1672. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1673. }
  1674. {
  1675. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1676. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1677. EXPECT_STREQ("bytes=0-0, -1", val);
  1678. }
  1679. }
  1680. TEST(BearerTokenAuthTest, SchemeValidation) {
  1681. // A value shorter than "Bearer " must not throw from the fixed-length
  1682. // substr, and a non-Bearer scheme must not be reported as a token.
  1683. struct {
  1684. const char *value;
  1685. const char *expected;
  1686. } cases[] = {
  1687. {"x", ""},
  1688. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1689. {"Bearer abc123", "abc123"},
  1690. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1691. };
  1692. for (const auto &c : cases) {
  1693. Request req;
  1694. req.set_header("Authorization", c.value);
  1695. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1696. }
  1697. }
  1698. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1699. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1700. // to depend on the standard library (libstdc++ handed back duplicates in
  1701. // reverse insertion order, libc++ in insertion order).
  1702. Request req;
  1703. req.set_header("Accept-Encoding", "gzip");
  1704. req.set_header("Accept-Encoding", "deflate");
  1705. req.set_header("Accept-Encoding", "br");
  1706. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1707. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1708. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1709. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1710. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1711. }
  1712. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1713. Request req;
  1714. req.set_header("X-Test", "only");
  1715. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1716. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1717. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1718. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1719. }
  1720. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1721. Request req;
  1722. req.set_header("X-First", "1");
  1723. req.set_header("X-Test", "2");
  1724. req.params.emplace("first", "1");
  1725. req.params.emplace("test", "2");
  1726. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1727. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1728. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1729. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1730. // The second one is negative when read as a signed value
  1731. const auto max_id = (std::numeric_limits<size_t>::max)();
  1732. for (auto id : {max_id / 2, max_id}) {
  1733. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1734. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1735. EXPECT_EQ("", req.get_param_value("test", id));
  1736. EXPECT_EQ("", req.form.get_field("test", id));
  1737. EXPECT_EQ("", req.form.get_file("test", id).content);
  1738. }
  1739. }
  1740. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1741. Headers headers;
  1742. headers.emplace("Host", "example.com");
  1743. headers.emplace("Accept-Encoding", "gzip");
  1744. headers.emplace("User-Agent", "test");
  1745. headers.emplace("Accept-Encoding", "deflate");
  1746. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1747. "Accept-Encoding=deflate ",
  1748. entries_to_string(headers));
  1749. }
  1750. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1751. Headers headers = {{"Content-Type", "text/html"},
  1752. {"CONTENT-TYPE", "text/xml"}};
  1753. EXPECT_EQ(2U, headers.count("content-type"));
  1754. auto it = headers.find("content-type");
  1755. ASSERT_TRUE(it != headers.end());
  1756. EXPECT_EQ("text/html", it->second);
  1757. }
  1758. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1759. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1760. // drop only those fields and leave everything positioned between them.
  1761. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1762. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1763. auto rng = headers.equal_range("a");
  1764. headers.erase(rng.first, rng.second);
  1765. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1766. }
  1767. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1768. Headers headers = {
  1769. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1770. EXPECT_EQ(3U, headers.erase("A"));
  1771. EXPECT_EQ(0U, headers.count("A"));
  1772. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1773. }
  1774. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1775. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1776. headers.emplace_front("Host", "example.com");
  1777. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1778. entries_to_string(headers));
  1779. }
  1780. TEST(ParseHeaderValueTest, Range) {
  1781. {
  1782. Ranges ranges;
  1783. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1784. EXPECT_TRUE(ret);
  1785. EXPECT_EQ(1u, ranges.size());
  1786. EXPECT_EQ(1u, ranges[0].first);
  1787. EXPECT_EQ(-1, ranges[0].second);
  1788. }
  1789. {
  1790. Ranges ranges;
  1791. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1792. EXPECT_TRUE(ret);
  1793. EXPECT_EQ(1u, ranges.size());
  1794. EXPECT_EQ(-1, ranges[0].first);
  1795. EXPECT_EQ(1u, ranges[0].second);
  1796. }
  1797. {
  1798. Ranges ranges;
  1799. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1800. EXPECT_TRUE(ret);
  1801. EXPECT_EQ(1u, ranges.size());
  1802. EXPECT_EQ(1u, ranges[0].first);
  1803. EXPECT_EQ(10u, ranges[0].second);
  1804. }
  1805. {
  1806. Ranges ranges;
  1807. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1808. EXPECT_FALSE(ret);
  1809. }
  1810. {
  1811. Ranges ranges;
  1812. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1813. EXPECT_TRUE(ret);
  1814. EXPECT_EQ(2u, ranges.size());
  1815. EXPECT_EQ(1u, ranges[0].first);
  1816. EXPECT_EQ(10u, ranges[0].second);
  1817. EXPECT_EQ(100u, ranges[1].first);
  1818. EXPECT_EQ(-1, ranges[1].second);
  1819. }
  1820. {
  1821. Ranges ranges;
  1822. auto ret =
  1823. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1824. EXPECT_TRUE(ret);
  1825. EXPECT_EQ(3u, ranges.size());
  1826. EXPECT_EQ(1u, ranges[0].first);
  1827. EXPECT_EQ(10u, ranges[0].second);
  1828. EXPECT_EQ(100u, ranges[1].first);
  1829. EXPECT_EQ(200u, ranges[1].second);
  1830. EXPECT_EQ(300u, ranges[2].first);
  1831. EXPECT_EQ(400u, ranges[2].second);
  1832. }
  1833. {
  1834. Ranges ranges;
  1835. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1836. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1837. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1838. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1839. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1840. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1841. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1842. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1843. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1844. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1845. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1846. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1847. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1848. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1849. EXPECT_FALSE(
  1850. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1851. EXPECT_TRUE(ranges.empty());
  1852. }
  1853. {
  1854. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1855. // remainder of the representation, so it stays accepted.
  1856. Ranges ranges;
  1857. auto ret =
  1858. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1859. EXPECT_TRUE(ret);
  1860. ASSERT_EQ(1u, ranges.size());
  1861. EXPECT_EQ(0, ranges[0].first);
  1862. EXPECT_EQ(-1, ranges[0].second);
  1863. }
  1864. // RFC 9110 14.1: range unit names are case-insensitive.
  1865. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1866. Ranges ranges;
  1867. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1868. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1869. }
  1870. }
  1871. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1872. Request req;
  1873. req.set_header("Accept-Encoding", "gzip");
  1874. Response res;
  1875. res.set_header("Content-Type", "text/plain");
  1876. auto ret = detail::encoding_type(req, res);
  1877. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1878. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1879. #else
  1880. EXPECT_TRUE(ret == detail::EncodingType::None);
  1881. #endif
  1882. }
  1883. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1884. Request req;
  1885. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1886. Response res;
  1887. res.set_header("Content-Type", "text/plain");
  1888. auto ret = detail::encoding_type(req, res);
  1889. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1890. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1891. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1892. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1893. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1894. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1895. #else
  1896. EXPECT_TRUE(ret == detail::EncodingType::None);
  1897. #endif
  1898. }
  1899. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1900. Request req;
  1901. req.set_header("Accept-Encoding",
  1902. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1903. Response res;
  1904. res.set_header("Content-Type", "text/plain");
  1905. auto ret = detail::encoding_type(req, res);
  1906. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1907. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1908. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1909. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1910. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1911. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1912. #else
  1913. EXPECT_TRUE(ret == detail::EncodingType::None);
  1914. #endif
  1915. }
  1916. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1917. // All supported encodings rejected with q=0 should return None
  1918. Request req;
  1919. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1920. Response res;
  1921. res.set_header("Content-Type", "text/plain");
  1922. auto ret = detail::encoding_type(req, res);
  1923. EXPECT_TRUE(ret == detail::EncodingType::None);
  1924. }
  1925. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1926. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1927. Request req;
  1928. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1929. Response res;
  1930. res.set_header("Content-Type", "text/plain");
  1931. auto ret = detail::encoding_type(req, res);
  1932. EXPECT_TRUE(ret == detail::EncodingType::None);
  1933. }
  1934. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1935. Request req;
  1936. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1937. Response res;
  1938. res.set_header("Content-Type", "text/plain");
  1939. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1940. }
  1941. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1942. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1943. Request req;
  1944. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1945. Response res;
  1946. res.set_header("Content-Type", "text/plain");
  1947. auto ret = detail::encoding_type(req, res);
  1948. EXPECT_TRUE(ret == detail::EncodingType::None);
  1949. }
  1950. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1951. // RFC 7231: Accept-Encoding values are case-insensitive
  1952. Request req;
  1953. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1954. Response res;
  1955. res.set_header("Content-Type", "text/plain");
  1956. auto ret = detail::encoding_type(req, res);
  1957. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1958. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1959. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1960. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1961. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1962. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1963. #else
  1964. EXPECT_TRUE(ret == detail::EncodingType::None);
  1965. #endif
  1966. }
  1967. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1968. // q value should determine priority, not hardcoded order
  1969. Request req;
  1970. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1971. Response res;
  1972. res.set_header("Content-Type", "text/plain");
  1973. auto ret = detail::encoding_type(req, res);
  1974. // gzip has highest q=1.0, so it should be selected even though
  1975. // br and zstd are also supported
  1976. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1977. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1978. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1979. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1980. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1981. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1982. #else
  1983. EXPECT_TRUE(ret == detail::EncodingType::None);
  1984. #endif
  1985. }
  1986. TEST(BufferStreamTest, read) {
  1987. detail::BufferStream strm1;
  1988. Stream &strm = strm1;
  1989. EXPECT_EQ(5, strm.write("hello"));
  1990. char buf[512];
  1991. EXPECT_EQ(2, strm.read(buf, 2));
  1992. EXPECT_EQ('h', buf[0]);
  1993. EXPECT_EQ('e', buf[1]);
  1994. EXPECT_EQ(2, strm.read(buf, 2));
  1995. EXPECT_EQ('l', buf[0]);
  1996. EXPECT_EQ('l', buf[1]);
  1997. EXPECT_EQ(1, strm.read(buf, 1));
  1998. EXPECT_EQ('o', buf[0]);
  1999. EXPECT_EQ(0, strm.read(buf, 1));
  2000. }
  2001. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2002. auto host = "www.httpwatch.com";
  2003. auto ip = hosted_at(host);
  2004. EXPECT_EQ("23.96.13.243", ip);
  2005. std::vector<std::string> addrs;
  2006. hosted_at(host, addrs);
  2007. EXPECT_EQ(1u, addrs.size());
  2008. }
  2009. #if 0 // It depends on each test environment...
  2010. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2011. auto host = "www.youtube.com";
  2012. std::vector<std::string> addrs;
  2013. hosted_at(host, addrs);
  2014. EXPECT_EQ(20u, addrs.size());
  2015. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2016. EXPECT_TRUE(it != addrs.end());
  2017. }
  2018. #endif
  2019. class ChunkedEncodingTest : public ::testing::Test {
  2020. protected:
  2021. ChunkedEncodingTest()
  2022. : cli_(HOST, PORT)
  2023. #ifdef CPPHTTPLIB_SSL_ENABLED
  2024. ,
  2025. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2026. #endif
  2027. {
  2028. cli_.set_connection_timeout(2);
  2029. #ifdef CPPHTTPLIB_SSL_ENABLED
  2030. cli_.enable_server_certificate_verification(false);
  2031. #endif
  2032. }
  2033. virtual void SetUp() {
  2034. read_file("./image.jpg", image_data_);
  2035. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2036. res.set_content("Hello World!", "text/plain");
  2037. });
  2038. svr_.Get(
  2039. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2040. res.set_chunked_content_provider(
  2041. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2042. size_t remaining = image_data_.size() - offset;
  2043. if (remaining == 0) {
  2044. sink.done();
  2045. } else {
  2046. constexpr size_t CHUNK_SIZE = 1024;
  2047. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2048. sink.write(&image_data_[offset], send_size);
  2049. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2050. }
  2051. return true;
  2052. });
  2053. });
  2054. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2055. svr_.wait_until_ready();
  2056. }
  2057. virtual void TearDown() {
  2058. svr_.stop();
  2059. if (!request_threads_.empty()) {
  2060. std::this_thread::sleep_for(std::chrono::seconds(1));
  2061. for (auto &t : request_threads_) {
  2062. t.join();
  2063. }
  2064. }
  2065. t_.join();
  2066. }
  2067. #ifdef CPPHTTPLIB_SSL_ENABLED
  2068. SSLClient cli_;
  2069. SSLServer svr_;
  2070. #else
  2071. Client cli_;
  2072. Server svr_;
  2073. #endif
  2074. thread t_;
  2075. std::vector<thread> request_threads_;
  2076. std::string image_data_;
  2077. };
  2078. TEST_F(ChunkedEncodingTest, NormalGet) {
  2079. auto res = cli_.Get("/chunked");
  2080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2081. std::string out;
  2082. read_file("./image.jpg", out);
  2083. EXPECT_EQ(StatusCode::OK_200, res->status);
  2084. EXPECT_EQ(out, res->body);
  2085. }
  2086. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2087. std::string body;
  2088. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2089. body.append(data, data_length);
  2090. return true;
  2091. });
  2092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2093. std::string out;
  2094. read_file("./image.jpg", out);
  2095. EXPECT_EQ(StatusCode::OK_200, res->status);
  2096. EXPECT_EQ(out, body);
  2097. }
  2098. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2099. std::string body;
  2100. auto res = cli_.Get(
  2101. "/chunked",
  2102. [&](const Response &response) {
  2103. EXPECT_EQ(StatusCode::OK_200, response.status);
  2104. return true;
  2105. },
  2106. [&](const char *data, size_t data_length) {
  2107. body.append(data, data_length);
  2108. return true;
  2109. });
  2110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2111. std::string out;
  2112. read_file("./image.jpg", out);
  2113. EXPECT_EQ(StatusCode::OK_200, res->status);
  2114. EXPECT_EQ(out, body);
  2115. }
  2116. TEST(RangeTest, FromHTTPBin_Online) {
  2117. auto host = "httpbingo.org";
  2118. auto path = std::string{"/range/32"};
  2119. #ifdef CPPHTTPLIB_SSL_ENABLED
  2120. auto port = 443;
  2121. SSLClient cli(host, port);
  2122. #else
  2123. auto port = 80;
  2124. Client cli(host, port);
  2125. #endif
  2126. cli.set_connection_timeout(5);
  2127. {
  2128. auto res = cli.Get(path);
  2129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2130. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2131. EXPECT_EQ(StatusCode::OK_200, res->status);
  2132. }
  2133. {
  2134. Headers headers = {make_range_header({{1, -1}})};
  2135. auto res = cli.Get(path, headers);
  2136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2137. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2138. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2139. }
  2140. {
  2141. Headers headers = {make_range_header({{1, 10}})};
  2142. auto res = cli.Get(path, headers);
  2143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2144. EXPECT_EQ("bcdefghijk", res->body);
  2145. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2146. }
  2147. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2148. // entire resource, while the original httpbin returned 200. Both are
  2149. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2150. {
  2151. Headers headers = {make_range_header({{0, 31}})};
  2152. auto res = cli.Get(path, headers);
  2153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2154. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2155. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2156. res->status == StatusCode::PartialContent_206);
  2157. }
  2158. {
  2159. Headers headers = {make_range_header({{0, -1}})};
  2160. auto res = cli.Get(path, headers);
  2161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2162. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2163. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2164. res->status == StatusCode::PartialContent_206);
  2165. }
  2166. // go-httpbin returns 206 with clamped range for over-range requests,
  2167. // while the original httpbin returned 416. Both behaviors are observed
  2168. // in real servers, so we only verify the request succeeds.
  2169. {
  2170. Headers headers = {make_range_header({{0, 32}})};
  2171. auto res = cli.Get(path, headers);
  2172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2173. }
  2174. }
  2175. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2176. auto host = "unresolvableaddress.local";
  2177. auto path = std::string{"/"};
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. auto port = 443;
  2180. SSLClient cli(host, port);
  2181. #else
  2182. auto port = 80;
  2183. Client cli(host, port);
  2184. #endif
  2185. cli.set_connection_timeout(1);
  2186. {
  2187. auto res = cli.Get(path);
  2188. ASSERT_FALSE(res);
  2189. }
  2190. std::this_thread::sleep_for(std::chrono::seconds(8));
  2191. }
  2192. #if defined(__linux__) && defined(__GLIBC__) && \
  2193. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2194. // Forward declaration: in split builds split.py strips `inline` and moves the
  2195. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2196. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2197. // against the symbol in both header-only and split builds.
  2198. namespace httplib {
  2199. namespace detail {
  2200. int getaddrinfo_with_timeout(const char *node, const char *service,
  2201. const struct addrinfo *hints,
  2202. struct addrinfo **res, time_t timeout_sec);
  2203. } // namespace detail
  2204. } // namespace httplib
  2205. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2206. //
  2207. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2208. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2209. // gai_suspend() call hits the connection timeout the function calls
  2210. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2211. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2212. // still alive and still references the now-destroyed stack frame.
  2213. //
  2214. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2215. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2216. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2217. // and runs them in a container.
  2218. namespace {
  2219. bool should_run_issue_2431_tests() {
  2220. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2221. return v && *v && std::string(v) != "0";
  2222. }
  2223. std::string unique_unresolvable_host(int n) {
  2224. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2225. // glibc still asks the configured nameserver — which is exactly the path
  2226. // we want to exercise. A unique label per call avoids the resolver cache.
  2227. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2228. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2229. std::to_string(n) + ".invalid";
  2230. }
  2231. } // namespace
  2232. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2233. if (!should_run_issue_2431_tests()) {
  2234. GTEST_SKIP()
  2235. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2236. }
  2237. for (int i = 0; i < 8; ++i) {
  2238. struct addrinfo hints;
  2239. memset(&hints, 0, sizeof(hints));
  2240. hints.ai_family = AF_UNSPEC;
  2241. hints.ai_socktype = SOCK_STREAM;
  2242. auto host = unique_unresolvable_host(i);
  2243. struct addrinfo *result = nullptr;
  2244. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2245. &result, /*timeout_sec=*/1);
  2246. if (rc == 0 && result) { freeaddrinfo(result); }
  2247. }
  2248. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2249. // stack region they still believe holds their gaicb.
  2250. std::this_thread::sleep_for(std::chrono::seconds(3));
  2251. }
  2252. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2253. if (!should_run_issue_2431_tests()) {
  2254. GTEST_SKIP()
  2255. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2256. }
  2257. std::atomic<bool> stop{false};
  2258. std::vector<std::thread> threads;
  2259. for (int t = 0; t < 8; ++t) {
  2260. threads.emplace_back([t, &stop] {
  2261. int i = 0;
  2262. while (!stop.load(std::memory_order_relaxed)) {
  2263. struct addrinfo hints;
  2264. memset(&hints, 0, sizeof(hints));
  2265. hints.ai_family = AF_UNSPEC;
  2266. hints.ai_socktype = SOCK_STREAM;
  2267. auto host = unique_unresolvable_host(t * 100000 + i++);
  2268. struct addrinfo *result = nullptr;
  2269. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2270. &result, /*timeout_sec=*/1);
  2271. if (rc == 0 && result) { freeaddrinfo(result); }
  2272. }
  2273. });
  2274. }
  2275. std::this_thread::sleep_for(std::chrono::seconds(8));
  2276. stop.store(true, std::memory_order_relaxed);
  2277. for (auto &th : threads) {
  2278. th.join();
  2279. }
  2280. std::this_thread::sleep_for(std::chrono::seconds(3));
  2281. }
  2282. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2283. if (!should_run_issue_2431_tests()) {
  2284. GTEST_SKIP()
  2285. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2286. }
  2287. std::atomic<bool> stop{false};
  2288. std::vector<std::thread> threads;
  2289. for (int t = 0; t < 8; ++t) {
  2290. threads.emplace_back([t, &stop] {
  2291. int i = 0;
  2292. while (!stop.load(std::memory_order_relaxed)) {
  2293. auto host = unique_unresolvable_host(t * 100000 + i++);
  2294. Client cli(host, 80);
  2295. cli.set_connection_timeout(1, 0);
  2296. cli.set_read_timeout(1, 0);
  2297. cli.set_write_timeout(1, 0);
  2298. (void)cli.Get("/");
  2299. }
  2300. });
  2301. }
  2302. std::this_thread::sleep_for(std::chrono::seconds(8));
  2303. stop.store(true, std::memory_order_relaxed);
  2304. for (auto &th : threads) {
  2305. th.join();
  2306. }
  2307. std::this_thread::sleep_for(std::chrono::seconds(3));
  2308. }
  2309. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2310. TEST(ConnectionErrorTest, InvalidHost) {
  2311. auto host = "-abcde.com";
  2312. #ifdef CPPHTTPLIB_SSL_ENABLED
  2313. auto port = 443;
  2314. SSLClient cli(host, port);
  2315. #else
  2316. auto port = 80;
  2317. Client cli(host, port);
  2318. #endif
  2319. cli.set_connection_timeout(std::chrono::seconds(2));
  2320. auto res = cli.Get("/");
  2321. ASSERT_TRUE(!res);
  2322. EXPECT_EQ(Error::Connection, res.error());
  2323. }
  2324. TEST(ConnectionErrorTest, InvalidHost2) {
  2325. auto host = "httpcan.org/";
  2326. #ifdef CPPHTTPLIB_SSL_ENABLED
  2327. SSLClient cli(host);
  2328. #else
  2329. Client cli(host);
  2330. #endif
  2331. cli.set_connection_timeout(std::chrono::seconds(2));
  2332. auto res = cli.Get("/");
  2333. ASSERT_TRUE(!res);
  2334. EXPECT_EQ(Error::Connection, res.error());
  2335. }
  2336. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2337. auto host = "httpcan.org/";
  2338. #ifdef CPPHTTPLIB_SSL_ENABLED
  2339. SSLClient cli(host);
  2340. #else
  2341. Client cli(host);
  2342. #endif
  2343. cli.set_connection_timeout(std::chrono::seconds(2));
  2344. auto res = cli.Get("/");
  2345. ASSERT_TRUE(!res);
  2346. stringstream s;
  2347. s << "error code: " << res.error();
  2348. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2349. }
  2350. TEST(ConnectionErrorTest, InvalidPort) {
  2351. auto host = "localhost";
  2352. auto port = 44380;
  2353. #ifdef CPPHTTPLIB_SSL_ENABLED
  2354. SSLClient cli(host, port);
  2355. #else
  2356. Client cli(host, port);
  2357. #endif
  2358. cli.set_connection_timeout(std::chrono::seconds(2));
  2359. auto res = cli.Get("/");
  2360. ASSERT_TRUE(!res);
  2361. EXPECT_TRUE(Error::Connection == res.error() ||
  2362. Error::ConnectionTimeout == res.error());
  2363. }
  2364. TEST(ConnectionErrorTest, Timeout_Online) {
  2365. auto host = "google.com";
  2366. #ifdef CPPHTTPLIB_SSL_ENABLED
  2367. auto port = 44380;
  2368. SSLClient cli(host, port);
  2369. #else
  2370. auto port = 8080;
  2371. Client cli(host, port);
  2372. #endif
  2373. cli.set_connection_timeout(std::chrono::seconds(2));
  2374. // only probe one address type so that the error reason
  2375. // correlates to the timed-out IPv4, not the unsupported
  2376. // IPv6 connection attempt
  2377. cli.set_address_family(AF_INET);
  2378. auto res = cli.Get("/");
  2379. ASSERT_TRUE(!res);
  2380. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2381. }
  2382. TEST(CancelTest, NoCancel_Online) {
  2383. auto host = "httpbingo.org";
  2384. auto path = std::string{"/range/32"};
  2385. #ifdef CPPHTTPLIB_SSL_ENABLED
  2386. auto port = 443;
  2387. SSLClient cli(host, port);
  2388. #else
  2389. auto port = 80;
  2390. Client cli(host, port);
  2391. #endif
  2392. cli.set_connection_timeout(std::chrono::seconds(5));
  2393. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2395. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2396. EXPECT_EQ(StatusCode::OK_200, res->status);
  2397. }
  2398. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2399. // Use /bytes with a large payload so that the DownloadProgress callback
  2400. // (which only fires for Content-Length responses) is invoked before the
  2401. // entire body is received, giving cancellation a chance to fire.
  2402. auto host = "httpbingo.org";
  2403. auto path = std::string{"/bytes/524288"};
  2404. #ifdef CPPHTTPLIB_SSL_ENABLED
  2405. auto port = 443;
  2406. SSLClient cli(host, port);
  2407. #else
  2408. auto port = 80;
  2409. Client cli(host, port);
  2410. #endif
  2411. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2412. cli.set_connection_timeout(std::chrono::seconds(5));
  2413. ASSERT_TRUE(!res);
  2414. EXPECT_EQ(Error::Canceled, res.error());
  2415. }
  2416. TEST(CancelTest, WithCancelLargePayload_Online) {
  2417. auto host = "httpbingo.org";
  2418. auto path = std::string{"/bytes/524288"};
  2419. #ifdef CPPHTTPLIB_SSL_ENABLED
  2420. auto port = 443;
  2421. SSLClient cli(host, port);
  2422. #else
  2423. auto port = 80;
  2424. Client cli(host, port);
  2425. #endif
  2426. cli.set_connection_timeout(std::chrono::seconds(5));
  2427. uint32_t count = 0;
  2428. auto res =
  2429. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2430. ASSERT_TRUE(!res);
  2431. EXPECT_EQ(Error::Canceled, res.error());
  2432. }
  2433. TEST(CancelTest, NoCancelPost) {
  2434. Server svr;
  2435. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2436. res.set_content("Hello World!", "text/plain");
  2437. });
  2438. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2439. auto se = detail::scope_exit([&] {
  2440. svr.stop();
  2441. thread.join();
  2442. ASSERT_FALSE(svr.is_running());
  2443. });
  2444. svr.wait_until_ready();
  2445. Client cli(HOST, PORT);
  2446. cli.set_connection_timeout(std::chrono::seconds(5));
  2447. auto res =
  2448. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2449. "application/json", [](uint64_t, uint64_t) { return true; });
  2450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2451. EXPECT_EQ("Hello World!", res->body);
  2452. EXPECT_EQ(StatusCode::OK_200, res->status);
  2453. }
  2454. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2455. Server svr;
  2456. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2457. res.set_content("Hello World!", "text/plain");
  2458. });
  2459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2460. auto se = detail::scope_exit([&] {
  2461. svr.stop();
  2462. thread.join();
  2463. ASSERT_FALSE(svr.is_running());
  2464. });
  2465. svr.wait_until_ready();
  2466. Client cli(HOST, PORT);
  2467. cli.set_connection_timeout(std::chrono::seconds(5));
  2468. auto res =
  2469. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2470. "application/json", [](uint64_t, uint64_t) { return false; });
  2471. ASSERT_TRUE(!res);
  2472. EXPECT_EQ(Error::Canceled, res.error());
  2473. }
  2474. TEST(CancelTest, WithCancelLargePayloadPost) {
  2475. Server svr;
  2476. svr.set_payload_max_length(200 * 1024 * 1024);
  2477. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2478. res.set_content(LARGE_DATA, "text/plain");
  2479. });
  2480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2481. auto se = detail::scope_exit([&] {
  2482. svr.stop();
  2483. thread.join();
  2484. ASSERT_FALSE(svr.is_running());
  2485. });
  2486. svr.wait_until_ready();
  2487. Client cli(HOST, PORT);
  2488. cli.set_payload_max_length(200 * 1024 * 1024);
  2489. cli.set_connection_timeout(std::chrono::seconds(5));
  2490. auto res =
  2491. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2492. "application/json", [](uint64_t, uint64_t) { return false; });
  2493. ASSERT_TRUE(!res);
  2494. EXPECT_EQ(Error::Canceled, res.error());
  2495. }
  2496. TEST(CancelTest, NoCancelPut) {
  2497. Server svr;
  2498. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2499. res.set_content("Hello World!", "text/plain");
  2500. });
  2501. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2502. auto se = detail::scope_exit([&] {
  2503. svr.stop();
  2504. thread.join();
  2505. ASSERT_FALSE(svr.is_running());
  2506. });
  2507. svr.wait_until_ready();
  2508. Client cli(HOST, PORT);
  2509. cli.set_connection_timeout(std::chrono::seconds(5));
  2510. auto res =
  2511. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2512. "application/json", [](uint64_t, uint64_t) { return true; });
  2513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2514. EXPECT_EQ("Hello World!", res->body);
  2515. EXPECT_EQ(StatusCode::OK_200, res->status);
  2516. }
  2517. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2518. Server svr;
  2519. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2520. res.set_content("Hello World!", "text/plain");
  2521. });
  2522. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2523. auto se = detail::scope_exit([&] {
  2524. svr.stop();
  2525. thread.join();
  2526. ASSERT_FALSE(svr.is_running());
  2527. });
  2528. svr.wait_until_ready();
  2529. Client cli(HOST, PORT);
  2530. cli.set_connection_timeout(std::chrono::seconds(5));
  2531. auto res =
  2532. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2533. "application/json", [](uint64_t, uint64_t) { return false; });
  2534. ASSERT_TRUE(!res);
  2535. EXPECT_EQ(Error::Canceled, res.error());
  2536. }
  2537. TEST(CancelTest, WithCancelLargePayloadPut) {
  2538. Server svr;
  2539. svr.set_payload_max_length(200 * 1024 * 1024);
  2540. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2541. res.set_content(LARGE_DATA, "text/plain");
  2542. });
  2543. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2544. auto se = detail::scope_exit([&] {
  2545. svr.stop();
  2546. thread.join();
  2547. ASSERT_FALSE(svr.is_running());
  2548. });
  2549. svr.wait_until_ready();
  2550. Client cli(HOST, PORT);
  2551. cli.set_payload_max_length(200 * 1024 * 1024);
  2552. cli.set_connection_timeout(std::chrono::seconds(5));
  2553. auto res =
  2554. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2555. "application/json", [](uint64_t, uint64_t) { return false; });
  2556. ASSERT_TRUE(!res);
  2557. EXPECT_EQ(Error::Canceled, res.error());
  2558. }
  2559. TEST(CancelTest, NoCancelPatch) {
  2560. Server svr;
  2561. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2562. res.set_content("Hello World!", "text/plain");
  2563. });
  2564. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2565. auto se = detail::scope_exit([&] {
  2566. svr.stop();
  2567. thread.join();
  2568. ASSERT_FALSE(svr.is_running());
  2569. });
  2570. svr.wait_until_ready();
  2571. Client cli(HOST, PORT);
  2572. cli.set_connection_timeout(std::chrono::seconds(5));
  2573. auto res =
  2574. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2575. "application/json", [](uint64_t, uint64_t) { return true; });
  2576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2577. EXPECT_EQ("Hello World!", res->body);
  2578. EXPECT_EQ(StatusCode::OK_200, res->status);
  2579. }
  2580. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2581. Server svr;
  2582. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2583. res.set_content("Hello World!", "text/plain");
  2584. });
  2585. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2586. auto se = detail::scope_exit([&] {
  2587. svr.stop();
  2588. thread.join();
  2589. ASSERT_FALSE(svr.is_running());
  2590. });
  2591. svr.wait_until_ready();
  2592. Client cli(HOST, PORT);
  2593. cli.set_connection_timeout(std::chrono::seconds(5));
  2594. auto res =
  2595. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2596. "application/json", [](uint64_t, uint64_t) { return false; });
  2597. ASSERT_TRUE(!res);
  2598. EXPECT_EQ(Error::Canceled, res.error());
  2599. }
  2600. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2601. Server svr;
  2602. svr.set_payload_max_length(200 * 1024 * 1024);
  2603. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2604. res.set_content(LARGE_DATA, "text/plain");
  2605. });
  2606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2607. auto se = detail::scope_exit([&] {
  2608. svr.stop();
  2609. thread.join();
  2610. ASSERT_FALSE(svr.is_running());
  2611. });
  2612. svr.wait_until_ready();
  2613. Client cli(HOST, PORT);
  2614. cli.set_payload_max_length(200 * 1024 * 1024);
  2615. cli.set_connection_timeout(std::chrono::seconds(5));
  2616. auto res =
  2617. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2618. "application/json", [](uint64_t, uint64_t) { return false; });
  2619. ASSERT_TRUE(!res);
  2620. EXPECT_EQ(Error::Canceled, res.error());
  2621. }
  2622. TEST(CancelTest, NoCancelDelete) {
  2623. Server svr;
  2624. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2625. res.set_content("Hello World!", "text/plain");
  2626. });
  2627. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2628. auto se = detail::scope_exit([&] {
  2629. svr.stop();
  2630. thread.join();
  2631. ASSERT_FALSE(svr.is_running());
  2632. });
  2633. svr.wait_until_ready();
  2634. Client cli(HOST, PORT);
  2635. cli.set_connection_timeout(std::chrono::seconds(5));
  2636. auto res =
  2637. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2638. "application/json", [](uint64_t, uint64_t) { return true; });
  2639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2640. EXPECT_EQ("Hello World!", res->body);
  2641. EXPECT_EQ(StatusCode::OK_200, res->status);
  2642. }
  2643. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2644. Server svr;
  2645. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2646. res.set_content("Hello World!", "text/plain");
  2647. });
  2648. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2649. auto se = detail::scope_exit([&] {
  2650. svr.stop();
  2651. thread.join();
  2652. ASSERT_FALSE(svr.is_running());
  2653. });
  2654. svr.wait_until_ready();
  2655. Client cli(HOST, PORT);
  2656. cli.set_connection_timeout(std::chrono::seconds(5));
  2657. auto res =
  2658. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2659. "application/json", [](uint64_t, uint64_t) { return false; });
  2660. ASSERT_TRUE(!res);
  2661. EXPECT_EQ(Error::Canceled, res.error());
  2662. }
  2663. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2664. Server svr;
  2665. svr.set_payload_max_length(200 * 1024 * 1024);
  2666. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2667. res.set_content(LARGE_DATA, "text/plain");
  2668. });
  2669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2670. auto se = detail::scope_exit([&] {
  2671. svr.stop();
  2672. thread.join();
  2673. ASSERT_FALSE(svr.is_running());
  2674. });
  2675. svr.wait_until_ready();
  2676. Client cli(HOST, PORT);
  2677. cli.set_payload_max_length(200 * 1024 * 1024);
  2678. cli.set_connection_timeout(std::chrono::seconds(5));
  2679. auto res =
  2680. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2681. "application/json", [](uint64_t, uint64_t) { return false; });
  2682. ASSERT_TRUE(!res);
  2683. EXPECT_EQ(Error::Canceled, res.error());
  2684. }
  2685. static std::string remove_whitespace(const std::string &input) {
  2686. std::string output;
  2687. output.reserve(input.size());
  2688. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2689. [](unsigned char c) { return !std::isspace(c); });
  2690. return output;
  2691. }
  2692. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2693. auto host = "httpbingo.org";
  2694. auto path = std::string{"/basic-auth/hello/world"};
  2695. #ifdef CPPHTTPLIB_SSL_ENABLED
  2696. auto port = 443;
  2697. SSLClient cli(host, port);
  2698. #else
  2699. auto port = 80;
  2700. Client cli(host, port);
  2701. #endif
  2702. {
  2703. auto res = cli.Get(path);
  2704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2705. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2706. }
  2707. {
  2708. auto res = cli.Get(
  2709. path, Headers{make_basic_authentication_header("hello", "world")});
  2710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2711. auto body = remove_whitespace(res->body);
  2712. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2713. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2714. EXPECT_EQ(StatusCode::OK_200, res->status);
  2715. }
  2716. {
  2717. cli.set_basic_auth("hello", "world");
  2718. auto res = cli.Get(path);
  2719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2720. auto body = remove_whitespace(res->body);
  2721. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2722. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2723. EXPECT_EQ(StatusCode::OK_200, res->status);
  2724. }
  2725. {
  2726. cli.set_basic_auth("hello", "bad");
  2727. auto res = cli.Get(path);
  2728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2729. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2730. }
  2731. {
  2732. cli.set_basic_auth("bad", "world");
  2733. auto res = cli.Get(path);
  2734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2735. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2736. }
  2737. }
  2738. #ifdef CPPHTTPLIB_SSL_ENABLED
  2739. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2740. auto host = "httpbingo.org";
  2741. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2742. auto paths = std::vector<std::string>{
  2743. "/digest-auth/auth/hello/world/MD5",
  2744. "/digest-auth/auth/hello/world/SHA-256",
  2745. };
  2746. auto port = 443;
  2747. SSLClient cli(host, port);
  2748. {
  2749. auto res = cli.Get(unauth_path);
  2750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2751. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2752. }
  2753. {
  2754. cli.set_digest_auth("hello", "world");
  2755. for (const auto &path : paths) {
  2756. auto res = cli.Get(path.c_str());
  2757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2758. auto body = remove_whitespace(res->body);
  2759. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2760. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2761. EXPECT_EQ(StatusCode::OK_200, res->status);
  2762. }
  2763. cli.set_digest_auth("hello", "bad");
  2764. for (const auto &path : paths) {
  2765. auto res = cli.Get(path.c_str());
  2766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2767. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2768. }
  2769. }
  2770. }
  2771. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2772. // comma-separated list of challenges, and each challenge may itself carry a
  2773. // comma-separated auth-param list, so a server can legally offer Basic
  2774. // before Digest, either as two field lines or packed into one. Runs one 401
  2775. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2776. // value() joins them in receipt order) and checks that the retry carries a
  2777. // well-formed Digest Authorization header naming expected_realm.
  2778. static void
  2779. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2780. const std::string &expected_realm) {
  2781. std::atomic<int> hits{0};
  2782. Server svr;
  2783. svr.Get("/x", [&](const Request &req, Response &res) {
  2784. if (++hits == 1) {
  2785. res.status = StatusCode::Unauthorized_401;
  2786. for (const auto &challenge : challenges) {
  2787. res.set_header("WWW-Authenticate", challenge);
  2788. }
  2789. } else {
  2790. auto authorization = req.get_header_value("Authorization");
  2791. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2792. EXPECT_NE(std::string::npos,
  2793. authorization.find("realm=\"" + expected_realm + "\""));
  2794. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2795. res.set_content("ok", "text/plain");
  2796. }
  2797. });
  2798. auto port = svr.bind_to_any_port(HOST);
  2799. std::thread t([&]() { svr.listen_after_bind(); });
  2800. auto se = detail::scope_exit([&] {
  2801. svr.stop();
  2802. t.join();
  2803. });
  2804. svr.wait_until_ready();
  2805. Client cli(HOST, port);
  2806. cli.set_digest_auth("hello", "world");
  2807. auto res = cli.Get("/x");
  2808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2809. EXPECT_EQ(2, hits.load());
  2810. }
  2811. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2812. static const char *kDigestChallenge =
  2813. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2814. "algorithm=MD5";
  2815. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2816. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2817. "testrealm");
  2818. }
  2819. // Same challenge list with the schemes in the opposite order, to make sure
  2820. // the fix above didn't just special-case "Basic first".
  2821. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2822. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2823. "testrealm");
  2824. }
  2825. // A comma inside a quoted auth-param value must not be mistaken for the
  2826. // separator between two challenges (or two auth-params).
  2827. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2828. run_digest_challenge_list_test(
  2829. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2830. "algorithm=MD5"},
  2831. "test,realm");
  2832. }
  2833. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2834. // make_digest_authentication_header() dereferences both unconditionally, so
  2835. // a server sending a challenge missing either one must not be treated as
  2836. // usable -- doing so used to crash the client with std::out_of_range.
  2837. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2838. Server svr;
  2839. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2840. res.status = StatusCode::Unauthorized_401;
  2841. res.set_header("WWW-Authenticate", challenge);
  2842. });
  2843. auto port = svr.bind_to_any_port(HOST);
  2844. std::thread t([&]() { svr.listen_after_bind(); });
  2845. auto se = detail::scope_exit([&] {
  2846. svr.stop();
  2847. t.join();
  2848. });
  2849. svr.wait_until_ready();
  2850. Client cli(HOST, port);
  2851. cli.set_digest_auth("hello", "world");
  2852. auto res = cli.Get("/x");
  2853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2854. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2855. }
  2856. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2857. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2858. }
  2859. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2860. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2861. }
  2862. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2863. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2864. }
  2865. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2866. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2867. // when storing the values, so the header builder has to re-escape them (and
  2868. // keep algorithm a bare token); otherwise the value breaks out of its
  2869. // quoted-string and injects extra auth-params into the client's Authorization.
  2870. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2871. std::atomic<int> hits{0};
  2872. std::string authorization;
  2873. Server svr;
  2874. svr.Get("/x", [&](const Request &req, Response &res) {
  2875. if (++hits == 1) {
  2876. res.status = StatusCode::Unauthorized_401;
  2877. // On the wire the quotes embedded in the values are backslash-escaped.
  2878. res.set_header("WWW-Authenticate",
  2879. "Digest realm=\"testrealm\", "
  2880. "nonce=\"n\\\"; injected=\\\"x\", "
  2881. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2882. } else {
  2883. authorization = req.get_header_value("Authorization");
  2884. res.set_content("ok", "text/plain");
  2885. }
  2886. });
  2887. auto port = svr.bind_to_any_port(HOST);
  2888. std::thread t([&]() { svr.listen_after_bind(); });
  2889. auto se = detail::scope_exit([&] {
  2890. svr.stop();
  2891. t.join();
  2892. });
  2893. svr.wait_until_ready();
  2894. Client cli(HOST, port);
  2895. cli.set_digest_auth("hello", "world");
  2896. auto res = cli.Get("/x");
  2897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2898. EXPECT_EQ(2, hits.load());
  2899. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2900. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2901. // inside its quoted-string rather than starting an "injected" auth-param.
  2902. EXPECT_NE(std::string::npos,
  2903. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2904. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2905. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2906. }
  2907. #endif
  2908. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2909. auto host = "google.com";
  2910. auto another_host = "example.com";
  2911. auto wrong_ip = "0.0.0.0";
  2912. #ifdef CPPHTTPLIB_SSL_ENABLED
  2913. SSLClient cli(host);
  2914. #else
  2915. Client cli(host);
  2916. #endif
  2917. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2918. auto res = cli.Get("/");
  2919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2920. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2921. }
  2922. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2923. auto host = "google.com";
  2924. auto wrong_ip = "0.0.0.0";
  2925. #ifdef CPPHTTPLIB_SSL_ENABLED
  2926. SSLClient cli(host);
  2927. #else
  2928. Client cli(host);
  2929. #endif
  2930. cli.set_hostname_addr_map({{host, wrong_ip}});
  2931. auto res = cli.Get("/");
  2932. ASSERT_TRUE(!res);
  2933. EXPECT_EQ(Error::Connection, res.error());
  2934. }
  2935. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2936. // A mapped value that is not an IP literal must be resolved. "localhost"
  2937. // resolves from the hosts file, so this test needs no external DNS.
  2938. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2939. auto host = "target.invalid";
  2940. Server svr;
  2941. std::string received_host;
  2942. svr.Get("/hi", [&](const Request &req, Response &res) {
  2943. received_host = req.get_header_value("Host");
  2944. res.set_content("Hello World!", "text/plain");
  2945. });
  2946. auto port = svr.bind_to_any_port(HOST);
  2947. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2948. auto se = detail::scope_exit([&] {
  2949. svr.stop();
  2950. thread.join();
  2951. ASSERT_FALSE(svr.is_running());
  2952. });
  2953. svr.wait_until_ready();
  2954. Client cli(host, port);
  2955. cli.set_hostname_addr_map({{host, HOST}});
  2956. auto res = cli.Get("/hi");
  2957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2958. EXPECT_EQ(StatusCode::OK_200, res->status);
  2959. // The mapping only redirects the connection; the identity stays host_.
  2960. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2961. }
  2962. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2963. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2964. auto host = "target.invalid";
  2965. Server svr;
  2966. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2967. res.set_content("Hello World!", "text/plain");
  2968. });
  2969. auto port = svr.bind_to_any_port("127.0.0.1");
  2970. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2971. auto se = detail::scope_exit([&] {
  2972. svr.stop();
  2973. thread.join();
  2974. ASSERT_FALSE(svr.is_running());
  2975. });
  2976. svr.wait_until_ready();
  2977. Client cli(host, port);
  2978. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2979. auto res = cli.Get("/hi");
  2980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2981. EXPECT_EQ(StatusCode::OK_200, res->status);
  2982. }
  2983. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2984. // An empty mapped value must leave host_ as the connection target. Without
  2985. // that guard the empty value would become the host argument, getaddrinfo
  2986. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2987. // loopback - silently connecting somewhere the caller never asked for.
  2988. // The server listens on loopback, so such a fallback would succeed and is
  2989. // therefore observable as a failure of this test.
  2990. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2991. Server svr;
  2992. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2993. res.set_content("Hello World!", "text/plain");
  2994. });
  2995. auto port = svr.bind_to_any_port(HOST);
  2996. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2997. auto se = detail::scope_exit([&] {
  2998. svr.stop();
  2999. thread.join();
  3000. ASSERT_FALSE(svr.is_running());
  3001. });
  3002. svr.wait_until_ready();
  3003. Client cli(blackhole, port);
  3004. cli.set_hostname_addr_map({{blackhole, ""}});
  3005. cli.set_connection_timeout(1);
  3006. auto res = cli.Get("/hi");
  3007. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3008. }
  3009. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3010. auto host = "httpbingo.org";
  3011. auto path = std::string{"/absolute-redirect/3"};
  3012. #ifdef CPPHTTPLIB_SSL_ENABLED
  3013. SSLClient cli(host);
  3014. #else
  3015. Client cli(host);
  3016. #endif
  3017. cli.set_follow_location(true);
  3018. auto res = cli.Get(path);
  3019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3020. EXPECT_EQ(StatusCode::OK_200, res->status);
  3021. }
  3022. TEST(RedirectTest, Redirect_Online) {
  3023. auto host = "httpbingo.org";
  3024. auto path = std::string{"/redirect/3"};
  3025. #ifdef CPPHTTPLIB_SSL_ENABLED
  3026. SSLClient cli(host);
  3027. #else
  3028. Client cli(host);
  3029. #endif
  3030. cli.set_follow_location(true);
  3031. auto res = cli.Get(path);
  3032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3033. EXPECT_EQ(StatusCode::OK_200, res->status);
  3034. }
  3035. TEST(RelativeRedirectTest, Redirect_Online) {
  3036. auto host = "httpbingo.org";
  3037. auto path = std::string{"/relative-redirect/3"};
  3038. #ifdef CPPHTTPLIB_SSL_ENABLED
  3039. SSLClient cli(host);
  3040. #else
  3041. Client cli(host);
  3042. #endif
  3043. cli.set_follow_location(true);
  3044. auto res = cli.Get(path);
  3045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3046. EXPECT_EQ(StatusCode::OK_200, res->status);
  3047. }
  3048. TEST(TooManyRedirectTest, Redirect_Online) {
  3049. auto host = "httpbingo.org";
  3050. auto path = std::string{"/redirect/21"};
  3051. #ifdef CPPHTTPLIB_SSL_ENABLED
  3052. SSLClient cli(host);
  3053. #else
  3054. Client cli(host);
  3055. #endif
  3056. cli.set_follow_location(true);
  3057. auto res = cli.Get(path);
  3058. ASSERT_TRUE(!res);
  3059. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3060. }
  3061. #ifdef CPPHTTPLIB_SSL_ENABLED
  3062. TEST(YahooRedirectTest, Redirect_Online) {
  3063. Client cli("yahoo.com");
  3064. auto res = cli.Get("/");
  3065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3066. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3067. cli.set_follow_location(true);
  3068. res = cli.Get("/");
  3069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3070. EXPECT_EQ(StatusCode::OK_200, res->status);
  3071. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3072. }
  3073. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3074. #define REDIR_HOST "httpbingo.org"
  3075. #define REDIR_PATH "/redirect-to"
  3076. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3077. SSLClient cli(REDIR_HOST);
  3078. cli.set_follow_location(true);
  3079. auto res =
  3080. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3082. EXPECT_EQ(StatusCode::OK_200, res->status);
  3083. }
  3084. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3085. SSLClient cli(REDIR_HOST);
  3086. cli.set_follow_location(true);
  3087. Params params;
  3088. params.emplace("url", "http://example.com");
  3089. params.emplace("status_code", "302");
  3090. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3092. EXPECT_EQ(StatusCode::OK_200, res->status);
  3093. }
  3094. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3095. SSLClient cli(REDIR_HOST);
  3096. cli.set_follow_location(true);
  3097. Params params;
  3098. params.emplace("url", "http://example.com");
  3099. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3101. EXPECT_EQ(StatusCode::OK_200, res->status);
  3102. }
  3103. TEST(UrlWithSpace, Redirect_Online) {
  3104. SSLClient cli("edge.forgecdn.net");
  3105. cli.set_follow_location(true);
  3106. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3108. EXPECT_EQ(StatusCode::OK_200, res->status);
  3109. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3110. }
  3111. #endif
  3112. #if !defined(_WIN32) && !defined(_WIN64)
  3113. TEST(ReceiveSignals, Signal) {
  3114. auto setupSignalHandlers = []() {
  3115. struct sigaction act;
  3116. sigemptyset(&act.sa_mask);
  3117. act.sa_flags = SA_SIGINFO;
  3118. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3119. switch (sig) {
  3120. case SIGINT:
  3121. default: break;
  3122. }
  3123. };
  3124. ::sigaction(SIGINT, &act, nullptr);
  3125. };
  3126. Server svr;
  3127. int port = 0;
  3128. auto thread = std::thread([&]() {
  3129. setupSignalHandlers();
  3130. port = svr.bind_to_any_port(HOST);
  3131. svr.listen_after_bind();
  3132. });
  3133. auto se = detail::scope_exit([&] {
  3134. svr.stop();
  3135. thread.join();
  3136. ASSERT_FALSE(svr.is_running());
  3137. });
  3138. svr.wait_until_ready();
  3139. ASSERT_TRUE(svr.is_running());
  3140. pthread_kill(thread.native_handle(), SIGINT);
  3141. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3142. ASSERT_TRUE(svr.is_running());
  3143. }
  3144. #endif
  3145. TEST(RedirectToDifferentPort, Redirect) {
  3146. Server svr1;
  3147. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3148. res.set_content("Hello World!", "text/plain");
  3149. });
  3150. int svr1_port = 0;
  3151. auto thread1 = std::thread([&]() {
  3152. svr1_port = svr1.bind_to_any_port(HOST);
  3153. svr1.listen_after_bind();
  3154. });
  3155. Server svr2;
  3156. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3157. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3158. });
  3159. int svr2_port = 0;
  3160. auto thread2 = std::thread([&]() {
  3161. svr2_port = svr2.bind_to_any_port(HOST);
  3162. svr2.listen_after_bind();
  3163. });
  3164. auto se = detail::scope_exit([&] {
  3165. svr2.stop();
  3166. thread2.join();
  3167. svr1.stop();
  3168. thread1.join();
  3169. ASSERT_FALSE(svr2.is_running());
  3170. ASSERT_FALSE(svr1.is_running());
  3171. });
  3172. svr1.wait_until_ready();
  3173. svr2.wait_until_ready();
  3174. Client cli("localhost", svr2_port);
  3175. cli.set_follow_location(true);
  3176. auto res = cli.Get("/2");
  3177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3178. EXPECT_EQ(StatusCode::OK_200, res->status);
  3179. EXPECT_EQ("Hello World!", res->body);
  3180. }
  3181. // GET /redir on one server redirects to /target on another port, so the
  3182. // client follows it with a new client.
  3183. static Result
  3184. GetThroughRedirectToDifferentPort(Server::Handler target,
  3185. const std::function<void(Client &)> &setup,
  3186. const Headers &headers = Headers()) {
  3187. Server target_svr;
  3188. target_svr.Get("/target", target);
  3189. int target_port = 0;
  3190. auto target_thread = std::thread([&]() {
  3191. target_port = target_svr.bind_to_any_port(HOST);
  3192. target_svr.listen_after_bind();
  3193. });
  3194. Server origin_svr;
  3195. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3196. res.set_redirect(
  3197. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3198. });
  3199. int origin_port = 0;
  3200. auto origin_thread = std::thread([&]() {
  3201. origin_port = origin_svr.bind_to_any_port(HOST);
  3202. origin_svr.listen_after_bind();
  3203. });
  3204. auto se = detail::scope_exit([&] {
  3205. origin_svr.stop();
  3206. origin_thread.join();
  3207. target_svr.stop();
  3208. target_thread.join();
  3209. });
  3210. target_svr.wait_until_ready();
  3211. origin_svr.wait_until_ready();
  3212. Client cli("localhost", origin_port);
  3213. cli.set_follow_location(true);
  3214. setup(cli);
  3215. return cli.Get("/redir", headers);
  3216. }
  3217. static void
  3218. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3219. std::string captured_authorization;
  3220. auto result = GetThroughRedirectToDifferentPort(
  3221. [&](const Request &req, Response &res) {
  3222. captured_authorization = req.get_header_value("Authorization");
  3223. res.set_content("OK", "text/plain");
  3224. },
  3225. set_auth);
  3226. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3227. EXPECT_EQ(StatusCode::OK_200, result->status);
  3228. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3229. EXPECT_TRUE(captured_authorization.empty());
  3230. }
  3231. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3232. TestDoNotForwardCredentialsOnRedirect(
  3233. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3234. }
  3235. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3236. TestDoNotForwardCredentialsOnRedirect(
  3237. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3238. }
  3239. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3240. std::string captured_cookie;
  3241. auto result = GetThroughRedirectToDifferentPort(
  3242. [&](const Request &req, Response &res) {
  3243. captured_cookie = req.get_header_value("Cookie");
  3244. res.set_content("OK", "text/plain");
  3245. },
  3246. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3247. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3248. EXPECT_EQ(StatusCode::OK_200, result->status);
  3249. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3250. EXPECT_TRUE(captured_cookie.empty());
  3251. }
  3252. TEST(RedirectToSamePort, ForwardCookie) {
  3253. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3254. // header so that ordinary session flows keep working.
  3255. Server svr;
  3256. std::string captured_cookie;
  3257. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3258. res.set_redirect("/target", 302);
  3259. });
  3260. svr.Get("/target", [&](const Request &req, Response &res) {
  3261. captured_cookie = req.get_header_value("Cookie");
  3262. res.set_content("OK", "text/plain");
  3263. });
  3264. auto port = svr.bind_to_any_port(HOST);
  3265. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3266. auto se = detail::scope_exit([&] {
  3267. svr.stop();
  3268. thread.join();
  3269. ASSERT_FALSE(svr.is_running());
  3270. });
  3271. svr.wait_until_ready();
  3272. Client cli(HOST, port);
  3273. cli.set_follow_location(true);
  3274. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3275. auto res = cli.Get("/redir", headers);
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. EXPECT_EQ(StatusCode::OK_200, res->status);
  3278. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3279. }
  3280. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3281. std::string authorization;
  3282. std::string trace_id;
  3283. auto result = GetThroughRedirectToDifferentPort(
  3284. [&](const Request &req, Response &res) {
  3285. authorization = req.get_header_value("Authorization");
  3286. trace_id = req.get_header_value("X-Trace-Id");
  3287. res.set_content("OK", "text/plain");
  3288. },
  3289. [](Client &cli) {
  3290. cli.set_default_headers(
  3291. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3292. });
  3293. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3294. EXPECT_EQ(StatusCode::OK_200, result->status);
  3295. // Like a header given with the request, a default one goes along unless it
  3296. // carries credentials (RFC 9110 15.4).
  3297. EXPECT_TRUE(authorization.empty());
  3298. EXPECT_EQ("42", trace_id);
  3299. }
  3300. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3301. auto result = GetThroughRedirectToDifferentPort(
  3302. [](const Request &, Response &res) {
  3303. res.set_content(std::string(2048, 'x'), "text/plain");
  3304. },
  3305. [](Client &cli) { cli.set_payload_max_length(1024); });
  3306. EXPECT_FALSE(result);
  3307. }
  3308. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3309. auto result = GetThroughRedirectToDifferentPort(
  3310. [](const Request &req, Response &res) {
  3311. // Answer after a second, or once the client gives up.
  3312. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3313. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3314. }
  3315. res.set_content("late", "text/plain");
  3316. },
  3317. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3318. ASSERT_FALSE(result);
  3319. EXPECT_EQ(Error::Read, result.error());
  3320. }
  3321. #ifdef CPPHTTPLIB_SSL_ENABLED
  3322. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3323. auto result = GetThroughRedirectToDifferentPort(
  3324. [](const Request &, Response &res) {
  3325. res.status = StatusCode::Unauthorized_401;
  3326. res.set_header("WWW-Authenticate",
  3327. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3328. },
  3329. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3330. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3331. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3332. }
  3333. #endif
  3334. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3335. Server svr;
  3336. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3337. // Port number that overflows int — should not crash
  3338. res.set_redirect("http://localhost:99999999999999999999/target");
  3339. });
  3340. auto port = svr.bind_to_any_port(HOST);
  3341. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3342. auto se = detail::scope_exit([&] {
  3343. svr.stop();
  3344. thread.join();
  3345. ASSERT_FALSE(svr.is_running());
  3346. });
  3347. svr.wait_until_ready();
  3348. Client cli(HOST, port);
  3349. cli.set_follow_location(true);
  3350. auto res = cli.Get("/redir");
  3351. // Should fail gracefully, not crash (no valid response due to bad port)
  3352. EXPECT_FALSE(res);
  3353. }
  3354. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3355. Server svr;
  3356. auto port = svr.bind_to_any_port(HOST);
  3357. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3358. // The server's own port followed by junk must not be followed
  3359. res.set_redirect("http://" + std::string(HOST) + ":" +
  3360. std::to_string(port) + "junk/target");
  3361. });
  3362. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3363. res.set_content("target", "text/plain");
  3364. });
  3365. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3366. auto se = detail::scope_exit([&] {
  3367. svr.stop();
  3368. thread.join();
  3369. ASSERT_FALSE(svr.is_running());
  3370. });
  3371. svr.wait_until_ready();
  3372. Client cli(HOST, port);
  3373. cli.set_follow_location(true);
  3374. auto res = cli.Get("/redir");
  3375. EXPECT_FALSE(res);
  3376. }
  3377. TEST(RedirectFromPageWithContent, Redirect) {
  3378. Server svr;
  3379. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3380. res.set_content("___", "text/plain");
  3381. res.set_redirect("/2");
  3382. });
  3383. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3384. res.set_content("Hello World!", "text/plain");
  3385. });
  3386. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3387. auto se = detail::scope_exit([&] {
  3388. svr.stop();
  3389. th.join();
  3390. ASSERT_FALSE(svr.is_running());
  3391. });
  3392. svr.wait_until_ready();
  3393. {
  3394. Client cli("localhost", PORT);
  3395. cli.set_follow_location(true);
  3396. std::string body;
  3397. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3398. body.append(data, data_length);
  3399. return true;
  3400. });
  3401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3402. EXPECT_EQ(StatusCode::OK_200, res->status);
  3403. EXPECT_EQ("Hello World!", body);
  3404. }
  3405. {
  3406. Client cli("localhost", PORT);
  3407. std::string body;
  3408. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3409. body.append(data, data_length);
  3410. return true;
  3411. });
  3412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3413. EXPECT_EQ(StatusCode::Found_302, res->status);
  3414. EXPECT_EQ("___", body);
  3415. }
  3416. }
  3417. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3418. Server svr;
  3419. auto port_str = std::to_string(PORT);
  3420. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3421. auto expected_host = "[::1]:" + port_str;
  3422. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3423. res.set_content("___", "text/plain");
  3424. // res.set_redirect("/2");
  3425. res.set_redirect(redirect_url);
  3426. });
  3427. svr.Get("/2", [&](const Request &req, Response &res) {
  3428. auto host_header = req.headers.find("Host");
  3429. ASSERT_TRUE(host_header != req.headers.end());
  3430. EXPECT_EQ(expected_host, host_header->second);
  3431. res.set_content("Hello World!", "text/plain");
  3432. });
  3433. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3434. auto se = detail::scope_exit([&] {
  3435. svr.stop();
  3436. th.join();
  3437. ASSERT_FALSE(svr.is_running());
  3438. });
  3439. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3440. // actually starts anything, so the condition !svr.is_running() will
  3441. // always remain true, and the loop never stops.
  3442. // This basically counts how many milliseconds have passed since the
  3443. // call to svr.listen(), and if after 5 seconds nothing started yet
  3444. // aborts the test.
  3445. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3446. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3447. ASSERT_LT(milliseconds, 5000U);
  3448. }
  3449. {
  3450. Client cli("::1", PORT);
  3451. cli.set_follow_location(true);
  3452. std::string body;
  3453. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3454. body.append(data, data_length);
  3455. return true;
  3456. });
  3457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3458. EXPECT_EQ(StatusCode::OK_200, res->status);
  3459. EXPECT_EQ("Hello World!", body);
  3460. }
  3461. {
  3462. Client cli("::1", PORT);
  3463. std::string body;
  3464. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3465. body.append(data, data_length);
  3466. return true;
  3467. });
  3468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3469. EXPECT_EQ(StatusCode::Found_302, res->status);
  3470. EXPECT_EQ("___", body);
  3471. }
  3472. }
  3473. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3474. Server svr;
  3475. svr.Get("/foo", [](const Request &req, Response &res) {
  3476. auto a = req.params.find("a");
  3477. if (a != req.params.end()) {
  3478. res.set_content((*a).second, "text/plain");
  3479. res.status = StatusCode::OK_200;
  3480. } else {
  3481. res.status = StatusCode::BadRequest_400;
  3482. }
  3483. });
  3484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3485. auto se = detail::scope_exit([&] {
  3486. svr.stop();
  3487. thread.join();
  3488. ASSERT_FALSE(svr.is_running());
  3489. });
  3490. svr.wait_until_ready();
  3491. {
  3492. Client cli(HOST, PORT);
  3493. cli.set_path_encode(false);
  3494. auto res = cli.Get("/foo?a=explicitly+encoded");
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. // This expects it back with a space, as the `+` won't have been
  3498. // url-encoded, and server-side the params get decoded turning `+`
  3499. // into spaces.
  3500. EXPECT_EQ("explicitly encoded", res->body);
  3501. }
  3502. }
  3503. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3504. // When path encoding is disabled the client must transmit the supplied
  3505. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3506. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3507. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3508. // than a space (0x20). Assert on the raw wire target to catch this.
  3509. Server svr;
  3510. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3511. svr.Get("/foo", [&](const Request &req, Response &res) {
  3512. EXPECT_EQ(expected_target, req.target);
  3513. res.status = StatusCode::OK_200;
  3514. });
  3515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3516. auto se = detail::scope_exit([&] {
  3517. svr.stop();
  3518. thread.join();
  3519. ASSERT_FALSE(svr.is_running());
  3520. });
  3521. svr.wait_until_ready();
  3522. {
  3523. Client cli(HOST, PORT);
  3524. cli.set_path_encode(false);
  3525. auto res = cli.Get(expected_target.c_str());
  3526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3527. EXPECT_EQ(StatusCode::OK_200, res->status);
  3528. }
  3529. }
  3530. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3531. // `open_stream()` used to skip the path encoding that the buffered send
  3532. // path applies, so the same `path` produced different bytes in the request
  3533. // line depending on which API was used. Assert the two agree.
  3534. Server svr;
  3535. std::string target;
  3536. svr.Get(".*", [&](const Request &req, Response &res) {
  3537. target = req.target;
  3538. res.status = StatusCode::OK_200;
  3539. });
  3540. auto port = svr.bind_to_any_port(HOST);
  3541. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3542. auto se = detail::scope_exit([&] {
  3543. svr.stop();
  3544. thread.join();
  3545. ASSERT_FALSE(svr.is_running());
  3546. });
  3547. svr.wait_until_ready();
  3548. struct {
  3549. const char *path;
  3550. const char *expected;
  3551. } cases[] = {
  3552. {"/a b?x=1", "/a%20b?x=1"},
  3553. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3554. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3555. };
  3556. for (const auto &c : cases) {
  3557. Client cli(HOST, port);
  3558. target.clear();
  3559. auto res = cli.Get(c.path);
  3560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3561. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3562. auto buffered_target = target;
  3563. target.clear();
  3564. auto handle = cli.open_stream("GET", c.path);
  3565. EXPECT_TRUE(handle.is_valid())
  3566. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3567. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3568. }
  3569. }
  3570. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3571. // The `set_path_encode(false)` contract — transmit the supplied target
  3572. // verbatim — must hold for the streaming API too.
  3573. Server svr;
  3574. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3575. std::string target;
  3576. svr.Get("/foo", [&](const Request &req, Response &res) {
  3577. target = req.target;
  3578. res.status = StatusCode::OK_200;
  3579. });
  3580. auto port = svr.bind_to_any_port(HOST);
  3581. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3582. auto se = detail::scope_exit([&] {
  3583. svr.stop();
  3584. thread.join();
  3585. ASSERT_FALSE(svr.is_running());
  3586. });
  3587. svr.wait_until_ready();
  3588. {
  3589. Client cli(HOST, port);
  3590. cli.set_path_encode(false);
  3591. auto handle = cli.open_stream("GET", expected_target);
  3592. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3593. EXPECT_EQ(expected_target, target);
  3594. }
  3595. }
  3596. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3597. // With path encoding enabled a CR/LF in the target is percent-encoded
  3598. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3599. // write_request_line still backstops `set_path_encode(false)`, which is
  3600. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3601. Server svr;
  3602. // Captured before routing: the decoded path contains a newline, which a
  3603. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3604. std::string target;
  3605. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3606. target = req.target;
  3607. res.status = StatusCode::OK_200;
  3608. return Server::HandlerResponse::Handled;
  3609. });
  3610. auto port = svr.bind_to_any_port(HOST);
  3611. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3612. auto se = detail::scope_exit([&] {
  3613. svr.stop();
  3614. thread.join();
  3615. ASSERT_FALSE(svr.is_running());
  3616. });
  3617. svr.wait_until_ready();
  3618. {
  3619. Client cli(HOST, port);
  3620. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3621. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3622. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3623. }
  3624. }
  3625. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3626. // Every control character is percent-encoded, not just CR/LF, so the target
  3627. // passes the request-target check in write_request_line.
  3628. Server svr;
  3629. std::string target;
  3630. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3631. target = req.target;
  3632. res.status = StatusCode::OK_200;
  3633. return Server::HandlerResponse::Handled;
  3634. });
  3635. auto port = svr.bind_to_any_port(HOST);
  3636. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3637. auto se = detail::scope_exit([&] {
  3638. svr.stop();
  3639. thread.join();
  3640. ASSERT_FALSE(svr.is_running());
  3641. });
  3642. svr.wait_until_ready();
  3643. {
  3644. Client cli(HOST, port);
  3645. auto res = cli.Get("/a\tb\x1b\x7f");
  3646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3647. EXPECT_EQ("/a%09b%1B%7F", target);
  3648. }
  3649. }
  3650. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3651. // Nothing may reach the wire: a raw CR/LF target would split the request
  3652. // line and inject headers.
  3653. Server svr;
  3654. // Pre-routing so that "not called" means nothing reached the server at all,
  3655. // rather than merely failing to match a handler pattern.
  3656. auto handler_called = false;
  3657. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3658. handler_called = true;
  3659. res.status = StatusCode::OK_200;
  3660. return Server::HandlerResponse::Handled;
  3661. });
  3662. auto port = svr.bind_to_any_port(HOST);
  3663. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3664. auto se = detail::scope_exit([&] {
  3665. svr.stop();
  3666. thread.join();
  3667. ASSERT_FALSE(svr.is_running());
  3668. });
  3669. svr.wait_until_ready();
  3670. {
  3671. Client cli(HOST, port);
  3672. cli.set_path_encode(false);
  3673. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3674. EXPECT_FALSE(handle.is_valid());
  3675. EXPECT_EQ(Error::Write, handle.error);
  3676. EXPECT_FALSE(handler_called);
  3677. }
  3678. }
  3679. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3680. // Which of the two branches runs is decided by whether the query component
  3681. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3682. // an empty query and must still fall back to building one from
  3683. // `req.params`, while a non-empty query must win over `req.params`.
  3684. Server svr;
  3685. std::string target;
  3686. svr.Get("/foo", [&](const Request &req, Response &res) {
  3687. target = req.target;
  3688. res.status = StatusCode::OK_200;
  3689. });
  3690. auto port = svr.bind_to_any_port(HOST);
  3691. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3692. auto se = detail::scope_exit([&] {
  3693. svr.stop();
  3694. thread.join();
  3695. ASSERT_FALSE(svr.is_running());
  3696. });
  3697. svr.wait_until_ready();
  3698. {
  3699. // Trailing `?` -> empty query component -> `req.params` is used.
  3700. Client cli(HOST, port);
  3701. Request req;
  3702. req.method = "GET";
  3703. req.path = "/foo?";
  3704. req.params.emplace("a", "1");
  3705. target.clear();
  3706. auto res = cli.send(req);
  3707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3708. EXPECT_EQ("/foo?a=1", target);
  3709. }
  3710. {
  3711. // Non-empty query in `req.path` -> `req.params` is not appended.
  3712. Client cli(HOST, port);
  3713. Request req;
  3714. req.method = "GET";
  3715. req.path = "/foo?b=2";
  3716. req.params.emplace("a", "1");
  3717. target.clear();
  3718. auto res = cli.send(req);
  3719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3720. EXPECT_EQ("/foo?b=2", target);
  3721. }
  3722. }
  3723. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3724. Server svr;
  3725. svr.Get("/", [](const Request &req, Response &) {
  3726. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3727. });
  3728. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3729. auto se = detail::scope_exit([&] {
  3730. svr.stop();
  3731. thread.join();
  3732. ASSERT_FALSE(svr.is_running());
  3733. });
  3734. svr.wait_until_ready();
  3735. {
  3736. Client cli(HOST, PORT);
  3737. cli.set_path_encode(false);
  3738. auto res = cli.Get("/?something=%0A");
  3739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3740. EXPECT_EQ(StatusCode::OK_200, res->status);
  3741. }
  3742. }
  3743. TEST(BindServerTest, BindDualStack) {
  3744. Server svr;
  3745. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3746. res.set_content("Hello World!", "text/plain");
  3747. });
  3748. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3749. auto se = detail::scope_exit([&] {
  3750. svr.stop();
  3751. thread.join();
  3752. ASSERT_FALSE(svr.is_running());
  3753. });
  3754. svr.wait_until_ready();
  3755. {
  3756. Client cli("127.0.0.1", PORT);
  3757. auto res = cli.Get("/1");
  3758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3759. EXPECT_EQ(StatusCode::OK_200, res->status);
  3760. EXPECT_EQ("Hello World!", res->body);
  3761. }
  3762. {
  3763. Client cli("::1", PORT);
  3764. auto res = cli.Get("/1");
  3765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3766. EXPECT_EQ(StatusCode::OK_200, res->status);
  3767. EXPECT_EQ("Hello World!", res->body);
  3768. }
  3769. }
  3770. TEST(BindServerTest, BindAndListenSeparately) {
  3771. Server svr;
  3772. int port = svr.bind_to_any_port("0.0.0.0");
  3773. ASSERT_TRUE(svr.is_valid());
  3774. ASSERT_TRUE(port > 0);
  3775. svr.stop();
  3776. }
  3777. // Reports whether anything is still listening on a loopback port. A plain
  3778. // connect() is used instead of a Client request because a socket left bound by
  3779. // mistake accepts the connection into its backlog and never answers, which
  3780. // would hang the test instead of failing it.
  3781. static bool is_loopback_port_accepting(int port) {
  3782. sockaddr_in addr{};
  3783. addr.sin_family = AF_INET;
  3784. addr.sin_port = htons(static_cast<uint16_t>(port));
  3785. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3786. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3787. EXPECT_NE(sock, INVALID_SOCKET);
  3788. if (sock == INVALID_SOCKET) { return false; }
  3789. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3790. static_cast<socklen_t>(sizeof(addr)));
  3791. detail::close_socket(sock);
  3792. return ret == 0;
  3793. }
  3794. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3795. Server svr;
  3796. auto port = svr.bind_to_any_port("127.0.0.1");
  3797. ASSERT_TRUE(port > 0);
  3798. svr.stop();
  3799. // bind_to_any_port() already called listen(2), so until stop() closed the
  3800. // descriptor the port kept accepting connections into the backlog. ASSERT
  3801. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3802. // below blocks forever in the accept loop.
  3803. ASSERT_FALSE(is_loopback_port_accepting(port));
  3804. // Nothing is left to accept on, so listen_after_bind() must report failure
  3805. // instead of returning success without ever serving.
  3806. EXPECT_FALSE(svr.listen_after_bind());
  3807. // The failed listen marks the server decommissioned, so a waiter returns
  3808. // instead of spinning forever.
  3809. svr.wait_until_ready();
  3810. }
  3811. #ifdef CPPHTTPLIB_SSL_ENABLED
  3812. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3813. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3814. CLIENT_CA_CERT_DIR);
  3815. int port = svr.bind_to_any_port("0.0.0.0");
  3816. ASSERT_TRUE(svr.is_valid());
  3817. ASSERT_TRUE(port > 0);
  3818. svr.stop();
  3819. }
  3820. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3821. // or a rejected CustomRoute() registration would not stop the server binding.
  3822. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3823. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3824. CLIENT_CA_CERT_DIR);
  3825. ASSERT_TRUE(svr.is_valid());
  3826. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3827. EXPECT_FALSE(svr.is_valid());
  3828. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3829. }
  3830. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3831. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3832. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3833. int port = svr.bind_to_any_port("0.0.0.0");
  3834. ASSERT_TRUE(svr.is_valid());
  3835. ASSERT_TRUE(port > 0);
  3836. svr.stop();
  3837. }
  3838. TEST(BindServerTest, UpdateCertsPem) {
  3839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3840. int port = svr.bind_to_any_port("0.0.0.0");
  3841. ASSERT_TRUE(svr.is_valid());
  3842. ASSERT_TRUE(port > 0);
  3843. // Read PEM files
  3844. std::string cert_pem, key_pem, ca_pem;
  3845. read_file(SERVER_CERT_FILE, cert_pem);
  3846. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3847. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3848. // Update server certificates using PEM API
  3849. ASSERT_TRUE(
  3850. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3851. ASSERT_TRUE(svr.is_valid());
  3852. svr.stop();
  3853. }
  3854. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3855. // Start server with client CA (enables client auth)
  3856. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3857. ASSERT_TRUE(svr.is_valid());
  3858. bool handler_called = false;
  3859. svr.Get("/test", [&](const Request &req, Response &res) {
  3860. handler_called = true;
  3861. // Verify client certificate is present
  3862. auto cert = req.peer_cert();
  3863. EXPECT_TRUE(static_cast<bool>(cert));
  3864. res.set_content("ok", "text/plain");
  3865. });
  3866. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3867. auto se = detail::scope_exit([&] {
  3868. svr.stop();
  3869. t.join();
  3870. ASSERT_FALSE(svr.is_running());
  3871. });
  3872. svr.wait_until_ready();
  3873. // Read PEM files
  3874. std::string cert_pem, key_pem, ca_pem;
  3875. read_file(SERVER_CERT_FILE, cert_pem);
  3876. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3877. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3878. // Update server certificates and client CA using PEM API while server running
  3879. ASSERT_TRUE(
  3880. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3881. // Connect with client certificate
  3882. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3883. cli.enable_server_certificate_verification(false);
  3884. cli.set_connection_timeout(30);
  3885. auto res = cli.Get("/test");
  3886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3887. ASSERT_EQ(StatusCode::OK_200, res->status);
  3888. ASSERT_TRUE(handler_called);
  3889. EXPECT_EQ("ok", res->body);
  3890. }
  3891. #endif
  3892. TEST(ErrorHandlerTest, ContentLength) {
  3893. Server svr;
  3894. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3895. res.status = StatusCode::OK_200;
  3896. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3897. "text/html"); // <= Content-Length still 13
  3898. });
  3899. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3900. res.set_content("Hello World!\n", "text/plain");
  3901. res.status = 524;
  3902. });
  3903. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3904. auto se = detail::scope_exit([&] {
  3905. svr.stop();
  3906. thread.join();
  3907. ASSERT_FALSE(svr.is_running());
  3908. });
  3909. svr.wait_until_ready();
  3910. {
  3911. Client cli(HOST, PORT);
  3912. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3914. EXPECT_EQ(StatusCode::OK_200, res->status);
  3915. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3916. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3917. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3918. }
  3919. }
  3920. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3921. TEST(ExceptionTest, WithoutExceptionHandler) {
  3922. Server svr;
  3923. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3924. throw std::runtime_error("exception...");
  3925. });
  3926. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3927. throw std::runtime_error("exception\r\n...");
  3928. });
  3929. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3930. auto se = detail::scope_exit([&] {
  3931. svr.stop();
  3932. listen_thread.join();
  3933. ASSERT_FALSE(svr.is_running());
  3934. });
  3935. svr.wait_until_ready();
  3936. Client cli("localhost", PORT);
  3937. {
  3938. auto res = cli.Get("/exception");
  3939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3940. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3941. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3942. }
  3943. {
  3944. auto res = cli.Get("/unknown");
  3945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3946. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3947. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3948. }
  3949. }
  3950. TEST(ExceptionTest, WithExceptionHandler) {
  3951. Server svr;
  3952. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3953. std::exception_ptr ep) {
  3954. EXPECT_FALSE(ep == nullptr);
  3955. try {
  3956. std::rethrow_exception(ep);
  3957. } catch (std::exception &e) {
  3958. EXPECT_EQ("abc", std::string(e.what()));
  3959. } catch (...) {}
  3960. res.status = StatusCode::InternalServerError_500;
  3961. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3962. "text/html"); // <= Content-Length still 13 at this point
  3963. });
  3964. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3965. res.set_content("Hello World!\n", "text/plain");
  3966. throw std::runtime_error("abc");
  3967. });
  3968. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3969. auto se = detail::scope_exit([&] {
  3970. svr.stop();
  3971. thread.join();
  3972. ASSERT_FALSE(svr.is_running());
  3973. });
  3974. svr.wait_until_ready();
  3975. for (size_t i = 0; i < 10; i++) {
  3976. Client cli(HOST, PORT);
  3977. for (size_t j = 0; j < 100; j++) {
  3978. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3980. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3981. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3982. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3983. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3984. }
  3985. cli.set_keep_alive(true);
  3986. for (size_t j = 0; j < 100; j++) {
  3987. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3989. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3990. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3991. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3992. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3993. }
  3994. }
  3995. }
  3996. TEST(ExceptionTest, AndErrorHandler) {
  3997. Server svr;
  3998. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3999. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4000. });
  4001. svr.set_exception_handler(
  4002. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4003. EXPECT_FALSE(ep == nullptr);
  4004. try {
  4005. std::rethrow_exception(ep);
  4006. } catch (std::exception &e) {
  4007. res.set_content(e.what(), "text/html");
  4008. } catch (...) {}
  4009. res.status = StatusCode::InternalServerError_500;
  4010. });
  4011. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4012. throw std::runtime_error("EXCEPTION");
  4013. });
  4014. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4015. res.set_content("ERROR", "text/html");
  4016. res.status = StatusCode::InternalServerError_500;
  4017. });
  4018. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4019. auto se = detail::scope_exit([&] {
  4020. svr.stop();
  4021. thread.join();
  4022. ASSERT_FALSE(svr.is_running());
  4023. });
  4024. svr.wait_until_ready();
  4025. Client cli(HOST, PORT);
  4026. {
  4027. auto res = cli.Get("/exception");
  4028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4029. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4030. EXPECT_EQ("EXCEPTION", res->body);
  4031. }
  4032. {
  4033. auto res = cli.Get("/error");
  4034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4035. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4036. EXPECT_EQ("ERROR", res->body);
  4037. }
  4038. {
  4039. auto res = cli.Get("/invalid");
  4040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4041. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4042. EXPECT_EQ("NOT_FOUND", res->body);
  4043. }
  4044. }
  4045. #endif
  4046. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4047. // process_request() wraps only routing() in a try/catch, so an exception from
  4048. // any other user callback used to unwind into the task queue - which does not
  4049. // catch - and terminate the process. Each test below runs the server on a
  4050. // single worker thread: a guard that catches the exception but still loses the
  4051. // thread would otherwise be hidden by a spare worker serving the follow-up
  4052. // request. Note that a regression here aborts the whole test binary rather
  4053. // than failing one test.
  4054. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4055. Server svr;
  4056. svr.new_task_queue = [] { return new ThreadPool(1); };
  4057. std::atomic<int> reported{0};
  4058. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4059. if (err == Error::UserCallbackException) { reported++; }
  4060. });
  4061. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4062. res.set_content_provider(
  4063. 1024, "text/plain",
  4064. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4065. sink.write("hello", 5);
  4066. throw std::runtime_error("from the content provider");
  4067. });
  4068. });
  4069. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4070. res.set_content("ok", "text/plain");
  4071. });
  4072. auto port = svr.bind_to_any_port(HOST);
  4073. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4074. auto se = detail::scope_exit([&] {
  4075. svr.stop();
  4076. listen_thread.join();
  4077. ASSERT_FALSE(svr.is_running());
  4078. });
  4079. svr.wait_until_ready();
  4080. {
  4081. Client cli(HOST, port);
  4082. cli.set_read_timeout(5, 0);
  4083. EXPECT_FALSE(cli.Get("/throw"));
  4084. }
  4085. EXPECT_TRUE(svr.is_running());
  4086. EXPECT_EQ(1, reported.load());
  4087. // A request on a fresh connection is still served.
  4088. {
  4089. Client cli(HOST, port);
  4090. auto res = cli.Get("/ok");
  4091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4092. EXPECT_EQ(StatusCode::OK_200, res->status);
  4093. EXPECT_EQ("ok", res->body);
  4094. }
  4095. }
  4096. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4097. Server svr;
  4098. svr.new_task_queue = [] { return new ThreadPool(1); };
  4099. std::atomic<bool> should_throw{true};
  4100. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4101. res.set_content("hi", "text/plain");
  4102. });
  4103. svr.set_post_routing_handler(
  4104. [&](const Request & /*req*/, Response & /*res*/) {
  4105. if (should_throw) {
  4106. throw std::runtime_error("from the post-routing handler");
  4107. }
  4108. });
  4109. auto port = svr.bind_to_any_port(HOST);
  4110. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4111. auto se = detail::scope_exit([&] {
  4112. svr.stop();
  4113. listen_thread.join();
  4114. ASSERT_FALSE(svr.is_running());
  4115. });
  4116. svr.wait_until_ready();
  4117. {
  4118. Client cli(HOST, port);
  4119. cli.set_read_timeout(5, 0);
  4120. EXPECT_FALSE(cli.Get("/hi"));
  4121. }
  4122. EXPECT_TRUE(svr.is_running());
  4123. should_throw = false;
  4124. {
  4125. Client cli(HOST, port);
  4126. auto res = cli.Get("/hi");
  4127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4128. EXPECT_EQ(StatusCode::OK_200, res->status);
  4129. EXPECT_EQ("hi", res->body);
  4130. }
  4131. }
  4132. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4133. // The guard reports the caught exception through the error logger, which is
  4134. // a user callback too. A logger that throws has to be contained as well, or
  4135. // the process would terminate from inside the catch.
  4136. Server svr;
  4137. svr.new_task_queue = [] { return new ThreadPool(1); };
  4138. std::atomic<int> reported{0};
  4139. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4140. if (err == Error::UserCallbackException) {
  4141. reported++;
  4142. throw std::runtime_error("from the error logger");
  4143. }
  4144. });
  4145. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4146. res.set_content_provider(
  4147. 1024, "text/plain",
  4148. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4149. sink.write("hello", 5);
  4150. throw std::runtime_error("from the content provider");
  4151. });
  4152. });
  4153. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4154. res.set_content("ok", "text/plain");
  4155. });
  4156. auto port = svr.bind_to_any_port(HOST);
  4157. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4158. auto se = detail::scope_exit([&] {
  4159. svr.stop();
  4160. listen_thread.join();
  4161. ASSERT_FALSE(svr.is_running());
  4162. });
  4163. svr.wait_until_ready();
  4164. {
  4165. Client cli(HOST, port);
  4166. cli.set_read_timeout(5, 0);
  4167. EXPECT_FALSE(cli.Get("/throw"));
  4168. }
  4169. EXPECT_TRUE(svr.is_running());
  4170. EXPECT_EQ(1, reported.load());
  4171. {
  4172. Client cli(HOST, port);
  4173. auto res = cli.Get("/ok");
  4174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4175. EXPECT_EQ(StatusCode::OK_200, res->status);
  4176. EXPECT_EQ("ok", res->body);
  4177. }
  4178. }
  4179. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4180. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4181. // so the exception unwinds through the ws::WebSocket object on its way to
  4182. // the guard. None of the HTTP cases above cross that.
  4183. Server svr;
  4184. svr.new_task_queue = [] { return new ThreadPool(1); };
  4185. std::atomic<int> reported{0};
  4186. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4187. if (err == Error::UserCallbackException) { reported++; }
  4188. });
  4189. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4190. throw std::runtime_error("from the WebSocket handler");
  4191. });
  4192. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4193. res.set_content("ok", "text/plain");
  4194. });
  4195. auto port = svr.bind_to_any_port(HOST);
  4196. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4197. auto se = detail::scope_exit([&] {
  4198. svr.stop();
  4199. listen_thread.join();
  4200. ASSERT_FALSE(svr.is_running());
  4201. });
  4202. svr.wait_until_ready();
  4203. {
  4204. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4205. "/ws");
  4206. auto res = client.connect();
  4207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4208. // The server dropped the connection instead of dying.
  4209. std::string msg;
  4210. EXPECT_FALSE(client.read(msg));
  4211. client.close();
  4212. }
  4213. EXPECT_TRUE(svr.is_running());
  4214. EXPECT_EQ(1, reported.load());
  4215. {
  4216. Client cli(HOST, port);
  4217. auto res = cli.Get("/ok");
  4218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4219. EXPECT_EQ(StatusCode::OK_200, res->status);
  4220. EXPECT_EQ("ok", res->body);
  4221. }
  4222. }
  4223. #ifdef CPPHTTPLIB_SSL_ENABLED
  4224. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4225. // SSLServer::process_and_close_socket() is a separate overload with its own
  4226. // guard, so it is exercised on its own.
  4227. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4228. ASSERT_TRUE(svr.is_valid());
  4229. svr.new_task_queue = [] { return new ThreadPool(1); };
  4230. std::atomic<int> reported{0};
  4231. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4232. if (err == Error::UserCallbackException) { reported++; }
  4233. });
  4234. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4235. res.set_content_provider(
  4236. 1024, "text/plain",
  4237. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4238. sink.write("hello", 5);
  4239. throw std::runtime_error("from the content provider");
  4240. });
  4241. });
  4242. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4243. res.set_content("ok", "text/plain");
  4244. });
  4245. auto port = svr.bind_to_any_port(HOST);
  4246. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4247. auto se = detail::scope_exit([&] {
  4248. svr.stop();
  4249. listen_thread.join();
  4250. ASSERT_FALSE(svr.is_running());
  4251. });
  4252. svr.wait_until_ready();
  4253. {
  4254. SSLClient cli(HOST, port);
  4255. cli.enable_server_certificate_verification(false);
  4256. cli.set_read_timeout(5, 0);
  4257. EXPECT_FALSE(cli.Get("/throw"));
  4258. }
  4259. EXPECT_TRUE(svr.is_running());
  4260. EXPECT_EQ(1, reported.load());
  4261. {
  4262. SSLClient cli(HOST, port);
  4263. cli.enable_server_certificate_verification(false);
  4264. auto res = cli.Get("/ok");
  4265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4266. EXPECT_EQ(StatusCode::OK_200, res->status);
  4267. EXPECT_EQ("ok", res->body);
  4268. }
  4269. }
  4270. #endif
  4271. #endif
  4272. TEST(NoContentTest, ContentLength) {
  4273. Server svr;
  4274. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4275. res.status = StatusCode::NoContent_204;
  4276. });
  4277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4278. auto se = detail::scope_exit([&] {
  4279. svr.stop();
  4280. thread.join();
  4281. ASSERT_FALSE(svr.is_running());
  4282. });
  4283. svr.wait_until_ready();
  4284. {
  4285. Client cli(HOST, PORT);
  4286. auto res = cli.Get("/hi");
  4287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4288. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4289. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4290. }
  4291. }
  4292. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4293. #ifdef CPPHTTPLIB_SSL_ENABLED
  4294. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4295. ASSERT_TRUE(svr.is_valid());
  4296. #else
  4297. Server svr;
  4298. #endif
  4299. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4300. if (req.path == "/routing_handler") {
  4301. res.set_header("PRE_ROUTING", "on");
  4302. res.set_content("Routing Handler", "text/plain");
  4303. return httplib::Server::HandlerResponse::Handled;
  4304. }
  4305. return httplib::Server::HandlerResponse::Unhandled;
  4306. });
  4307. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4308. res.set_content("Error", "text/html");
  4309. });
  4310. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4311. if (req.path == "/routing_handler") {
  4312. res.set_header("POST_ROUTING", "on");
  4313. }
  4314. });
  4315. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4316. res.set_content("Hello World!\n", "text/plain");
  4317. });
  4318. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4319. auto se = detail::scope_exit([&] {
  4320. svr.stop();
  4321. thread.join();
  4322. ASSERT_FALSE(svr.is_running());
  4323. });
  4324. svr.wait_until_ready();
  4325. {
  4326. #ifdef CPPHTTPLIB_SSL_ENABLED
  4327. SSLClient cli(HOST, PORT);
  4328. cli.enable_server_certificate_verification(false);
  4329. #else
  4330. Client cli(HOST, PORT);
  4331. #endif
  4332. auto res = cli.Get("/routing_handler");
  4333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4334. EXPECT_EQ(StatusCode::OK_200, res->status);
  4335. EXPECT_EQ("Routing Handler", res->body);
  4336. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4337. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4338. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4339. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4340. }
  4341. {
  4342. #ifdef CPPHTTPLIB_SSL_ENABLED
  4343. SSLClient cli(HOST, PORT);
  4344. cli.enable_server_certificate_verification(false);
  4345. #else
  4346. Client cli(HOST, PORT);
  4347. #endif
  4348. auto res = cli.Get("/hi");
  4349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4350. EXPECT_EQ(StatusCode::OK_200, res->status);
  4351. EXPECT_EQ("Hello World!\n", res->body);
  4352. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4353. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4354. }
  4355. {
  4356. #ifdef CPPHTTPLIB_SSL_ENABLED
  4357. SSLClient cli(HOST, PORT);
  4358. cli.enable_server_certificate_verification(false);
  4359. #else
  4360. Client cli(HOST, PORT);
  4361. #endif
  4362. auto res = cli.Get("/aaa");
  4363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4364. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4365. EXPECT_EQ("Error", res->body);
  4366. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4367. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4368. }
  4369. }
  4370. TEST(RequestHandlerTest, PreRequestHandler) {
  4371. auto route_path = "/user/:user";
  4372. Server svr;
  4373. svr.Get("/hi", [](const Request &, Response &res) {
  4374. res.set_content("hi", "text/plain");
  4375. });
  4376. svr.Get(route_path, [](const Request &req, Response &res) {
  4377. res.set_content(req.path_params.at("user"), "text/plain");
  4378. });
  4379. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4380. if (req.matched_route == route_path) {
  4381. auto user = req.path_params.at("user");
  4382. if (user != "john") {
  4383. res.status = StatusCode::Forbidden_403;
  4384. res.set_content("error", "text/html");
  4385. return Server::HandlerResponse::Handled;
  4386. }
  4387. }
  4388. return Server::HandlerResponse::Unhandled;
  4389. });
  4390. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4391. auto se = detail::scope_exit([&] {
  4392. svr.stop();
  4393. thread.join();
  4394. ASSERT_FALSE(svr.is_running());
  4395. });
  4396. svr.wait_until_ready();
  4397. Client cli(HOST, PORT);
  4398. {
  4399. auto res = cli.Get("/hi");
  4400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4401. EXPECT_EQ(StatusCode::OK_200, res->status);
  4402. EXPECT_EQ("hi", res->body);
  4403. }
  4404. {
  4405. auto res = cli.Get("/user/john");
  4406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4407. EXPECT_EQ(StatusCode::OK_200, res->status);
  4408. EXPECT_EQ("john", res->body);
  4409. }
  4410. {
  4411. auto res = cli.Get("/user/invalid-user");
  4412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4413. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4414. EXPECT_EQ("error", res->body);
  4415. }
  4416. }
  4417. // The pre-request handler must run before the request body is read, so a
  4418. // rejected request never forces the server to buffer a (potentially large)
  4419. // body. Here the posted body is larger than the payload limit: if the body
  4420. // were read first the server would answer 413, but because the pre-request
  4421. // handler runs first it answers 403 and the body is never read.
  4422. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4423. Server svr;
  4424. svr.set_payload_max_length(8);
  4425. auto handler_ran = false;
  4426. svr.Post("/reject", [&](const Request &req, Response &res) {
  4427. handler_ran = true;
  4428. res.set_content(req.body, "text/plain");
  4429. });
  4430. svr.Post("/accept", [](const Request &req, Response &res) {
  4431. res.set_content(req.body, "text/plain");
  4432. });
  4433. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4434. if (req.matched_route == "/reject") {
  4435. res.status = StatusCode::Forbidden_403;
  4436. res.set_content("denied", "text/plain");
  4437. return Server::HandlerResponse::Handled;
  4438. }
  4439. return Server::HandlerResponse::Unhandled;
  4440. });
  4441. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4442. auto se = detail::scope_exit([&] {
  4443. svr.stop();
  4444. thread.join();
  4445. ASSERT_FALSE(svr.is_running());
  4446. });
  4447. svr.wait_until_ready();
  4448. Client cli(HOST, PORT);
  4449. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4450. // rejects with 403 before the body is read, so 413 is never reached.
  4451. {
  4452. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4454. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4455. EXPECT_EQ("denied", res->body);
  4456. EXPECT_FALSE(handler_ran);
  4457. }
  4458. // An approved route still reads the body and enforces the payload limit.
  4459. {
  4460. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4462. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4463. }
  4464. }
  4465. TEST(UserDataTest, BasicOperations) {
  4466. httplib::UserData ud;
  4467. // Initially empty
  4468. EXPECT_FALSE(ud.has("key"));
  4469. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4470. // set and get
  4471. ud.set("key", 42);
  4472. EXPECT_TRUE(ud.has("key"));
  4473. auto *p = ud.get<int>("key");
  4474. ASSERT_NE(nullptr, p);
  4475. EXPECT_EQ(42, *p);
  4476. // Type mismatch → nullptr
  4477. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4478. // Overwrite with different type
  4479. ud.set("key", std::string("hello"));
  4480. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4481. auto *s = ud.get<std::string>("key");
  4482. ASSERT_NE(nullptr, s);
  4483. EXPECT_EQ("hello", *s);
  4484. // erase
  4485. ud.erase("key");
  4486. EXPECT_FALSE(ud.has("key"));
  4487. // clear
  4488. ud.set("a", 1);
  4489. ud.set("b", 2);
  4490. ud.clear();
  4491. EXPECT_FALSE(ud.has("a"));
  4492. EXPECT_FALSE(ud.has("b"));
  4493. }
  4494. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4495. struct AuthCtx {
  4496. std::string user_id;
  4497. };
  4498. Server svr;
  4499. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4500. res.user_data.set("auth", AuthCtx{"alice"});
  4501. return Server::HandlerResponse::Unhandled;
  4502. });
  4503. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4504. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4505. ASSERT_NE(nullptr, ctx);
  4506. res.set_content("Hello " + ctx->user_id, "text/plain");
  4507. });
  4508. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4509. auto se = detail::scope_exit([&] {
  4510. svr.stop();
  4511. thread.join();
  4512. ASSERT_FALSE(svr.is_running());
  4513. });
  4514. svr.wait_until_ready();
  4515. Client cli(HOST, PORT);
  4516. auto res = cli.Get("/me");
  4517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4518. EXPECT_EQ(StatusCode::OK_200, res->status);
  4519. EXPECT_EQ("Hello alice", res->body);
  4520. }
  4521. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4522. struct RoleCtx {
  4523. std::string role;
  4524. };
  4525. Server svr;
  4526. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4527. res.user_data.set("role", RoleCtx{"admin"});
  4528. return Server::HandlerResponse::Unhandled;
  4529. });
  4530. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4531. auto *ctx = res.user_data.get<RoleCtx>("role");
  4532. ASSERT_NE(nullptr, ctx);
  4533. res.set_content(ctx->role, "text/plain");
  4534. });
  4535. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4536. auto se = detail::scope_exit([&] {
  4537. svr.stop();
  4538. thread.join();
  4539. ASSERT_FALSE(svr.is_running());
  4540. });
  4541. svr.wait_until_ready();
  4542. Client cli(HOST, PORT);
  4543. auto res = cli.Get("/role");
  4544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4545. EXPECT_EQ(StatusCode::OK_200, res->status);
  4546. EXPECT_EQ("admin", res->body);
  4547. }
  4548. TEST(InvalidFormatTest, StatusCode) {
  4549. Server svr;
  4550. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4551. res.set_content("Hello World!\n", "text/plain");
  4552. res.status = 9999; // Status should be a three-digit code...
  4553. });
  4554. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4555. auto se = detail::scope_exit([&] {
  4556. svr.stop();
  4557. thread.join();
  4558. ASSERT_FALSE(svr.is_running());
  4559. });
  4560. svr.wait_until_ready();
  4561. {
  4562. Client cli(HOST, PORT);
  4563. auto res = cli.Get("/hi");
  4564. ASSERT_FALSE(res);
  4565. }
  4566. }
  4567. TEST(URLFragmentTest, WithFragment) {
  4568. Server svr;
  4569. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4570. EXPECT_TRUE(req.target == "/hi");
  4571. });
  4572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4573. auto se = detail::scope_exit([&] {
  4574. svr.stop();
  4575. thread.join();
  4576. ASSERT_FALSE(svr.is_running());
  4577. });
  4578. svr.wait_until_ready();
  4579. {
  4580. Client cli(HOST, PORT);
  4581. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4582. EXPECT_TRUE(res);
  4583. EXPECT_EQ(StatusCode::OK_200, res->status);
  4584. res = cli.Get("/hi%23key1=val1=key2=val2");
  4585. EXPECT_TRUE(res);
  4586. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4587. }
  4588. }
  4589. TEST(HeaderWriter, SetHeaderWriter) {
  4590. Server svr;
  4591. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4592. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4593. return detail::write_headers(strm, hdrs);
  4594. });
  4595. svr.Get("/hi", [](const Request &req, Response &res) {
  4596. auto it = req.headers.find("CustomClientHeader");
  4597. EXPECT_TRUE(it != req.headers.end());
  4598. EXPECT_EQ(it->second, "CustomClientValue");
  4599. res.set_content("Hello World!\n", "text/plain");
  4600. });
  4601. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4602. auto se = detail::scope_exit([&] {
  4603. svr.stop();
  4604. thread.join();
  4605. ASSERT_FALSE(svr.is_running());
  4606. });
  4607. svr.wait_until_ready();
  4608. {
  4609. Client cli(HOST, PORT);
  4610. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4611. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4612. return detail::write_headers(strm, hdrs);
  4613. });
  4614. auto res = cli.Get("/hi");
  4615. EXPECT_TRUE(res);
  4616. EXPECT_EQ(StatusCode::OK_200, res->status);
  4617. auto it = res->headers.find("CustomServerHeader");
  4618. EXPECT_TRUE(it != res->headers.end());
  4619. EXPECT_EQ(it->second, "CustomServerValue");
  4620. }
  4621. }
  4622. class ServerTest : public ::testing::Test {
  4623. protected:
  4624. ServerTest()
  4625. : cli_(HOST, PORT)
  4626. #ifdef CPPHTTPLIB_SSL_ENABLED
  4627. ,
  4628. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4629. #endif
  4630. {
  4631. #ifdef CPPHTTPLIB_SSL_ENABLED
  4632. cli_.enable_server_certificate_verification(false);
  4633. #endif
  4634. // Allow LARGE_DATA (100MB) responses
  4635. cli_.set_payload_max_length(200 * 1024 * 1024);
  4636. }
  4637. virtual void SetUp() {
  4638. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4639. svr_.set_payload_max_length(200 * 1024 * 1024);
  4640. svr_.set_mount_point("/", "./www");
  4641. svr_.set_mount_point("/mount", "./www2");
  4642. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4643. svr_.Get("/hi",
  4644. [&](const Request & /*req*/, Response &res) {
  4645. res.set_content("Hello World!", "text/plain");
  4646. })
  4647. .Get("/file_content",
  4648. [&](const Request & /*req*/, Response &res) {
  4649. res.set_file_content("./www/dir/test.html");
  4650. })
  4651. .Get("/file_content_with_content_type",
  4652. [&](const Request & /*req*/, Response &res) {
  4653. res.set_file_content("./www/file", "text/plain");
  4654. })
  4655. .Get("/invalid_file_content",
  4656. [&](const Request & /*req*/, Response &res) {
  4657. res.set_file_content("./www/dir/invalid_file_path");
  4658. })
  4659. .Get("/http_response_splitting",
  4660. [&](const Request & /*req*/, Response &res) {
  4661. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4662. EXPECT_EQ(0U, res.headers.size());
  4663. EXPECT_FALSE(res.has_header("a"));
  4664. res.set_header("a", "1\nSet-Cookie: a=1");
  4665. EXPECT_EQ(0U, res.headers.size());
  4666. EXPECT_FALSE(res.has_header("a"));
  4667. res.set_header("a", "1\rSet-Cookie: a=1");
  4668. EXPECT_EQ(0U, res.headers.size());
  4669. EXPECT_FALSE(res.has_header("a"));
  4670. res.set_header("a\r\nb", "0");
  4671. EXPECT_EQ(0U, res.headers.size());
  4672. EXPECT_FALSE(res.has_header("a"));
  4673. res.set_header("a\rb", "0");
  4674. EXPECT_EQ(0U, res.headers.size());
  4675. EXPECT_FALSE(res.has_header("a"));
  4676. res.set_header("a\nb", "0");
  4677. EXPECT_EQ(0U, res.headers.size());
  4678. EXPECT_FALSE(res.has_header("a"));
  4679. res.set_redirect("1\r\nSet-Cookie: a=1");
  4680. EXPECT_EQ(0U, res.headers.size());
  4681. EXPECT_FALSE(res.has_header("Location"));
  4682. })
  4683. .Get("/slow",
  4684. [&](const Request & /*req*/, Response &res) {
  4685. std::this_thread::sleep_for(std::chrono::seconds(4));
  4686. res.set_content("slow", "text/plain");
  4687. })
  4688. #if 0
  4689. .Post("/slowpost",
  4690. [&](const Request & /*req*/, Response &res) {
  4691. std::this_thread::sleep_for(std::chrono::seconds(2));
  4692. res.set_content("slow", "text/plain");
  4693. })
  4694. #endif
  4695. .Get("/remote_addr",
  4696. [&](const Request &req, Response &res) {
  4697. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4698. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4699. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4700. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4701. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4702. #endif
  4703. res.set_content(req.remote_addr, "text/plain");
  4704. })
  4705. .Get("/local_addr",
  4706. [&](const Request &req, Response &res) {
  4707. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4708. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4709. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4710. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4711. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4712. #endif
  4713. auto local_addr = req.local_addr;
  4714. auto local_port = std::to_string(req.local_port);
  4715. res.set_content(local_addr.append(":").append(local_port),
  4716. "text/plain");
  4717. })
  4718. .Get("/endwith%",
  4719. [&](const Request & /*req*/, Response &res) {
  4720. res.set_content("Hello World!", "text/plain");
  4721. })
  4722. .Get("/a\\+\\+b",
  4723. [&](const Request &req, Response &res) {
  4724. ASSERT_TRUE(req.has_param("a +b"));
  4725. auto val = req.get_param_value("a +b");
  4726. res.set_content(val, "text/plain");
  4727. })
  4728. .Get("/", [&](const Request & /*req*/,
  4729. Response &res) { res.set_redirect("/hi"); })
  4730. .Post("/1",
  4731. [](const Request & /*req*/, Response &res) {
  4732. res.set_redirect("/2", StatusCode::SeeOther_303);
  4733. })
  4734. .Get("/2",
  4735. [](const Request & /*req*/, Response &res) {
  4736. res.set_content("redirected.", "text/plain");
  4737. res.status = StatusCode::OK_200;
  4738. })
  4739. .Post("/person",
  4740. [&](const Request &req, Response &res) {
  4741. if (req.has_param("name") && req.has_param("note")) {
  4742. persons_[req.get_param_value("name")] =
  4743. req.get_param_value("note");
  4744. } else {
  4745. res.status = StatusCode::BadRequest_400;
  4746. }
  4747. })
  4748. .Put("/person",
  4749. [&](const Request &req, Response &res) {
  4750. if (req.has_param("name") && req.has_param("note")) {
  4751. persons_[req.get_param_value("name")] =
  4752. req.get_param_value("note");
  4753. } else {
  4754. res.status = StatusCode::BadRequest_400;
  4755. }
  4756. })
  4757. .Get("/person/(.*)",
  4758. [&](const Request &req, Response &res) {
  4759. string name = req.matches[1];
  4760. if (persons_.find(name) != persons_.end()) {
  4761. auto note = persons_[name];
  4762. res.set_content(note, "text/plain");
  4763. } else {
  4764. res.status = StatusCode::NotFound_404;
  4765. }
  4766. })
  4767. .Delete("/person",
  4768. [&](const Request &req, Response &res) {
  4769. if (req.has_param("name")) {
  4770. string name = req.get_param_value("name");
  4771. if (persons_.find(name) != persons_.end()) {
  4772. persons_.erase(name);
  4773. res.set_content("DELETED", "text/plain");
  4774. } else {
  4775. res.status = StatusCode::NotFound_404;
  4776. }
  4777. } else {
  4778. res.status = StatusCode::BadRequest_400;
  4779. }
  4780. })
  4781. .Post("/x-www-form-urlencoded-json",
  4782. [&](const Request &req, Response &res) {
  4783. auto json = req.get_param_value("json");
  4784. ASSERT_EQ(JSON_DATA, json);
  4785. res.set_content(json, "appliation/json");
  4786. res.status = StatusCode::OK_200;
  4787. })
  4788. .Get("/streamed-chunked",
  4789. [&](const Request & /*req*/, Response &res) {
  4790. res.set_chunked_content_provider(
  4791. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4792. sink.os << "123";
  4793. sink.os << "456";
  4794. sink.os << "789";
  4795. sink.done();
  4796. return true;
  4797. });
  4798. })
  4799. .Get("/streamed-chunked-with-prohibited-trailer",
  4800. [&](const Request & /*req*/, Response &res) {
  4801. auto i = new int(0);
  4802. // Declare both a prohibited trailer (Content-Length) and an
  4803. // allowed one
  4804. res.set_header("Trailer", "Content-Length, X-Allowed");
  4805. res.set_chunked_content_provider(
  4806. "text/plain",
  4807. [i](size_t /*offset*/, DataSink &sink) {
  4808. switch (*i) {
  4809. case 0: sink.os << "123"; break;
  4810. case 1: sink.os << "456"; break;
  4811. case 2: sink.os << "789"; break;
  4812. case 3: {
  4813. sink.done_with_trailer(
  4814. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4815. } break;
  4816. }
  4817. (*i)++;
  4818. return true;
  4819. },
  4820. [i](bool success) {
  4821. EXPECT_TRUE(success);
  4822. delete i;
  4823. });
  4824. })
  4825. .Get("/streamed-chunked2",
  4826. [&](const Request & /*req*/, Response &res) {
  4827. auto i = new int(0);
  4828. res.set_chunked_content_provider(
  4829. "text/plain",
  4830. [i](size_t /*offset*/, DataSink &sink) {
  4831. switch (*i) {
  4832. case 0: sink.os << "123"; break;
  4833. case 1: sink.os << "456"; break;
  4834. case 2: sink.os << "789"; break;
  4835. case 3: sink.done(); break;
  4836. }
  4837. (*i)++;
  4838. return true;
  4839. },
  4840. [i](bool success) {
  4841. EXPECT_TRUE(success);
  4842. delete i;
  4843. });
  4844. })
  4845. .Get("/streamed-chunked-with-trailer",
  4846. [&](const Request & /*req*/, Response &res) {
  4847. auto i = new int(0);
  4848. res.set_header("Trailer", "Dummy1, Dummy2");
  4849. res.set_chunked_content_provider(
  4850. "text/plain",
  4851. [i](size_t /*offset*/, DataSink &sink) {
  4852. switch (*i) {
  4853. case 0: sink.os << "123"; break;
  4854. case 1: sink.os << "456"; break;
  4855. case 2: sink.os << "789"; break;
  4856. case 3: {
  4857. sink.done_with_trailer(
  4858. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4859. } break;
  4860. }
  4861. (*i)++;
  4862. return true;
  4863. },
  4864. [i](bool success) {
  4865. EXPECT_TRUE(success);
  4866. delete i;
  4867. });
  4868. })
  4869. .Get("/streamed",
  4870. [&](const Request & /*req*/, Response &res) {
  4871. res.set_content_provider(
  4872. 6, "text/plain",
  4873. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4874. sink.os << (offset < 3 ? "a" : "b");
  4875. return true;
  4876. });
  4877. })
  4878. .Get("/streamed-without-length",
  4879. [&](const Request & /*req*/, Response &res) {
  4880. auto data = new std::string("abcdefg");
  4881. res.set_content_provider(
  4882. "text/plain",
  4883. [data](size_t offset, DataSink &sink) {
  4884. if (offset < data->size()) {
  4885. sink.os << data->substr(offset);
  4886. }
  4887. sink.done();
  4888. return true;
  4889. },
  4890. [data](bool success) {
  4891. EXPECT_TRUE(success);
  4892. delete data;
  4893. });
  4894. })
  4895. .Get("/streamed-with-range",
  4896. [&](const Request &req, Response &res) {
  4897. auto data = new std::string("abcdefg");
  4898. // An explicit status keeps the server from picking the 206 it
  4899. // would otherwise choose for a ranged request, so the response
  4900. // is not a partial representation.
  4901. auto status = req.get_param_value("status");
  4902. if (status == "200") {
  4903. res.status = StatusCode::OK_200;
  4904. } else if (status == "403") {
  4905. res.status = StatusCode::Forbidden_403;
  4906. }
  4907. res.set_content_provider(
  4908. data->size(), "text/plain",
  4909. [data](size_t offset, size_t length, DataSink &sink) {
  4910. size_t DATA_CHUNK_SIZE = 4;
  4911. const auto &d = *data;
  4912. auto out_len =
  4913. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4914. auto ret =
  4915. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4916. EXPECT_TRUE(ret);
  4917. return true;
  4918. },
  4919. [data, &req](bool success) {
  4920. EXPECT_EQ(success, !req.has_param("error"));
  4921. delete data;
  4922. });
  4923. })
  4924. .Get("/streamed-cancel",
  4925. [&](const Request & /*req*/, Response &res) {
  4926. res.set_content_provider(
  4927. size_t(-1), "text/plain",
  4928. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4929. sink.os << "data_chunk";
  4930. return true;
  4931. });
  4932. })
  4933. .Get("/regex-with-delimiter",
  4934. [&](const Request &req, Response & /*res*/) {
  4935. ASSERT_TRUE(req.has_param("key"));
  4936. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4937. })
  4938. .Get("/with-range",
  4939. [&](const Request & /*req*/, Response &res) {
  4940. res.set_content("abcdefg", "text/plain");
  4941. })
  4942. .Get("/test-start-time",
  4943. [&](const Request &req, Response & /*res*/) {
  4944. EXPECT_NE(req.start_time_,
  4945. std::chrono::steady_clock::time_point::min());
  4946. })
  4947. .Get("/with-range-customized-response",
  4948. [&](const Request & /*req*/, Response &res) {
  4949. res.status = StatusCode::BadRequest_400;
  4950. res.set_content(JSON_DATA, "application/json");
  4951. })
  4952. .Post("/chunked",
  4953. [&](const Request &req, Response & /*res*/) {
  4954. EXPECT_EQ(req.body, "dechunked post body");
  4955. })
  4956. .Post("/large-chunked",
  4957. [&](const Request &req, Response & /*res*/) {
  4958. std::string expected(6 * 30 * 1024u, 'a');
  4959. EXPECT_EQ(req.body, expected);
  4960. })
  4961. .Post("/multipart",
  4962. [&](const Request &req, Response & /*res*/) {
  4963. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4964. req.form.get_field_count("text2") +
  4965. req.form.get_field_count("file3") +
  4966. req.form.get_field_count("file4"));
  4967. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4968. req.form.get_file_count("file2"));
  4969. ASSERT_TRUE(!req.form.has_file("???"));
  4970. ASSERT_TRUE(!req.form.has_field("???"));
  4971. ASSERT_TRUE(req.body.empty());
  4972. {
  4973. const auto &text = req.form.get_field("text1");
  4974. EXPECT_EQ("text default", text);
  4975. }
  4976. {
  4977. const auto &text = req.form.get_field("text2");
  4978. EXPECT_EQ("aωb", text);
  4979. }
  4980. {
  4981. const auto &file = req.form.get_file("file1");
  4982. EXPECT_EQ("hello.txt", file.filename);
  4983. EXPECT_EQ("text/plain", file.content_type);
  4984. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4985. }
  4986. {
  4987. const auto &file = req.form.get_file("file2");
  4988. EXPECT_EQ("world.json", file.filename);
  4989. EXPECT_EQ("application/json", file.content_type);
  4990. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4991. }
  4992. {
  4993. const auto &text = req.form.get_field("file3");
  4994. EXPECT_EQ(0u, text.size());
  4995. }
  4996. {
  4997. const auto &text = req.form.get_field("file4");
  4998. EXPECT_EQ(0u, text.size());
  4999. }
  5000. })
  5001. .Post("/multipart/multi_file_values",
  5002. [&](const Request &req, Response & /*res*/) {
  5003. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5004. req.form.get_field_count("multi_text1"));
  5005. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5006. ASSERT_TRUE(!req.form.has_file("???"));
  5007. ASSERT_TRUE(!req.form.has_field("???"));
  5008. ASSERT_TRUE(req.body.empty());
  5009. {
  5010. const auto &text = req.form.get_field("text");
  5011. EXPECT_EQ("default text", text);
  5012. }
  5013. {
  5014. const auto &text1_values = req.form.get_fields("multi_text1");
  5015. EXPECT_EQ(2u, text1_values.size());
  5016. EXPECT_EQ("aaaaa", text1_values[0]);
  5017. EXPECT_EQ("bbbbb", text1_values[1]);
  5018. }
  5019. {
  5020. const auto &file1_values = req.form.get_files("multi_file1");
  5021. EXPECT_EQ(2u, file1_values.size());
  5022. auto file1 = file1_values[0];
  5023. EXPECT_EQ(file1.filename, "hello.txt");
  5024. EXPECT_EQ(file1.content_type, "text/plain");
  5025. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5026. auto file2 = file1_values[1];
  5027. EXPECT_EQ(file2.filename, "world.json");
  5028. EXPECT_EQ(file2.content_type, "application/json");
  5029. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5030. }
  5031. })
  5032. .Post("/empty",
  5033. [&](const Request &req, Response &res) {
  5034. EXPECT_EQ(req.body, "");
  5035. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5036. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5037. res.set_content("empty", "text/plain");
  5038. })
  5039. .Post("/empty-no-content-type",
  5040. [&](const Request &req, Response &res) {
  5041. EXPECT_EQ(req.body, "");
  5042. EXPECT_FALSE(req.has_header("Content-Type"));
  5043. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5044. res.set_content("empty-no-content-type", "text/plain");
  5045. })
  5046. .Post("/path-only",
  5047. [&](const Request &req, Response &res) {
  5048. EXPECT_EQ(req.body, "");
  5049. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5050. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5051. res.set_content("path-only", "text/plain");
  5052. })
  5053. .Post("/path-headers-only",
  5054. [&](const Request &req, Response &res) {
  5055. EXPECT_EQ(req.body, "");
  5056. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5057. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5058. EXPECT_EQ("world", req.get_header_value("hello"));
  5059. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5060. res.set_content("path-headers-only", "text/plain");
  5061. })
  5062. .Post("/post-large",
  5063. [&](const Request &req, Response &res) {
  5064. EXPECT_EQ(req.body, LARGE_DATA);
  5065. res.set_content(req.body, "text/plain");
  5066. })
  5067. .Post("/post-loopback",
  5068. [&](const Request &, Response &res,
  5069. ContentReader const &content_reader) {
  5070. std::string body;
  5071. content_reader([&](const char *data, size_t data_length) {
  5072. body.append(data, data_length);
  5073. return true;
  5074. });
  5075. res.set_content(body, "text/plain");
  5076. })
  5077. .Put("/put-loopback",
  5078. [&](const Request &, Response &res,
  5079. ContentReader const &content_reader) {
  5080. std::string body;
  5081. content_reader([&](const char *data, size_t data_length) {
  5082. body.append(data, data_length);
  5083. return true;
  5084. });
  5085. res.set_content(body, "text/plain");
  5086. })
  5087. .Patch("/patch-loopback",
  5088. [&](const Request &, Response &res,
  5089. ContentReader const &content_reader) {
  5090. std::string body;
  5091. content_reader([&](const char *data, size_t data_length) {
  5092. body.append(data, data_length);
  5093. return true;
  5094. });
  5095. res.set_content(body, "text/plain");
  5096. })
  5097. .Put("/empty-no-content-type",
  5098. [&](const Request &req, Response &res) {
  5099. EXPECT_EQ(req.body, "");
  5100. EXPECT_FALSE(req.has_header("Content-Type"));
  5101. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5102. res.set_content("empty-no-content-type", "text/plain");
  5103. })
  5104. .Put("/put",
  5105. [&](const Request &req, Response &res) {
  5106. EXPECT_EQ(req.body, "PUT");
  5107. res.set_content(req.body, "text/plain");
  5108. })
  5109. .Put("/put-large",
  5110. [&](const Request &req, Response &res) {
  5111. EXPECT_EQ(req.body, LARGE_DATA);
  5112. res.set_content(req.body, "text/plain");
  5113. })
  5114. .Patch("/patch",
  5115. [&](const Request &req, Response &res) {
  5116. EXPECT_EQ(req.body, "PATCH");
  5117. res.set_content(req.body, "text/plain");
  5118. })
  5119. .Delete("/delete",
  5120. [&](const Request & /*req*/, Response &res) {
  5121. res.set_content("DELETE", "text/plain");
  5122. })
  5123. .Delete("/delete-body",
  5124. [&](const Request &req, Response &res) {
  5125. EXPECT_EQ(req.body, "content");
  5126. res.set_content(req.body, "text/plain");
  5127. })
  5128. .Options(R"(\*)",
  5129. [&](const Request & /*req*/, Response &res) {
  5130. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5131. })
  5132. .CustomRoute("PROPFIND", "/dav/:id",
  5133. [&](const Request &req, Response &res) {
  5134. res.set_header("x-body-size",
  5135. std::to_string(req.body.size()));
  5136. res.set_header("x-matched-route", req.matched_route);
  5137. res.set_header("x-dav-id", req.path_params.at("id"));
  5138. res.status = StatusCode::MultiStatus_207;
  5139. res.set_content(req.body, "application/xml");
  5140. })
  5141. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5142. [&](const Request &req, Response &res) {
  5143. res.set_header("x-dav-match", req.matches[1]);
  5144. res.status = StatusCode::MultiStatus_207;
  5145. })
  5146. .CustomRoute("MKCOL", "/dav-mkcol",
  5147. [&](const Request &req, Response &res) {
  5148. EXPECT_TRUE(req.body.empty());
  5149. res.status = StatusCode::Created_201;
  5150. })
  5151. .CustomRoute(
  5152. "REPORT", "/dav-report",
  5153. [&](const Request & /*req*/, Response &res,
  5154. const ContentReader &content_reader) {
  5155. std::string body;
  5156. content_reader([&](const char *data, size_t data_length) {
  5157. body.append(data, data_length);
  5158. return true;
  5159. });
  5160. res.set_header("x-body-size", std::to_string(body.size()));
  5161. res.status = StatusCode::MultiStatus_207;
  5162. res.set_content(body, "application/xml");
  5163. })
  5164. .Get("/request-target",
  5165. [&](const Request &req, Response & /*res*/) {
  5166. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5167. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5168. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5169. })
  5170. .Get("/long-query-value",
  5171. [&](const Request &req, Response & /*res*/) {
  5172. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5173. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5174. })
  5175. .Get("/too-long-query-value",
  5176. [&](const Request &req, Response & /*res*/) {
  5177. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5178. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5179. })
  5180. .Get("/array-param",
  5181. [&](const Request &req, Response & /*res*/) {
  5182. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5183. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5184. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5185. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5186. })
  5187. .Get("/array-param-values",
  5188. [&](const Request &req, Response & /*res*/) {
  5189. auto values = req.get_param_values("array");
  5190. EXPECT_EQ(3u, values.size());
  5191. EXPECT_EQ("value1", values[0]);
  5192. EXPECT_EQ("value2", values[1]);
  5193. EXPECT_EQ("value3", values[2]);
  5194. auto empty = req.get_param_values("nonexistent");
  5195. EXPECT_TRUE(empty.empty());
  5196. })
  5197. .Post("/validate-no-multiple-headers",
  5198. [&](const Request &req, Response & /*res*/) {
  5199. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5200. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5201. })
  5202. .Post("/content_receiver",
  5203. [&](const Request &req, Response &res,
  5204. const ContentReader &content_reader) {
  5205. if (req.is_multipart_form_data()) {
  5206. std::vector<FormData> items;
  5207. content_reader(
  5208. [&](const FormData &file) {
  5209. items.push_back(file);
  5210. return true;
  5211. },
  5212. [&](const char *data, size_t data_length) {
  5213. items.back().content.append(data, data_length);
  5214. return true;
  5215. });
  5216. EXPECT_EQ(5u, items.size());
  5217. {
  5218. const auto &file = get_file_value(items, "text1");
  5219. EXPECT_TRUE(file.filename.empty());
  5220. EXPECT_EQ("text default", file.content);
  5221. }
  5222. {
  5223. const auto &file = get_file_value(items, "text2");
  5224. EXPECT_TRUE(file.filename.empty());
  5225. EXPECT_EQ("aωb", file.content);
  5226. }
  5227. {
  5228. const auto &file = get_file_value(items, "file1");
  5229. EXPECT_EQ("hello.txt", file.filename);
  5230. EXPECT_EQ("text/plain", file.content_type);
  5231. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5232. }
  5233. {
  5234. const auto &file = get_file_value(items, "file2");
  5235. EXPECT_EQ("world.json", file.filename);
  5236. EXPECT_EQ("application/json", file.content_type);
  5237. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5238. }
  5239. {
  5240. const auto &file = get_file_value(items, "file3");
  5241. EXPECT_TRUE(file.filename.empty());
  5242. EXPECT_EQ("application/octet-stream", file.content_type);
  5243. EXPECT_EQ(0u, file.content.size());
  5244. }
  5245. } else {
  5246. std::string body;
  5247. content_reader([&](const char *data, size_t data_length) {
  5248. EXPECT_EQ(7U, data_length);
  5249. body.append(data, data_length);
  5250. return true;
  5251. });
  5252. EXPECT_EQ(body, "content");
  5253. res.set_content(body, "text/plain");
  5254. }
  5255. })
  5256. .Put("/content_receiver",
  5257. [&](const Request & /*req*/, Response &res,
  5258. const ContentReader &content_reader) {
  5259. std::string body;
  5260. content_reader([&](const char *data, size_t data_length) {
  5261. body.append(data, data_length);
  5262. return true;
  5263. });
  5264. EXPECT_EQ(body, "content");
  5265. res.set_content(body, "text/plain");
  5266. })
  5267. .Patch("/content_receiver",
  5268. [&](const Request & /*req*/, Response &res,
  5269. const ContentReader &content_reader) {
  5270. std::string body;
  5271. content_reader([&](const char *data, size_t data_length) {
  5272. body.append(data, data_length);
  5273. return true;
  5274. });
  5275. EXPECT_EQ(body, "content");
  5276. res.set_content(body, "text/plain");
  5277. })
  5278. .Post("/query-string-and-body",
  5279. [&](const Request &req, Response & /*res*/) {
  5280. ASSERT_TRUE(req.has_param("key"));
  5281. EXPECT_EQ(req.get_param_value("key"), "value");
  5282. EXPECT_EQ(req.body, "content");
  5283. })
  5284. .Get("/last-request",
  5285. [&](const Request &req, Response & /*res*/) {
  5286. EXPECT_EQ("close", req.get_header_value("Connection"));
  5287. })
  5288. .Get(R"(/redirect/(\d+))",
  5289. [&](const Request &req, Response &res) {
  5290. auto num = std::stoi(req.matches[1]) + 1;
  5291. std::string url = "/redirect/" + std::to_string(num);
  5292. res.set_redirect(url);
  5293. })
  5294. .Post("/binary",
  5295. [&](const Request &req, Response &res) {
  5296. EXPECT_EQ(4U, req.body.size());
  5297. EXPECT_EQ("application/octet-stream",
  5298. req.get_header_value("Content-Type"));
  5299. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5300. res.set_content(req.body, "application/octet-stream");
  5301. })
  5302. .Put("/binary",
  5303. [&](const Request &req, Response &res) {
  5304. EXPECT_EQ(4U, req.body.size());
  5305. EXPECT_EQ("application/octet-stream",
  5306. req.get_header_value("Content-Type"));
  5307. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5308. res.set_content(req.body, "application/octet-stream");
  5309. })
  5310. .Patch("/binary",
  5311. [&](const Request &req, Response &res) {
  5312. EXPECT_EQ(4U, req.body.size());
  5313. EXPECT_EQ("application/octet-stream",
  5314. req.get_header_value("Content-Type"));
  5315. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5316. res.set_content(req.body, "application/octet-stream");
  5317. })
  5318. .Delete("/binary",
  5319. [&](const Request &req, Response &res) {
  5320. EXPECT_EQ(4U, req.body.size());
  5321. EXPECT_EQ("application/octet-stream",
  5322. req.get_header_value("Content-Type"));
  5323. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5324. res.set_content(req.body, "application/octet-stream");
  5325. })
  5326. .Get("/issue1772",
  5327. [&](const Request & /*req*/, Response &res) {
  5328. res.status = 401;
  5329. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5330. })
  5331. .Delete("/issue609",
  5332. [](const httplib::Request &, httplib::Response &res,
  5333. const httplib::ContentReader &) {
  5334. res.set_content("ok", "text/plain");
  5335. })
  5336. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5337. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5338. .Get("/compress",
  5339. [&](const Request & /*req*/, Response &res) {
  5340. res.set_content(
  5341. "12345678901234567890123456789012345678901234567890123456789"
  5342. "01234567890123456789012345678901234567890",
  5343. "text/plain");
  5344. })
  5345. .Get("/compress-with-charset",
  5346. [&](const Request & /*req*/, Response &res) {
  5347. res.set_content(
  5348. "12345678901234567890123456789012345678901234567890123456789"
  5349. "01234567890123456789012345678901234567890",
  5350. "application/json; charset=utf-8");
  5351. })
  5352. .Get("/nocompress",
  5353. [&](const Request & /*req*/, Response &res) {
  5354. res.set_content(
  5355. "12345678901234567890123456789012345678901234567890123456789"
  5356. "01234567890123456789012345678901234567890",
  5357. "application/octet-stream");
  5358. })
  5359. .Post("/compress-multipart",
  5360. [&](const Request &req, Response & /*res*/) {
  5361. EXPECT_EQ(2u, req.form.fields.size());
  5362. ASSERT_TRUE(!req.form.has_field("???"));
  5363. {
  5364. const auto &text = req.form.get_field("key1");
  5365. EXPECT_EQ("test", text);
  5366. }
  5367. {
  5368. const auto &text = req.form.get_field("key2");
  5369. EXPECT_EQ("--abcdefg123", text);
  5370. }
  5371. })
  5372. #endif
  5373. ;
  5374. persons_["john"] = "programmer";
  5375. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5376. svr_.wait_until_ready();
  5377. }
  5378. virtual void TearDown() {
  5379. svr_.stop();
  5380. if (!request_threads_.empty()) {
  5381. std::this_thread::sleep_for(std::chrono::seconds(1));
  5382. for (auto &t : request_threads_) {
  5383. t.join();
  5384. }
  5385. }
  5386. t_.join();
  5387. }
  5388. map<string, string> persons_;
  5389. #ifdef CPPHTTPLIB_SSL_ENABLED
  5390. SSLClient cli_;
  5391. SSLServer svr_;
  5392. #else
  5393. Client cli_;
  5394. Server svr_;
  5395. #endif
  5396. thread t_;
  5397. std::vector<thread> request_threads_;
  5398. };
  5399. TEST_F(ServerTest, GetMethod200) {
  5400. auto res = cli_.Get("/hi");
  5401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5402. EXPECT_EQ("HTTP/1.1", res->version);
  5403. EXPECT_EQ(StatusCode::OK_200, res->status);
  5404. EXPECT_EQ("OK", res->reason);
  5405. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5406. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5407. EXPECT_EQ("Hello World!", res->body);
  5408. }
  5409. TEST_F(ServerTest, GetEmptyFile) {
  5410. auto res = cli_.Get("/empty_file");
  5411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5412. EXPECT_EQ(StatusCode::OK_200, res->status);
  5413. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5414. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5415. EXPECT_EQ("", res->body);
  5416. }
  5417. TEST_F(ServerTest, GetFileContent) {
  5418. auto res = cli_.Get("/file_content");
  5419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5420. EXPECT_EQ(StatusCode::OK_200, res->status);
  5421. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5422. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5423. EXPECT_EQ("test.html", res->body);
  5424. }
  5425. TEST_F(ServerTest, GetFileContentWithRange) {
  5426. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5428. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5429. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5430. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5431. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5432. EXPECT_EQ("est", res->body);
  5433. }
  5434. TEST_F(ServerTest, GetFileContentWithContentType) {
  5435. auto res = cli_.Get("/file_content_with_content_type");
  5436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5437. EXPECT_EQ(StatusCode::OK_200, res->status);
  5438. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5439. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5440. EXPECT_EQ("file\n", res->body);
  5441. }
  5442. TEST_F(ServerTest, GetInvalidFileContent) {
  5443. auto res = cli_.Get("/invalid_file_content");
  5444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5445. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5446. }
  5447. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5448. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5450. EXPECT_EQ("HTTP/1.1", res->version);
  5451. EXPECT_EQ(StatusCode::OK_200, res->status);
  5452. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5453. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5454. EXPECT_EQ("Hello World!", res->body);
  5455. }
  5456. TEST_F(ServerTest, GetMethod302) {
  5457. auto res = cli_.Get("/");
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::Found_302, res->status);
  5460. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5461. }
  5462. TEST_F(ServerTest, GetMethod302Redirect) {
  5463. cli_.set_follow_location(true);
  5464. auto res = cli_.Get("/");
  5465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5466. EXPECT_EQ(StatusCode::OK_200, res->status);
  5467. EXPECT_EQ("Hello World!", res->body);
  5468. EXPECT_EQ("/hi", res->location);
  5469. }
  5470. TEST_F(ServerTest, GetMethod404) {
  5471. auto res = cli_.Get("/invalid");
  5472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5473. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5474. }
  5475. TEST_F(ServerTest, HeadMethod200) {
  5476. auto res = cli_.Head("/hi");
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ(StatusCode::OK_200, res->status);
  5479. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5480. EXPECT_TRUE(res->body.empty());
  5481. }
  5482. TEST_F(ServerTest, HeadMethod200Static) {
  5483. auto res = cli_.Head("/mount/dir/index.html");
  5484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5485. EXPECT_EQ(StatusCode::OK_200, res->status);
  5486. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5487. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5488. EXPECT_TRUE(res->body.empty());
  5489. }
  5490. TEST_F(ServerTest, HeadMethod404) {
  5491. auto res = cli_.Head("/invalid");
  5492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5493. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5494. EXPECT_TRUE(res->body.empty());
  5495. }
  5496. TEST_F(ServerTest, GetMethodPersonJohn) {
  5497. auto res = cli_.Get("/person/john");
  5498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5499. EXPECT_EQ(StatusCode::OK_200, res->status);
  5500. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5501. EXPECT_EQ("programmer", res->body);
  5502. }
  5503. TEST_F(ServerTest, PostMethod1) {
  5504. auto res = cli_.Get("/person/john1");
  5505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5506. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5507. res = cli_.Post("/person", "name=john1&note=coder",
  5508. "application/x-www-form-urlencoded");
  5509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5510. ASSERT_EQ(StatusCode::OK_200, res->status);
  5511. res = cli_.Get("/person/john1");
  5512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5513. ASSERT_EQ(StatusCode::OK_200, res->status);
  5514. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5515. ASSERT_EQ("coder", res->body);
  5516. }
  5517. TEST_F(ServerTest, PostMethod2) {
  5518. auto res = cli_.Get("/person/john2");
  5519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5520. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5521. Params params;
  5522. params.emplace("name", "john2");
  5523. params.emplace("note", "coder");
  5524. res = cli_.Post("/person", params);
  5525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5526. ASSERT_EQ(StatusCode::OK_200, res->status);
  5527. res = cli_.Get("/person/john2");
  5528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5529. ASSERT_EQ(StatusCode::OK_200, res->status);
  5530. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5531. ASSERT_EQ("coder", res->body);
  5532. }
  5533. TEST_F(ServerTest, PutMethod3) {
  5534. auto res = cli_.Get("/person/john3");
  5535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5536. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5537. Params params;
  5538. params.emplace("name", "john3");
  5539. params.emplace("note", "coder");
  5540. res = cli_.Put("/person", params);
  5541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5542. ASSERT_EQ(StatusCode::OK_200, res->status);
  5543. res = cli_.Get("/person/john3");
  5544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5545. ASSERT_EQ(StatusCode::OK_200, res->status);
  5546. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5547. ASSERT_EQ("coder", res->body);
  5548. }
  5549. TEST_F(ServerTest, DeleteMethod1) {
  5550. auto res = cli_.Get("/person/john4");
  5551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5552. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5553. Params params;
  5554. params.emplace("name", "john4");
  5555. params.emplace("note", "coder");
  5556. res = cli_.Post("/person", params);
  5557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5558. ASSERT_EQ(StatusCode::OK_200, res->status);
  5559. res = cli_.Get("/person/john4");
  5560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5561. ASSERT_EQ(StatusCode::OK_200, res->status);
  5562. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5563. ASSERT_EQ("coder", res->body);
  5564. Params delete_params;
  5565. delete_params.emplace("name", "john4");
  5566. res = cli_.Delete("/person", delete_params);
  5567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5568. ASSERT_EQ(StatusCode::OK_200, res->status);
  5569. ASSERT_EQ("DELETED", res->body);
  5570. res = cli_.Get("/person/john4");
  5571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5572. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5573. }
  5574. TEST_F(ServerTest, DeleteMethod2) {
  5575. auto res = cli_.Get("/person/john5");
  5576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5577. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5578. Params params;
  5579. params.emplace("name", "john5");
  5580. params.emplace("note", "developer");
  5581. res = cli_.Post("/person", params);
  5582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5583. ASSERT_EQ(StatusCode::OK_200, res->status);
  5584. res = cli_.Get("/person/john5");
  5585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5586. ASSERT_EQ(StatusCode::OK_200, res->status);
  5587. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5588. ASSERT_EQ("developer", res->body);
  5589. Params delete_params;
  5590. delete_params.emplace("name", "john5");
  5591. Headers headers;
  5592. headers.emplace("Custom-Header", "test-value");
  5593. res = cli_.Delete("/person", headers, delete_params);
  5594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5595. ASSERT_EQ(StatusCode::OK_200, res->status);
  5596. ASSERT_EQ("DELETED", res->body);
  5597. res = cli_.Get("/person/john5");
  5598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5599. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5600. }
  5601. TEST_F(ServerTest, DeleteMethod3) {
  5602. auto res = cli_.Get("/person/john6");
  5603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5604. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5605. Params params;
  5606. params.emplace("name", "john6");
  5607. params.emplace("note", "tester");
  5608. res = cli_.Post("/person", params);
  5609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5610. ASSERT_EQ(StatusCode::OK_200, res->status);
  5611. res = cli_.Get("/person/john6");
  5612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5613. ASSERT_EQ(StatusCode::OK_200, res->status);
  5614. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5615. ASSERT_EQ("tester", res->body);
  5616. Params delete_params;
  5617. delete_params.emplace("name", "john6");
  5618. Headers headers;
  5619. headers.emplace("Custom-Header", "test-value");
  5620. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. ASSERT_EQ(StatusCode::OK_200, res->status);
  5623. ASSERT_EQ("DELETED", res->body);
  5624. res = cli_.Get("/person/john6");
  5625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5626. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5627. }
  5628. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5629. Params params;
  5630. params.emplace("json", JSON_DATA);
  5631. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5633. ASSERT_EQ(StatusCode::OK_200, res->status);
  5634. ASSERT_EQ(JSON_DATA, res->body);
  5635. }
  5636. TEST_F(ServerTest, PostEmptyContent) {
  5637. auto res = cli_.Post("/empty", "", "text/plain");
  5638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5639. ASSERT_EQ(StatusCode::OK_200, res->status);
  5640. ASSERT_EQ("empty", res->body);
  5641. }
  5642. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5643. auto res = cli_.Post("/empty-no-content-type");
  5644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5645. ASSERT_EQ(StatusCode::OK_200, res->status);
  5646. ASSERT_EQ("empty-no-content-type", res->body);
  5647. }
  5648. TEST_F(ServerTest, PostPathOnly) {
  5649. auto res = cli_.Post("/path-only");
  5650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5651. ASSERT_EQ(StatusCode::OK_200, res->status);
  5652. ASSERT_EQ("path-only", res->body);
  5653. }
  5654. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5655. auto res = cli_.Post("/path-headers-only",
  5656. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5658. ASSERT_EQ(StatusCode::OK_200, res->status);
  5659. ASSERT_EQ("path-headers-only", res->body);
  5660. }
  5661. TEST_F(ServerTest, PostLarge) {
  5662. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5664. ASSERT_EQ(StatusCode::OK_200, res->status);
  5665. EXPECT_EQ(LARGE_DATA, res->body);
  5666. }
  5667. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5668. auto res = cli_.Put("/empty-no-content-type");
  5669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5670. ASSERT_EQ(StatusCode::OK_200, res->status);
  5671. ASSERT_EQ("empty-no-content-type", res->body);
  5672. }
  5673. TEST_F(ServerTest, GetMethodDir) {
  5674. auto res = cli_.Get("/dir/");
  5675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5676. EXPECT_EQ(StatusCode::OK_200, res->status);
  5677. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5678. auto body = R"(<html>
  5679. <head>
  5680. </head>
  5681. <body>
  5682. <a href="/dir/test.html">Test</a>
  5683. <a href="/hi">hi</a>
  5684. </body>
  5685. </html>
  5686. )";
  5687. EXPECT_EQ(body, res->body);
  5688. }
  5689. TEST_F(ServerTest, GetMethodDirTest) {
  5690. auto res = cli_.Get("/dir/test.html");
  5691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5692. EXPECT_EQ(StatusCode::OK_200, res->status);
  5693. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5694. EXPECT_EQ("test.html", res->body);
  5695. }
  5696. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5697. auto res = cli_.Get("/dir/../dir/test.html");
  5698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5699. EXPECT_EQ(StatusCode::OK_200, res->status);
  5700. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5701. EXPECT_EQ("test.html", res->body);
  5702. }
  5703. TEST_F(ServerTest, GetMethodInvalidPath) {
  5704. auto res = cli_.Get("/dir/../test.html");
  5705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5706. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5707. }
  5708. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5709. auto res = cli_.Get("/../www/dir/test.html");
  5710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5711. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5712. }
  5713. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5714. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5716. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5717. }
  5718. TEST_F(ServerTest, GetMethodDirMountTest) {
  5719. auto res = cli_.Get("/mount/dir/test.html");
  5720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5721. EXPECT_EQ(StatusCode::OK_200, res->status);
  5722. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5723. EXPECT_EQ("test.html", res->body);
  5724. }
  5725. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5726. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5728. EXPECT_EQ(StatusCode::OK_200, res->status);
  5729. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5730. EXPECT_EQ("test.html", res->body);
  5731. }
  5732. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5733. auto res = cli_.Get("/mount/dir/../test.html");
  5734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5735. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5736. }
  5737. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5738. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5740. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5741. }
  5742. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5743. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5746. }
  5747. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5748. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5751. }
  5752. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5753. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5756. }
  5757. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5758. auto res = cli_.Get("/mount/dir");
  5759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5760. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5761. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5762. }
  5763. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5764. auto res = cli_.Get("//dir");
  5765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5766. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5767. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5768. }
  5769. TEST_F(ServerTest, PostMethod303) {
  5770. auto res = cli_.Post("/1", "body", "text/plain");
  5771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5772. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5773. EXPECT_EQ("/2", res->get_header_value("Location"));
  5774. }
  5775. TEST_F(ServerTest, PostMethod303Redirect) {
  5776. cli_.set_follow_location(true);
  5777. auto res = cli_.Post("/1", "body", "text/plain");
  5778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5779. EXPECT_EQ(StatusCode::OK_200, res->status);
  5780. EXPECT_EQ("redirected.", res->body);
  5781. EXPECT_EQ("/2", res->location);
  5782. }
  5783. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5784. auto res = cli_.Get("/dir/test.abcde");
  5785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5786. EXPECT_EQ(StatusCode::OK_200, res->status);
  5787. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5788. EXPECT_EQ("abcde", res->body);
  5789. }
  5790. TEST_F(ServerTest, StaticFileRange) {
  5791. auto res =
  5792. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5794. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5795. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5796. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5797. EXPECT_EQ(true, res->has_header("Content-Range"));
  5798. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5799. EXPECT_EQ(std::string("cd"), res->body);
  5800. }
  5801. TEST_F(ServerTest, StaticFileRanges) {
  5802. auto res = cli_.Get("/dir/test.abcde",
  5803. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5805. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5806. EXPECT_TRUE(
  5807. res->get_header_value("Content-Type")
  5808. .find(
  5809. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5810. 0);
  5811. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5812. }
  5813. TEST_F(ServerTest, StaticFileRangeHead) {
  5814. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5817. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5818. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5819. EXPECT_EQ(true, res->has_header("Content-Range"));
  5820. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5821. }
  5822. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5823. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5825. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5826. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5827. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5828. EXPECT_EQ(true, res->has_header("Content-Range"));
  5829. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5830. res->get_header_value("Content-Range"));
  5831. EXPECT_EQ("LAST\n", res->body);
  5832. }
  5833. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5834. auto res =
  5835. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5837. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5838. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5839. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5840. EXPECT_EQ(true, res->has_header("Content-Range"));
  5841. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5842. }
  5843. TEST_F(ServerTest, StaticFileBigFile) {
  5844. auto res = cli_.Get("/dir/1MB.txt");
  5845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5846. EXPECT_EQ(StatusCode::OK_200, res->status);
  5847. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5848. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5849. }
  5850. TEST_F(ServerTest, InvalidBaseDirMount) {
  5851. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5852. }
  5853. TEST_F(ServerTest, Binary) {
  5854. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5855. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5856. "application/octet-stream");
  5857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5858. ASSERT_EQ(StatusCode::OK_200, res->status);
  5859. ASSERT_EQ(4U, res->body.size());
  5860. res = cli_.Put("/binary", binary.data(), binary.size(),
  5861. "application/octet-stream");
  5862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5863. ASSERT_EQ(StatusCode::OK_200, res->status);
  5864. ASSERT_EQ(4U, res->body.size());
  5865. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5866. "application/octet-stream");
  5867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5868. ASSERT_EQ(StatusCode::OK_200, res->status);
  5869. ASSERT_EQ(4U, res->body.size());
  5870. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5871. "application/octet-stream");
  5872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5873. ASSERT_EQ(StatusCode::OK_200, res->status);
  5874. ASSERT_EQ(4U, res->body.size());
  5875. }
  5876. TEST_F(ServerTest, BinaryString) {
  5877. auto binary = std::string("\x00\x01\x02\x03", 4);
  5878. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5880. ASSERT_EQ(StatusCode::OK_200, res->status);
  5881. ASSERT_EQ(4U, res->body.size());
  5882. res = cli_.Put("/binary", binary, "application/octet-stream");
  5883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5884. ASSERT_EQ(StatusCode::OK_200, res->status);
  5885. ASSERT_EQ(4U, res->body.size());
  5886. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5888. ASSERT_EQ(StatusCode::OK_200, res->status);
  5889. ASSERT_EQ(4U, res->body.size());
  5890. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5892. ASSERT_EQ(StatusCode::OK_200, res->status);
  5893. ASSERT_EQ(4U, res->body.size());
  5894. }
  5895. TEST_F(ServerTest, EmptyRequest) {
  5896. auto res = cli_.Get("");
  5897. ASSERT_TRUE(!res);
  5898. EXPECT_EQ(Error::Connection, res.error());
  5899. }
  5900. TEST_F(ServerTest, LongRequest) {
  5901. std::string request;
  5902. for (size_t i = 0; i < 545; i++) {
  5903. request += "/TooLongRequest";
  5904. }
  5905. request += "OK";
  5906. auto res = cli_.Get(request.c_str());
  5907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5908. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5909. }
  5910. TEST_F(ServerTest, TooLongRequest) {
  5911. std::string request;
  5912. for (size_t i = 0; i < 546; i++) {
  5913. request += "/TooLongRequest";
  5914. }
  5915. request += "_NG";
  5916. auto start = std::chrono::high_resolution_clock::now();
  5917. cli_.set_keep_alive(true);
  5918. auto res = cli_.Get(request.c_str());
  5919. auto end = std::chrono::high_resolution_clock::now();
  5920. auto elapsed =
  5921. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5922. .count();
  5923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5924. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5925. EXPECT_LE(elapsed, 1000);
  5926. EXPECT_EQ("close", res->get_header_value("Connection"));
  5927. EXPECT_FALSE(cli_.is_socket_open());
  5928. }
  5929. TEST_F(ServerTest, AlmostTooLongRequest) {
  5930. // test for #2046 - URI length check shouldn't include other content on req
  5931. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5932. // leading /, space, HTTP/1.1)
  5933. std::string request =
  5934. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5935. auto res = cli_.Get(request.c_str());
  5936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5937. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5938. }
  5939. TEST_F(ServerTest, LongHeader) {
  5940. Request req;
  5941. req.method = "GET";
  5942. req.path = "/hi";
  5943. std::string host_and_port;
  5944. host_and_port += HOST;
  5945. host_and_port += ":";
  5946. host_and_port += std::to_string(PORT);
  5947. req.headers.emplace("Host", host_and_port.c_str());
  5948. req.headers.emplace("Accept", "*/*");
  5949. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5950. req.headers.emplace(
  5951. "Header-Name",
  5952. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5953. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5954. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5955. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5956. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5957. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5958. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5959. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5960. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5961. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5962. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5963. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5964. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5965. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5966. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5967. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5968. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5972. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5973. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5974. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5975. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5976. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5979. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5980. "@@@@@@@@@@@@@@@@");
  5981. auto res = std::make_shared<Response>();
  5982. auto error = Error::Success;
  5983. auto ret = cli_.send(req, *res, error);
  5984. ASSERT_TRUE(ret);
  5985. EXPECT_EQ(StatusCode::OK_200, res->status);
  5986. }
  5987. TEST_F(ServerTest, LongQueryValue) {
  5988. auto start = std::chrono::high_resolution_clock::now();
  5989. cli_.set_keep_alive(true);
  5990. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5991. auto end = std::chrono::high_resolution_clock::now();
  5992. auto elapsed =
  5993. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5994. .count();
  5995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5996. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5997. EXPECT_LE(elapsed, 1000);
  5998. EXPECT_EQ("close", res->get_header_value("Connection"));
  5999. EXPECT_FALSE(cli_.is_socket_open());
  6000. }
  6001. TEST_F(ServerTest, TooLongQueryValue) {
  6002. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6003. ASSERT_FALSE(res);
  6004. EXPECT_EQ(Error::Read, res.error());
  6005. }
  6006. TEST_F(ServerTest, TooLongHeader) {
  6007. Request req;
  6008. req.method = "GET";
  6009. req.path = "/hi";
  6010. std::string host_and_port;
  6011. host_and_port += HOST;
  6012. host_and_port += ":";
  6013. host_and_port += std::to_string(PORT);
  6014. req.headers.emplace("Host", host_and_port.c_str());
  6015. req.headers.emplace("Accept", "*/*");
  6016. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6017. req.headers.emplace(
  6018. "Header-Name",
  6019. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6020. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6021. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6022. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6023. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6024. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6025. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6026. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6027. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6028. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6029. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6030. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6031. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6032. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6033. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6034. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6047. "@@@@@@@@@@@@@@@@@");
  6048. auto res = std::make_shared<Response>();
  6049. auto error = Error::Success;
  6050. auto ret = cli_.send(req, *res, error);
  6051. ASSERT_TRUE(ret);
  6052. EXPECT_EQ(StatusCode::OK_200, res->status);
  6053. }
  6054. TEST_F(ServerTest, HeaderCountAtLimit) {
  6055. // Test with headers just under the 100 limit
  6056. httplib::Headers headers;
  6057. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6058. // This should keep us just under the 100 header limit
  6059. for (int i = 0; i < 95; i++) {
  6060. std::string name = "X-Test-Header-" + std::to_string(i);
  6061. std::string value = "value" + std::to_string(i);
  6062. headers.emplace(name, value);
  6063. }
  6064. // This should work fine as we're under the limit
  6065. auto res = cli_.Get("/hi", headers);
  6066. EXPECT_TRUE(res);
  6067. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6068. }
  6069. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6070. // Test with many headers to exceed the 100 limit
  6071. httplib::Headers headers;
  6072. // Add 150 headers to definitely exceed the 100 limit
  6073. for (int i = 0; i < 150; i++) {
  6074. std::string name = "X-Test-Header-" + std::to_string(i);
  6075. std::string value = "value" + std::to_string(i);
  6076. headers.emplace(name, value);
  6077. }
  6078. // This should fail due to exceeding header count limit
  6079. cli_.set_keep_alive(true);
  6080. auto res = cli_.Get("/hi", headers);
  6081. // The server should respond with 400 Bad Request
  6082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6083. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6084. EXPECT_EQ("close", res->get_header_value("Connection"));
  6085. EXPECT_FALSE(cli_.is_socket_open());
  6086. }
  6087. TEST_F(ServerTest, PercentEncoding) {
  6088. auto res = cli_.Get("/e%6edwith%");
  6089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6090. EXPECT_EQ(StatusCode::OK_200, res->status);
  6091. }
  6092. TEST_F(ServerTest, PercentEncodingUnicode) {
  6093. auto res = cli_.Get("/e%u006edwith%");
  6094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6095. EXPECT_EQ(StatusCode::OK_200, res->status);
  6096. }
  6097. TEST_F(ServerTest, InvalidPercentEncoding) {
  6098. auto res = cli_.Get("/%endwith%");
  6099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6100. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6101. }
  6102. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6103. auto res = cli_.Get("/%uendwith%");
  6104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6105. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6106. }
  6107. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6108. auto res = cli_.Get("/hello?aaa=bbb%");
  6109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6110. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6111. }
  6112. TEST_F(ServerTest, PlusSignEncoding) {
  6113. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6115. EXPECT_EQ(StatusCode::OK_200, res->status);
  6116. EXPECT_EQ("a +b", res->body);
  6117. }
  6118. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6119. // This test simulates a potential DoS attack using many headers
  6120. // to verify our security fix prevents memory exhaustion
  6121. httplib::Headers attack_headers;
  6122. // Attempt to add many headers like an attacker would (200 headers to far
  6123. // exceed limit)
  6124. for (int i = 0; i < 200; i++) {
  6125. std::string name = "X-Attack-Header-" + std::to_string(i);
  6126. std::string value = "attack_payload_" + std::to_string(i);
  6127. attack_headers.emplace(name, value);
  6128. }
  6129. // Try to POST with excessive headers
  6130. cli_.set_keep_alive(true);
  6131. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6132. // Should either fail or return 400 Bad Request due to security limit
  6133. if (res) {
  6134. // If we get a response, it should be 400 Bad Request
  6135. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6136. EXPECT_EQ("close", res->get_header_value("Connection"));
  6137. }
  6138. EXPECT_FALSE(cli_.is_socket_open());
  6139. }
  6140. TEST_F(ServerTest, MultipartFormData) {
  6141. UploadFormDataItems items = {
  6142. {"text1", "text default", "", ""},
  6143. {"text2", "aωb", "", ""},
  6144. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6145. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6146. {"file3", "", "", "application/octet-stream"},
  6147. {"file4", "", "", " application/json tmp-string "}};
  6148. auto res = cli_.Post("/multipart", items);
  6149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6150. EXPECT_EQ(StatusCode::OK_200, res->status);
  6151. }
  6152. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6153. UploadFormDataItems items = {
  6154. {"text", "default text", "", ""},
  6155. {"multi_text1", "aaaaa", "", ""},
  6156. {"multi_text1", "bbbbb", "", ""},
  6157. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6158. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6159. "application/json"},
  6160. };
  6161. auto res = cli_.Post("/multipart/multi_file_values", items);
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. EXPECT_EQ(StatusCode::OK_200, res->status);
  6164. }
  6165. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6166. auto res = cli_.Get("/hi");
  6167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6168. EXPECT_EQ(StatusCode::OK_200, res->status);
  6169. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6170. EXPECT_EQ("Hello World!", res->body);
  6171. }
  6172. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6173. Request req;
  6174. req.method = "POST";
  6175. req.path = "/chunked";
  6176. std::string host_and_port;
  6177. host_and_port += HOST;
  6178. host_and_port += ":";
  6179. host_and_port += std::to_string(PORT);
  6180. req.headers.emplace("Host", host_and_port.c_str());
  6181. req.headers.emplace("Accept", "*/*");
  6182. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6183. req.headers.emplace("Content-Type", "text/plain");
  6184. req.headers.emplace("Content-Length", "0");
  6185. req.headers.emplace(
  6186. "Transfer-Encoding",
  6187. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6188. // Client does not chunk, so make a chunked body manually.
  6189. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6190. auto res = std::make_shared<Response>();
  6191. auto error = Error::Success;
  6192. auto ret = cli_.send(req, *res, error);
  6193. ASSERT_TRUE(ret);
  6194. EXPECT_EQ(StatusCode::OK_200, res->status);
  6195. }
  6196. template <typename ClientT>
  6197. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6198. int expected_status) {
  6199. Request req;
  6200. req.method = "POST";
  6201. req.path = "/chunked";
  6202. std::string host_and_port;
  6203. host_and_port += HOST;
  6204. host_and_port += ":";
  6205. host_and_port += std::to_string(PORT);
  6206. req.headers.emplace("Host", host_and_port.c_str());
  6207. req.headers.emplace("Content-Length", "0");
  6208. req.headers.emplace("Transfer-Encoding", "chunked");
  6209. req.body = body;
  6210. auto res = std::make_shared<Response>();
  6211. auto error = Error::Success;
  6212. ASSERT_TRUE(cli.send(req, *res, error));
  6213. EXPECT_EQ(expected_status, res->status);
  6214. }
  6215. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6216. // rather than treat them as valid lengths.
  6217. template <typename ClientT>
  6218. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6219. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6220. }
  6221. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6222. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6223. }
  6224. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6225. expect_chunked_body_rejected(
  6226. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6227. }
  6228. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6229. // chunk-size line carries no CR, LF or other control character ahead of its
  6230. // terminator. Such a line must be refused rather than read as extension text.
  6231. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6232. expect_chunked_body_rejected(
  6233. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6234. }
  6235. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6236. expect_chunked_body_rejected(
  6237. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6238. }
  6239. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6240. expect_chunked_body_rejected(
  6241. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6242. }
  6243. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6244. // The literal stays split: a hex escape consumes every hex digit that
  6245. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6246. expect_chunked_body_rejected(
  6247. cli_, "4;a\x01"
  6248. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6249. }
  6250. TEST_F(ServerTest, AcceptsChunkExtension) {
  6251. expect_chunked_body_status(cli_,
  6252. "4;name=value\r\ndech\r\n"
  6253. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6254. "0;last\r\n\r\n",
  6255. StatusCode::OK_200);
  6256. }
  6257. TEST_F(ServerTest, GetStreamed2) {
  6258. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6261. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6262. EXPECT_EQ(true, res->has_header("Content-Range"));
  6263. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6264. EXPECT_EQ(std::string("ab"), res->body);
  6265. }
  6266. TEST_F(ServerTest, GetStreamed) {
  6267. auto res = cli_.Get("/streamed");
  6268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6269. EXPECT_EQ(StatusCode::OK_200, res->status);
  6270. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6271. EXPECT_EQ(std::string("aaabbb"), res->body);
  6272. }
  6273. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6274. auto res = cli_.Get("/streamed-without-length",
  6275. Headers{make_range_header({{0, -1}})});
  6276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6277. EXPECT_EQ(StatusCode::OK_200, res->status);
  6278. EXPECT_EQ(false, res->has_header("Content-Length"));
  6279. EXPECT_EQ(false, res->has_header("Content-Range"));
  6280. EXPECT_EQ(std::string("abcdefg"), res->body);
  6281. }
  6282. TEST_F(ServerTest, GetStreamedWithRange1) {
  6283. auto res =
  6284. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6286. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6287. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6288. EXPECT_EQ(true, res->has_header("Content-Range"));
  6289. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6290. EXPECT_EQ(std::string("def"), res->body);
  6291. }
  6292. TEST_F(ServerTest, GetStreamedWithRange2) {
  6293. auto res =
  6294. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6296. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6297. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6298. EXPECT_EQ(true, res->has_header("Content-Range"));
  6299. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6300. EXPECT_EQ(std::string("bcdefg"), res->body);
  6301. }
  6302. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6303. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6305. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6306. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6307. EXPECT_EQ(true, res->has_header("Content-Range"));
  6308. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6309. EXPECT_EQ(std::string("efg"), res->body);
  6310. }
  6311. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6312. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6313. // the entire representation.
  6314. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6315. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6317. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6318. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6319. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6320. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6321. }
  6322. }
  6323. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6324. auto res =
  6325. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6327. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6328. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6329. EXPECT_EQ(false, res->has_header("Content-Range"));
  6330. EXPECT_EQ(0U, res->body.size());
  6331. }
  6332. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6333. // Only a 206 is served as a partial representation. Under any other status
  6334. // `apply_ranges()` reported the full content length, so the body must match
  6335. // that header, and the content provider must never be asked for an offset
  6336. // outside the representation.
  6337. auto check = [&](int status, const char *range) {
  6338. auto path =
  6339. std::string("/streamed-with-range?status=") + std::to_string(status);
  6340. auto ctx = path + " Range: " + range;
  6341. auto res = cli_.Get(path, Headers{{"Range", range}});
  6342. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6343. EXPECT_EQ(status, res->status) << ctx;
  6344. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6345. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6346. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6347. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6348. };
  6349. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6350. check(403, "bytes=3-5");
  6351. // The offset is far past the representation.
  6352. check(403, "bytes=100000-100200");
  6353. // `first_pos` is still -1 here, and the bounds asserts in
  6354. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6355. check(403, "bytes=-3");
  6356. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6357. // multipart branch would have written one that is empty.
  6358. check(403, "bytes=1-2, 4-5");
  6359. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6360. // covers the whole representation.
  6361. check(200, "bytes=3-5");
  6362. check(200, "bytes=1-2, 4-5");
  6363. }
  6364. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6365. auto res =
  6366. cli_.Get("/streamed-with-range",
  6367. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6368. "92233720368547758079223372036854775807"}});
  6369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6370. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6371. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6372. EXPECT_EQ(false, res->has_header("Content-Range"));
  6373. EXPECT_EQ(0U, res->body.size());
  6374. }
  6375. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6376. auto res = cli_.Get(
  6377. "/with-range",
  6378. Headers{{"Range",
  6379. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6380. {"Accept-Encoding", ""}});
  6381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6382. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6383. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6384. EXPECT_EQ(true, res->has_header("Content-Range"));
  6385. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6386. EXPECT_EQ(std::string("abcdefg"), res->body);
  6387. }
  6388. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6389. auto res = cli_.Get("/with-range", Headers{
  6390. {"Range", "bytes=0-"},
  6391. {"Accept-Encoding", ""},
  6392. });
  6393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6394. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6395. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6396. EXPECT_EQ(true, res->has_header("Content-Range"));
  6397. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6398. EXPECT_EQ(std::string("abcdefg"), res->body);
  6399. }
  6400. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6401. auto res = cli_.Get("/streamed-with-range",
  6402. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6404. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6405. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6406. EXPECT_EQ(false, res->has_header("Content-Range"));
  6407. EXPECT_EQ(267U, res->body.size());
  6408. // Check that both range contents are present
  6409. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6410. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6411. // Check that Content-Range headers are present for both ranges
  6412. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6413. std::string::npos);
  6414. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6415. std::string::npos);
  6416. }
  6417. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6418. Ranges ranges;
  6419. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6420. ranges.emplace_back(0, -1);
  6421. }
  6422. auto res = cli_.Get("/streamed-with-range?error",
  6423. Headers{{make_range_header(ranges)}});
  6424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6425. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6426. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6427. EXPECT_EQ(false, res->has_header("Content-Range"));
  6428. EXPECT_EQ(0U, res->body.size());
  6429. }
  6430. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6431. auto res = cli_.Get("/streamed-with-range",
  6432. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6435. EXPECT_EQ(5U, res->body.size());
  6436. // Check that overlapping ranges are coalesced into a single range
  6437. EXPECT_EQ("bcdef", res->body);
  6438. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6439. // Should be single range, not multipart
  6440. EXPECT_TRUE(res->has_header("Content-Range"));
  6441. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6442. }
  6443. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6444. auto res = cli_.Get("/streamed-with-range",
  6445. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6447. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6448. EXPECT_EQ(268U, res->body.size());
  6449. // Check that both range contents are present
  6450. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6451. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6452. // Check that Content-Range headers are present for both ranges
  6453. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6454. std::string::npos);
  6455. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6456. std::string::npos);
  6457. }
  6458. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6459. auto res = cli_.Get("/streamed-with-range",
  6460. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6462. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6463. EXPECT_EQ(269U, res->body.size());
  6464. // Check that both duplicate range contents are present
  6465. size_t first_abc = res->body.find("abc\r\n");
  6466. EXPECT_TRUE(first_abc != std::string::npos);
  6467. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6468. EXPECT_TRUE(second_abc != std::string::npos);
  6469. // Check that Content-Range headers are present for both ranges
  6470. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6471. EXPECT_TRUE(first_range != std::string::npos);
  6472. size_t second_range =
  6473. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6474. EXPECT_TRUE(second_range != std::string::npos);
  6475. }
  6476. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6477. auto res =
  6478. cli_.Get("/streamed-with-range?error",
  6479. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6481. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6482. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6483. EXPECT_EQ(false, res->has_header("Content-Range"));
  6484. EXPECT_EQ(0U, res->body.size());
  6485. }
  6486. TEST_F(ServerTest, GetStreamedEndless) {
  6487. uint64_t offset = 0;
  6488. auto res = cli_.Get("/streamed-cancel",
  6489. [&](const char * /*data*/, uint64_t data_length) {
  6490. if (offset < 100) {
  6491. offset += data_length;
  6492. return true;
  6493. }
  6494. return false;
  6495. });
  6496. ASSERT_TRUE(!res);
  6497. EXPECT_EQ(Error::Canceled, res.error());
  6498. }
  6499. TEST_F(ServerTest, ClientStop) {
  6500. std::atomic_size_t count{4};
  6501. std::vector<std::thread> threads;
  6502. for (auto i = count.load(); i != 0; --i) {
  6503. threads.emplace_back([&]() {
  6504. auto res = cli_.Get("/streamed-cancel",
  6505. [&](const char *, uint64_t) { return true; });
  6506. --count;
  6507. ASSERT_TRUE(!res);
  6508. EXPECT_TRUE(res.error() == Error::Canceled ||
  6509. res.error() == Error::Read || res.error() == Error::Write);
  6510. });
  6511. }
  6512. std::this_thread::sleep_for(std::chrono::seconds(2));
  6513. while (count != 0) {
  6514. cli_.stop();
  6515. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6516. }
  6517. for (auto &t : threads) {
  6518. t.join();
  6519. }
  6520. }
  6521. TEST_F(ServerTest, GetWithRange1) {
  6522. auto res = cli_.Get("/with-range", Headers{
  6523. make_range_header({{3, 5}}),
  6524. {"Accept-Encoding", ""},
  6525. });
  6526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6527. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6528. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6529. EXPECT_EQ(true, res->has_header("Content-Range"));
  6530. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6531. EXPECT_EQ(std::string("def"), res->body);
  6532. }
  6533. TEST_F(ServerTest, GetWithRange2) {
  6534. auto res = cli_.Get("/with-range", Headers{
  6535. make_range_header({{1, -1}}),
  6536. {"Accept-Encoding", ""},
  6537. });
  6538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6539. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6540. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6541. EXPECT_EQ(true, res->has_header("Content-Range"));
  6542. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6543. EXPECT_EQ(std::string("bcdefg"), res->body);
  6544. }
  6545. TEST_F(ServerTest, GetWithRange3) {
  6546. auto res = cli_.Get("/with-range", Headers{
  6547. make_range_header({{0, 0}}),
  6548. {"Accept-Encoding", ""},
  6549. });
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6552. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6553. EXPECT_EQ(true, res->has_header("Content-Range"));
  6554. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6555. EXPECT_EQ(std::string("a"), res->body);
  6556. }
  6557. TEST_F(ServerTest, GetWithRange4) {
  6558. auto res = cli_.Get("/with-range", Headers{
  6559. make_range_header({{-1, 2}}),
  6560. {"Accept-Encoding", ""},
  6561. });
  6562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6563. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6564. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6565. EXPECT_EQ(true, res->has_header("Content-Range"));
  6566. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6567. EXPECT_EQ(std::string("fg"), res->body);
  6568. }
  6569. TEST_F(ServerTest, GetWithRange5) {
  6570. auto res = cli_.Get("/with-range", Headers{
  6571. make_range_header({{0, 5}}),
  6572. {"Accept-Encoding", ""},
  6573. });
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6576. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6577. EXPECT_EQ(true, res->has_header("Content-Range"));
  6578. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6579. EXPECT_EQ(std::string("abcdef"), res->body);
  6580. }
  6581. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6582. auto res =
  6583. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6585. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6586. }
  6587. TEST_F(ServerTest, GetWithRangeMultipart) {
  6588. auto res =
  6589. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6591. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6592. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6593. EXPECT_EQ(false, res->has_header("Content-Range"));
  6594. EXPECT_EQ(267U, res->body.size());
  6595. }
  6596. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6597. auto res = cli_.Get("/with-range",
  6598. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6600. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6601. }
  6602. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6603. auto res = cli_.Get("/with-range-customized-response",
  6604. Headers{{make_range_header({{1, 2}})}});
  6605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6606. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6607. EXPECT_EQ(true, res->has_header("Content-Length"));
  6608. EXPECT_EQ(false, res->has_header("Content-Range"));
  6609. EXPECT_EQ(JSON_DATA, res->body);
  6610. }
  6611. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6612. auto res = cli_.Get("/with-range-customized-response",
  6613. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6615. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6616. EXPECT_EQ(true, res->has_header("Content-Length"));
  6617. EXPECT_EQ(false, res->has_header("Content-Range"));
  6618. EXPECT_EQ(JSON_DATA, res->body);
  6619. }
  6620. TEST_F(ServerTest, Issue1772) {
  6621. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6623. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6624. }
  6625. TEST_F(ServerTest, Issue609) {
  6626. auto res = cli_.Delete("/issue609");
  6627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6628. EXPECT_EQ(StatusCode::OK_200, res->status);
  6629. EXPECT_EQ(std::string("ok"), res->body);
  6630. }
  6631. TEST_F(ServerTest, GetStreamedChunked) {
  6632. auto res = cli_.Get("/streamed-chunked");
  6633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6634. EXPECT_EQ(StatusCode::OK_200, res->status);
  6635. EXPECT_EQ(std::string("123456789"), res->body);
  6636. }
  6637. TEST_F(ServerTest, GetStreamedChunked2) {
  6638. auto res = cli_.Get("/streamed-chunked2");
  6639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6640. EXPECT_EQ(StatusCode::OK_200, res->status);
  6641. EXPECT_EQ(std::string("123456789"), res->body);
  6642. }
  6643. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6644. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6646. EXPECT_EQ(StatusCode::OK_200, res->status);
  6647. EXPECT_EQ(std::string("123456789"), res->body);
  6648. EXPECT_TRUE(res->has_header("Trailer"));
  6649. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6650. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6651. // Trailers are now stored separately from headers (security fix)
  6652. EXPECT_EQ(2U, res->trailers.size());
  6653. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6654. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6655. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6656. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6657. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6658. // Verify trailers are NOT in headers (security verification)
  6659. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6660. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6661. }
  6662. TEST_F(ServerTest, LargeChunkedPost) {
  6663. Request req;
  6664. req.method = "POST";
  6665. req.path = "/large-chunked";
  6666. std::string host_and_port;
  6667. host_and_port += HOST;
  6668. host_and_port += ":";
  6669. host_and_port += std::to_string(PORT);
  6670. req.headers.emplace("Host", host_and_port.c_str());
  6671. req.headers.emplace("Accept", "*/*");
  6672. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6673. req.headers.emplace("Content-Type", "text/plain");
  6674. req.headers.emplace("Content-Length", "0");
  6675. req.headers.emplace("Transfer-Encoding", "chunked");
  6676. std::string long_string(30 * 1024u, 'a');
  6677. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6678. // Attempt to make a large enough post to exceed OS buffers, to test that
  6679. // the server handles short reads if the full chunk data isn't available.
  6680. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6681. auto res = std::make_shared<Response>();
  6682. auto error = Error::Success;
  6683. auto ret = cli_.send(req, *res, error);
  6684. ASSERT_TRUE(ret);
  6685. EXPECT_EQ(StatusCode::OK_200, res->status);
  6686. }
  6687. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6688. auto res = cli_.Get("/remote_addr");
  6689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6690. EXPECT_EQ(StatusCode::OK_200, res->status);
  6691. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6692. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6693. }
  6694. TEST_F(ServerTest, GetMethodLocalAddr) {
  6695. auto res = cli_.Get("/local_addr");
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. EXPECT_EQ(StatusCode::OK_200, res->status);
  6698. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6699. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6700. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6701. }
  6702. TEST_F(ServerTest, HTTPResponseSplitting) {
  6703. auto res = cli_.Get("/http_response_splitting");
  6704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6705. EXPECT_EQ(StatusCode::OK_200, res->status);
  6706. }
  6707. TEST_F(ServerTest, SlowRequest) {
  6708. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6709. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6710. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6711. }
  6712. #if 0
  6713. TEST_F(ServerTest, SlowPost) {
  6714. char buffer[64 * 1024];
  6715. memset(buffer, 0x42, sizeof(buffer));
  6716. auto res = cli_.Post(
  6717. "/slowpost", 64 * 1024 * 1024,
  6718. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6719. auto ret = sink.write(buffer, sizeof(buffer));
  6720. EXPECT_TRUE(ret);
  6721. return true;
  6722. },
  6723. "text/plain");
  6724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6725. EXPECT_EQ(StatusCode::OK_200, res->status);
  6726. }
  6727. TEST_F(ServerTest, SlowPostFail) {
  6728. char buffer[64 * 1024];
  6729. memset(buffer, 0x42, sizeof(buffer));
  6730. cli_.set_write_timeout(std::chrono::seconds(0));
  6731. auto res = cli_.Post(
  6732. "/slowpost", 64 * 1024 * 1024,
  6733. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6734. sink.write(buffer, sizeof(buffer));
  6735. return true;
  6736. },
  6737. "text/plain");
  6738. ASSERT_TRUE(!res);
  6739. EXPECT_EQ(Error::Write, res.error());
  6740. }
  6741. #endif
  6742. TEST_F(ServerTest, Put) {
  6743. auto res = cli_.Put("/put", "PUT", "text/plain");
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::OK_200, res->status);
  6746. EXPECT_EQ("PUT", res->body);
  6747. }
  6748. TEST_F(ServerTest, PutWithContentProvider) {
  6749. auto res = cli_.Put(
  6750. "/put", 3,
  6751. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6752. sink.os << "PUT";
  6753. return true;
  6754. },
  6755. "text/plain");
  6756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6757. EXPECT_EQ(StatusCode::OK_200, res->status);
  6758. EXPECT_EQ("PUT", res->body);
  6759. }
  6760. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6761. auto res = cli_.Post(
  6762. "/post", 42,
  6763. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6764. return false;
  6765. },
  6766. "text/plain");
  6767. ASSERT_TRUE(!res);
  6768. EXPECT_EQ(Error::Canceled, res.error());
  6769. }
  6770. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6771. auto res = cli_.Put(
  6772. "/put",
  6773. [](size_t /*offset*/, DataSink &sink) {
  6774. sink.os << "PUT";
  6775. sink.done();
  6776. return true;
  6777. },
  6778. "text/plain");
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. EXPECT_EQ("PUT", res->body);
  6782. }
  6783. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6784. auto res = cli_.Post(
  6785. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6786. "text/plain");
  6787. ASSERT_TRUE(!res);
  6788. EXPECT_EQ(Error::Canceled, res.error());
  6789. }
  6790. TEST_F(ServerTest, PostLoopBack) {
  6791. std::string body;
  6792. auto res = cli_.Post(
  6793. "/post-loopback", 9,
  6794. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6795. EXPECT_EQ(9u, length);
  6796. sink.write("123", 3);
  6797. sink.write("456", 3);
  6798. sink.write("789", 3);
  6799. return true;
  6800. },
  6801. "text/plain",
  6802. [&body](const char *data, size_t data_length) {
  6803. body.append(data, data_length);
  6804. return true;
  6805. });
  6806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. EXPECT_EQ("123456789", body);
  6809. }
  6810. TEST_F(ServerTest, PutLoopBack) {
  6811. std::string body;
  6812. auto res = cli_.Put(
  6813. "/put-loopback", 9,
  6814. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6815. EXPECT_EQ(9u, length);
  6816. sink.write("123", 3);
  6817. sink.write("456", 3);
  6818. sink.write("789", 3);
  6819. return true;
  6820. },
  6821. "text/plain",
  6822. [&body](const char *data, size_t data_length) {
  6823. body.append(data, data_length);
  6824. return true;
  6825. });
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::OK_200, res->status);
  6828. EXPECT_EQ("123456789", body);
  6829. }
  6830. TEST_F(ServerTest, PatchLoopBack) {
  6831. std::string body;
  6832. auto res = cli_.Patch(
  6833. "/patch-loopback", 9,
  6834. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6835. EXPECT_EQ(9u, length);
  6836. sink.write("123", 3);
  6837. sink.write("456", 3);
  6838. sink.write("789", 3);
  6839. return true;
  6840. },
  6841. "text/plain",
  6842. [&body](const char *data, size_t data_length) {
  6843. body.append(data, data_length);
  6844. return true;
  6845. });
  6846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6847. EXPECT_EQ(StatusCode::OK_200, res->status);
  6848. EXPECT_EQ("123456789", body);
  6849. }
  6850. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6851. std::string body;
  6852. auto res = cli_.Post(
  6853. "/post-loopback",
  6854. [](size_t /*offset*/, DataSink &sink) {
  6855. sink.write("123", 3);
  6856. sink.write("456", 3);
  6857. sink.write("789", 3);
  6858. sink.done();
  6859. return true;
  6860. },
  6861. "text/plain",
  6862. [&body](const char *data, size_t data_length) {
  6863. body.append(data, data_length);
  6864. return true;
  6865. });
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. EXPECT_EQ("123456789", body);
  6869. }
  6870. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6871. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6872. cli_.set_compress(true);
  6873. auto res = cli_.Put(
  6874. "/put", 3,
  6875. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6876. sink.os << "PUT";
  6877. return true;
  6878. },
  6879. "text/plain");
  6880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6881. EXPECT_EQ(StatusCode::OK_200, res->status);
  6882. EXPECT_EQ("PUT", res->body);
  6883. }
  6884. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6885. cli_.set_compress(true);
  6886. auto res = cli_.Post(
  6887. "/post", 42,
  6888. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6889. return false;
  6890. },
  6891. "text/plain");
  6892. ASSERT_TRUE(!res);
  6893. EXPECT_EQ(Error::Canceled, res.error());
  6894. }
  6895. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6896. cli_.set_compress(true);
  6897. auto res = cli_.Put(
  6898. "/put",
  6899. [](size_t /*offset*/, DataSink &sink) {
  6900. sink.os << "PUT";
  6901. sink.done();
  6902. return true;
  6903. },
  6904. "text/plain");
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::OK_200, res->status);
  6907. EXPECT_EQ("PUT", res->body);
  6908. }
  6909. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6910. cli_.set_compress(true);
  6911. auto res = cli_.Post(
  6912. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6913. "text/plain");
  6914. ASSERT_TRUE(!res);
  6915. EXPECT_EQ(Error::Canceled, res.error());
  6916. }
  6917. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6918. cli_.set_compress(true);
  6919. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6921. EXPECT_EQ(StatusCode::OK_200, res->status);
  6922. EXPECT_EQ(LARGE_DATA, res->body);
  6923. }
  6924. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6925. #ifdef CPPHTTPLIB_SSL_ENABLED
  6926. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6927. Client cli(s.c_str());
  6928. cli.enable_server_certificate_verification(false);
  6929. #else
  6930. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6931. Client cli(s.c_str());
  6932. #endif
  6933. cli.set_compress(true);
  6934. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6936. EXPECT_EQ(StatusCode::OK_200, res->status);
  6937. EXPECT_EQ(LARGE_DATA, res->body);
  6938. // The compressed size should be less than a 10th of the original. May vary
  6939. // depending on the zlib library.
  6940. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6941. static_cast<uint64_t>(10 * 1024 * 1024));
  6942. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6943. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6944. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6945. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6946. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6947. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6948. #endif
  6949. }
  6950. TEST_F(ServerTest, PutContentWithDeflate) {
  6951. cli_.set_compress(false);
  6952. Headers headers;
  6953. headers.emplace("Content-Encoding", "deflate");
  6954. // PUT in deflate format:
  6955. auto res = cli_.Put("/put", headers,
  6956. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6958. EXPECT_EQ(StatusCode::OK_200, res->status);
  6959. EXPECT_EQ("PUT", res->body);
  6960. }
  6961. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6962. Headers headers;
  6963. headers.emplace("Accept-Encoding", "gzip, deflate");
  6964. auto res = cli_.Get("/streamed-chunked", headers);
  6965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6966. EXPECT_EQ(StatusCode::OK_200, res->status);
  6967. EXPECT_EQ(std::string("123456789"), res->body);
  6968. }
  6969. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6970. Headers headers;
  6971. headers.emplace("Accept-Encoding", "gzip, deflate");
  6972. auto res = cli_.Get("/streamed-chunked2", headers);
  6973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6974. EXPECT_EQ(StatusCode::OK_200, res->status);
  6975. EXPECT_EQ(std::string("123456789"), res->body);
  6976. }
  6977. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6978. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6980. EXPECT_EQ(StatusCode::OK_200, res->status);
  6981. }
  6982. TEST(GzipDecompressor, ChunkedDecompression) {
  6983. std::string data;
  6984. for (size_t i = 0; i < 32 * 1024; ++i) {
  6985. data.push_back(static_cast<char>('a' + i % 26));
  6986. }
  6987. std::string compressed_data;
  6988. {
  6989. httplib::detail::gzip_compressor compressor;
  6990. bool result = compressor.compress(
  6991. data.data(), data.size(),
  6992. /*last=*/true,
  6993. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6994. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6995. compressed_data_size);
  6996. return true;
  6997. });
  6998. ASSERT_TRUE(result);
  6999. }
  7000. std::string decompressed_data;
  7001. {
  7002. httplib::detail::gzip_decompressor decompressor;
  7003. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7004. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7005. size_t chunk_size = 130;
  7006. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7007. chunk_begin += chunk_size) {
  7008. size_t current_chunk_size =
  7009. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7010. bool result = decompressor.decompress(
  7011. compressed_data.data() + chunk_begin, current_chunk_size,
  7012. [&](const char *decompressed_data_chunk,
  7013. size_t decompressed_data_chunk_size) {
  7014. decompressed_data.insert(decompressed_data.size(),
  7015. decompressed_data_chunk,
  7016. decompressed_data_chunk_size);
  7017. return true;
  7018. });
  7019. ASSERT_TRUE(result);
  7020. }
  7021. }
  7022. ASSERT_EQ(data, decompressed_data);
  7023. }
  7024. TEST(GzipDecompressor, DeflateDecompression) {
  7025. std::string original_text = "Raw deflate without gzip";
  7026. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7027. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7028. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7029. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7030. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7031. std::string decompressed_data;
  7032. {
  7033. httplib::detail::gzip_decompressor decompressor;
  7034. bool result = decompressor.decompress(
  7035. compressed_data.data(), compressed_data.size(),
  7036. [&](const char *decompressed_data_chunk,
  7037. size_t decompressed_data_chunk_size) {
  7038. decompressed_data.insert(decompressed_data.size(),
  7039. decompressed_data_chunk,
  7040. decompressed_data_chunk_size);
  7041. return true;
  7042. });
  7043. ASSERT_TRUE(result);
  7044. }
  7045. ASSERT_EQ(original_text, decompressed_data);
  7046. }
  7047. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7048. std::string original_text = "Raw deflate without gzip";
  7049. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7050. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7051. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7052. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7053. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7054. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7055. std::string decompressed_data;
  7056. {
  7057. httplib::detail::gzip_decompressor decompressor;
  7058. bool result = decompressor.decompress(
  7059. compressed_data.data(), compressed_data.size(),
  7060. [&](const char *decompressed_data_chunk,
  7061. size_t decompressed_data_chunk_size) {
  7062. decompressed_data.insert(decompressed_data.size(),
  7063. decompressed_data_chunk,
  7064. decompressed_data_chunk_size);
  7065. return true;
  7066. });
  7067. ASSERT_TRUE(result);
  7068. }
  7069. ASSERT_EQ(original_text, decompressed_data);
  7070. }
  7071. #endif
  7072. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7073. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7074. Headers headers;
  7075. headers.emplace("Accept-Encoding", "br");
  7076. auto res = cli_.Get("/streamed-chunked", headers);
  7077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7078. EXPECT_EQ(StatusCode::OK_200, res->status);
  7079. EXPECT_EQ(std::string("123456789"), res->body);
  7080. }
  7081. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7082. Headers headers;
  7083. headers.emplace("Accept-Encoding", "br");
  7084. auto res = cli_.Get("/streamed-chunked2", headers);
  7085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7086. EXPECT_EQ(StatusCode::OK_200, res->status);
  7087. EXPECT_EQ(std::string("123456789"), res->body);
  7088. }
  7089. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7090. cli_.set_compress(true);
  7091. auto res = cli_.Put(
  7092. "/put", 3,
  7093. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7094. sink.os << "PUT";
  7095. return true;
  7096. },
  7097. "text/plain");
  7098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7099. EXPECT_EQ(StatusCode::OK_200, res->status);
  7100. EXPECT_EQ("PUT", res->body);
  7101. }
  7102. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7103. cli_.set_compress(true);
  7104. auto res = cli_.Put(
  7105. "/put",
  7106. [](size_t /*offset*/, DataSink &sink) {
  7107. sink.os << "PUT";
  7108. sink.done();
  7109. return true;
  7110. },
  7111. "text/plain");
  7112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7113. EXPECT_EQ(StatusCode::OK_200, res->status);
  7114. EXPECT_EQ("PUT", res->body);
  7115. }
  7116. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7117. cli_.set_compress(true);
  7118. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7120. EXPECT_EQ(StatusCode::OK_200, res->status);
  7121. EXPECT_EQ(LARGE_DATA, res->body);
  7122. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7123. }
  7124. #endif
  7125. TEST_F(ServerTest, Patch) {
  7126. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7128. EXPECT_EQ(StatusCode::OK_200, res->status);
  7129. EXPECT_EQ("PATCH", res->body);
  7130. }
  7131. TEST_F(ServerTest, Delete) {
  7132. auto res = cli_.Delete("/delete");
  7133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7134. EXPECT_EQ(StatusCode::OK_200, res->status);
  7135. EXPECT_EQ("DELETE", res->body);
  7136. }
  7137. TEST_F(ServerTest, DeleteContentReceiver) {
  7138. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7140. EXPECT_EQ(StatusCode::OK_200, res->status);
  7141. EXPECT_EQ("content", res->body);
  7142. }
  7143. TEST_F(ServerTest, Options) {
  7144. auto res = cli_.Options("*");
  7145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7146. EXPECT_EQ(StatusCode::OK_200, res->status);
  7147. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7148. EXPECT_TRUE(res->body.empty());
  7149. }
  7150. TEST_F(ServerTest, URL) {
  7151. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7153. EXPECT_EQ(StatusCode::OK_200, res->status);
  7154. }
  7155. TEST_F(ServerTest, ArrayParam) {
  7156. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7158. EXPECT_EQ(StatusCode::OK_200, res->status);
  7159. }
  7160. TEST_F(ServerTest, ArrayParamValues) {
  7161. auto res =
  7162. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7164. EXPECT_EQ(StatusCode::OK_200, res->status);
  7165. }
  7166. TEST_F(ServerTest, NoMultipleHeaders) {
  7167. Headers headers = {{"Content-Length", "5"}};
  7168. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7169. "text/plain");
  7170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7171. EXPECT_EQ(StatusCode::OK_200, res->status);
  7172. }
  7173. TEST_F(ServerTest, PostContentReceiver) {
  7174. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7176. ASSERT_EQ(StatusCode::OK_200, res->status);
  7177. ASSERT_EQ("content", res->body);
  7178. }
  7179. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7180. UploadFormDataItems items = {
  7181. {"text1", "text default", "", ""},
  7182. {"text2", "aωb", "", ""},
  7183. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7184. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7185. {"file3", "", "", "application/octet-stream"},
  7186. };
  7187. auto res = cli_.Post("/content_receiver", items);
  7188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7189. EXPECT_EQ(StatusCode::OK_200, res->status);
  7190. }
  7191. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7192. UploadFormDataItems items = {
  7193. {"text1", "text default", "", ""},
  7194. {"text2", "aωb", "", ""},
  7195. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7196. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7197. {"file3", "", "", "application/octet-stream"},
  7198. };
  7199. auto boundary = std::string("+++++");
  7200. std::string body;
  7201. for (const auto &item : items) {
  7202. body += "--" + boundary + "\r\n";
  7203. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7204. if (!item.filename.empty()) {
  7205. body += "; filename=\"" + item.filename + "\"";
  7206. }
  7207. body += "\r\n";
  7208. if (!item.content_type.empty()) {
  7209. body += "Content-Type: " + item.content_type + "\r\n";
  7210. }
  7211. body += "\r\n";
  7212. body += item.content + "\r\n";
  7213. }
  7214. body += "--" + boundary + "--\r\n";
  7215. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7216. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7218. EXPECT_EQ(StatusCode::OK_200, res->status);
  7219. }
  7220. TEST(MultipartFormDataTest, FieldEscaping) {
  7221. Server svr;
  7222. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7223. const ContentReader &content_reader) {
  7224. ASSERT_TRUE(req.is_multipart_form_data());
  7225. std::vector<FormData> received;
  7226. content_reader(
  7227. [&](const FormData &file) {
  7228. received.push_back(file);
  7229. return true;
  7230. },
  7231. [&](const char *data, size_t data_length) {
  7232. received.back().content.append(data, data_length);
  7233. return true;
  7234. });
  7235. // '"', CR and LF in names and filenames are escaped following the
  7236. // WHATWG HTML standard, so each part still parses as a single part
  7237. // with no injected headers. Content types get CR/LF escaped too,
  7238. // while '"' (legal there, e.g. quoted charset) is preserved.
  7239. ASSERT_EQ(4U, received.size());
  7240. EXPECT_EQ("na%22me", received[0].name);
  7241. EXPECT_EQ("quoted name", received[0].content);
  7242. EXPECT_EQ("file", received[1].name);
  7243. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7244. received[1].filename);
  7245. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7246. EXPECT_EQ("injected", received[1].content);
  7247. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7248. EXPECT_EQ("my%22file.txt", received[2].filename);
  7249. EXPECT_EQ("cr lf name", received[2].content);
  7250. EXPECT_EQ("typed", received[3].name);
  7251. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7252. received[3].content_type);
  7253. EXPECT_EQ("typed content", received[3].content);
  7254. });
  7255. auto port = svr.bind_to_any_port("localhost");
  7256. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7257. auto se = detail::scope_exit([&] {
  7258. svr.stop();
  7259. t.join();
  7260. ASSERT_FALSE(svr.is_running());
  7261. });
  7262. svr.wait_until_ready();
  7263. Client cli("localhost", port);
  7264. UploadFormDataItems items = {
  7265. {"na\"me", "quoted name", "", ""},
  7266. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7267. "application/octet-stream"},
  7268. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7269. {"typed", "typed content", "",
  7270. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7271. };
  7272. auto res = cli.Post("/post", items);
  7273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7274. EXPECT_EQ(StatusCode::OK_200, res->status);
  7275. }
  7276. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7277. const UploadFormDataItems items = {
  7278. {"name1", "Content 1", "", ""},
  7279. {"name2", "Content 2", "file2.txt", "text/plain"},
  7280. };
  7281. Server svr;
  7282. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7283. const ContentReader &content_reader) {
  7284. ASSERT_TRUE(req.is_multipart_form_data());
  7285. std::vector<FormData> received;
  7286. content_reader(
  7287. [&](const FormData &file) {
  7288. received.push_back(file);
  7289. return true;
  7290. },
  7291. [&](const char *data, size_t data_length) {
  7292. received.back().content.append(data, data_length);
  7293. return true;
  7294. });
  7295. ASSERT_EQ(2U, received.size());
  7296. EXPECT_EQ("name1", received[0].name);
  7297. EXPECT_EQ("Content 1", received[0].content);
  7298. EXPECT_EQ("name2", received[1].name);
  7299. EXPECT_EQ("Content 2", received[1].content);
  7300. EXPECT_EQ("file2.txt", received[1].filename);
  7301. EXPECT_EQ("text/plain", received[1].content_type);
  7302. });
  7303. auto port = svr.bind_to_any_port("localhost");
  7304. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7305. auto se = detail::scope_exit([&] {
  7306. svr.stop();
  7307. t.join();
  7308. ASSERT_FALSE(svr.is_running());
  7309. });
  7310. svr.wait_until_ready();
  7311. Client cli("localhost", port);
  7312. // Whole-body serialization with a generated boundary
  7313. {
  7314. MultipartFormDataWriter writer;
  7315. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7316. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7317. writer.content_type());
  7318. auto body = writer.serialize(items);
  7319. EXPECT_EQ(body.size(), writer.content_length(items));
  7320. auto res = cli.Post("/post", body, writer.content_type());
  7321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7322. EXPECT_EQ(StatusCode::OK_200, res->status);
  7323. }
  7324. // Per-part framing with a custom boundary via a content provider
  7325. {
  7326. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7327. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7328. MultipartFormDataWriter writer("custom-boundary_123");
  7329. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7330. std::string body;
  7331. for (const auto &item : items) {
  7332. body += writer.item_begin(item);
  7333. body += item.content;
  7334. body += MultipartFormDataWriter::item_end();
  7335. }
  7336. body += writer.finish();
  7337. EXPECT_EQ(body.size(), writer.content_length(items));
  7338. auto res = cli.Post(
  7339. "/post", body.size(),
  7340. [&](size_t offset, size_t length, DataSink &sink) {
  7341. sink.write(body.data() + offset, length);
  7342. return true;
  7343. },
  7344. writer.content_type());
  7345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7346. EXPECT_EQ(StatusCode::OK_200, res->status);
  7347. }
  7348. }
  7349. TEST_F(ServerTest, PostContentReceiverGzip) {
  7350. cli_.set_compress(true);
  7351. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7353. ASSERT_EQ(StatusCode::OK_200, res->status);
  7354. ASSERT_EQ("content", res->body);
  7355. }
  7356. TEST_F(ServerTest, PutContentReceiver) {
  7357. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7359. ASSERT_EQ(StatusCode::OK_200, res->status);
  7360. ASSERT_EQ("content", res->body);
  7361. }
  7362. TEST_F(ServerTest, PatchContentReceiver) {
  7363. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7365. ASSERT_EQ(StatusCode::OK_200, res->status);
  7366. ASSERT_EQ("content", res->body);
  7367. }
  7368. template <typename ClientType>
  7369. void TestWithHeadersAndContentReceiver(
  7370. ClientType &cli,
  7371. std::function<Result(ClientType &, const std::string &, const Headers &,
  7372. const std::string &, const std::string &,
  7373. ContentReceiver, DownloadProgress)>
  7374. request_func) {
  7375. Headers headers;
  7376. headers.emplace("X-Custom-Header", "test-value");
  7377. std::string received_body;
  7378. auto res = request_func(
  7379. cli, "/content_receiver", headers, "content", "application/json",
  7380. [&](const char *data, size_t data_length) {
  7381. received_body.append(data, data_length);
  7382. return true;
  7383. },
  7384. nullptr);
  7385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7386. EXPECT_EQ(StatusCode::OK_200, res->status);
  7387. EXPECT_EQ("content", received_body);
  7388. }
  7389. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7390. #ifdef CPPHTTPLIB_SSL_ENABLED
  7391. using ClientT = SSLClient;
  7392. #else
  7393. using ClientT = Client;
  7394. #endif
  7395. TestWithHeadersAndContentReceiver<ClientT>(
  7396. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7397. const std::string &body, const std::string &content_type,
  7398. ContentReceiver receiver, DownloadProgress progress) {
  7399. return cli.Post(path, headers, body, content_type, receiver, progress);
  7400. });
  7401. }
  7402. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7403. #ifdef CPPHTTPLIB_SSL_ENABLED
  7404. using ClientT = SSLClient;
  7405. #else
  7406. using ClientT = Client;
  7407. #endif
  7408. TestWithHeadersAndContentReceiver<ClientT>(
  7409. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7410. const std::string &body, const std::string &content_type,
  7411. ContentReceiver receiver, DownloadProgress progress) {
  7412. return cli.Put(path, headers, body, content_type, receiver, progress);
  7413. });
  7414. }
  7415. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7416. #ifdef CPPHTTPLIB_SSL_ENABLED
  7417. using ClientT = SSLClient;
  7418. #else
  7419. using ClientT = Client;
  7420. #endif
  7421. TestWithHeadersAndContentReceiver<ClientT>(
  7422. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7423. const std::string &body, const std::string &content_type,
  7424. ContentReceiver receiver, DownloadProgress progress) {
  7425. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7426. });
  7427. }
  7428. template <typename ClientType>
  7429. void TestWithHeadersAndContentReceiverWithProgress(
  7430. ClientType &cli,
  7431. std::function<Result(ClientType &, const std::string &, const Headers &,
  7432. const std::string &, const std::string &,
  7433. ContentReceiver, DownloadProgress)>
  7434. request_func) {
  7435. Headers headers;
  7436. headers.emplace("X-Test-Header", "progress-test");
  7437. std::string received_body;
  7438. auto progress_called = false;
  7439. auto res = request_func(
  7440. cli, "/content_receiver", headers, "content", "text/plain",
  7441. [&](const char *data, size_t data_length) {
  7442. received_body.append(data, data_length);
  7443. return true;
  7444. },
  7445. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7446. progress_called = true;
  7447. return true;
  7448. });
  7449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7450. EXPECT_EQ(StatusCode::OK_200, res->status);
  7451. EXPECT_EQ("content", received_body);
  7452. EXPECT_TRUE(progress_called);
  7453. }
  7454. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7455. #ifdef CPPHTTPLIB_SSL_ENABLED
  7456. using ClientT = SSLClient;
  7457. #else
  7458. using ClientT = Client;
  7459. #endif
  7460. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7461. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7462. const std::string &body, const std::string &content_type,
  7463. ContentReceiver receiver, DownloadProgress progress) {
  7464. return cli.Post(path, headers, body, content_type, receiver, progress);
  7465. });
  7466. }
  7467. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7468. #ifdef CPPHTTPLIB_SSL_ENABLED
  7469. using ClientT = SSLClient;
  7470. #else
  7471. using ClientT = Client;
  7472. #endif
  7473. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7474. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7475. const std::string &body, const std::string &content_type,
  7476. ContentReceiver receiver, DownloadProgress progress) {
  7477. return cli.Put(path, headers, body, content_type, receiver, progress);
  7478. });
  7479. }
  7480. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7481. #ifdef CPPHTTPLIB_SSL_ENABLED
  7482. using ClientT = SSLClient;
  7483. #else
  7484. using ClientT = Client;
  7485. #endif
  7486. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7487. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7488. const std::string &body, const std::string &content_type,
  7489. ContentReceiver receiver, DownloadProgress progress) {
  7490. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7491. });
  7492. }
  7493. template <typename ClientType>
  7494. void TestWithHeadersAndContentReceiverError(
  7495. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7496. const Headers &, const std::string &,
  7497. const std::string &, ContentReceiver)>
  7498. request_func) {
  7499. Headers headers;
  7500. headers.emplace("X-Error-Test", "true");
  7501. std::string received_body;
  7502. auto receiver_failed = false;
  7503. auto res =
  7504. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7505. [&](const char *data, size_t data_length) {
  7506. received_body.append(data, data_length);
  7507. receiver_failed = true;
  7508. return false;
  7509. });
  7510. ASSERT_FALSE(res);
  7511. EXPECT_TRUE(receiver_failed);
  7512. }
  7513. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7514. #ifdef CPPHTTPLIB_SSL_ENABLED
  7515. using ClientT = SSLClient;
  7516. #else
  7517. using ClientT = Client;
  7518. #endif
  7519. TestWithHeadersAndContentReceiverError<ClientT>(
  7520. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7521. const std::string &body, const std::string &content_type,
  7522. ContentReceiver receiver) {
  7523. return cli.Post(path, headers, body, content_type, receiver);
  7524. });
  7525. }
  7526. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7527. #ifdef CPPHTTPLIB_SSL_ENABLED
  7528. using ClientT = SSLClient;
  7529. #else
  7530. using ClientT = Client;
  7531. #endif
  7532. TestWithHeadersAndContentReceiverError<ClientT>(
  7533. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7534. const std::string &body, const std::string &content_type,
  7535. ContentReceiver receiver) {
  7536. return cli.Put(path, headers, body, content_type, receiver);
  7537. });
  7538. }
  7539. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7540. #ifdef CPPHTTPLIB_SSL_ENABLED
  7541. using ClientT = SSLClient;
  7542. #else
  7543. using ClientT = Client;
  7544. #endif
  7545. TestWithHeadersAndContentReceiverError<ClientT>(
  7546. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7547. const std::string &body, const std::string &content_type,
  7548. ContentReceiver receiver) {
  7549. return cli.Patch(path, headers, body, content_type, receiver);
  7550. });
  7551. }
  7552. TEST_F(ServerTest, PostQueryStringAndBody) {
  7553. auto res =
  7554. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7556. ASSERT_EQ(StatusCode::OK_200, res->status);
  7557. }
  7558. TEST_F(ServerTest, HTTP2Magic) {
  7559. Request req;
  7560. req.method = "PRI";
  7561. req.path = "*";
  7562. req.body = "SM";
  7563. auto res = std::make_shared<Response>();
  7564. auto error = Error::Success;
  7565. auto ret = cli_.send(req, *res, error);
  7566. ASSERT_TRUE(ret);
  7567. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7568. }
  7569. TEST_F(ServerTest, KeepAlive) {
  7570. auto res = cli_.Get("/hi");
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::OK_200, res->status);
  7573. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7574. EXPECT_EQ("Hello World!", res->body);
  7575. res = cli_.Get("/hi");
  7576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7577. EXPECT_EQ(StatusCode::OK_200, res->status);
  7578. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7579. EXPECT_EQ("Hello World!", res->body);
  7580. res = cli_.Get("/hi");
  7581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7582. EXPECT_EQ(StatusCode::OK_200, res->status);
  7583. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7584. EXPECT_EQ("Hello World!", res->body);
  7585. res = cli_.Get("/not-exist");
  7586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7588. res = cli_.Post("/empty", "", "text/plain");
  7589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7590. EXPECT_EQ(StatusCode::OK_200, res->status);
  7591. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7592. EXPECT_EQ("empty", res->body);
  7593. EXPECT_EQ("close", res->get_header_value("Connection"));
  7594. res = cli_.Post(
  7595. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7596. "text/plain");
  7597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7598. EXPECT_EQ(StatusCode::OK_200, res->status);
  7599. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7600. EXPECT_EQ("empty", res->body);
  7601. cli_.set_keep_alive(false);
  7602. res = cli_.Get("/last-request");
  7603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7604. EXPECT_EQ(StatusCode::OK_200, res->status);
  7605. EXPECT_EQ("close", res->get_header_value("Connection"));
  7606. }
  7607. TEST_F(ServerTest, TooManyRedirect) {
  7608. cli_.set_follow_location(true);
  7609. auto res = cli_.Get("/redirect/0");
  7610. ASSERT_TRUE(!res);
  7611. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7612. }
  7613. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7614. Request req;
  7615. req.method = "FOOBAR";
  7616. req.path = "/hi";
  7617. cli_.set_keep_alive(true);
  7618. auto res = cli_.send(req);
  7619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7620. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7621. EXPECT_EQ("close", res->get_header_value("Connection"));
  7622. EXPECT_FALSE(cli_.is_socket_open());
  7623. }
  7624. TEST_F(ServerTest, CustomRouteReadsBody) {
  7625. const std::string xml =
  7626. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7627. Request req;
  7628. req.method = "PROPFIND";
  7629. req.path = "/dav/dir";
  7630. req.set_header("Depth", "1");
  7631. req.body = xml;
  7632. auto res = cli_.send(req);
  7633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7634. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7635. EXPECT_EQ(xml, res->body);
  7636. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7637. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7638. }
  7639. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7640. Request req;
  7641. req.method = "PROPFIND";
  7642. req.path = "/dav/42";
  7643. auto res = cli_.send(req);
  7644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7645. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7646. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7647. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7648. }
  7649. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7650. Request req;
  7651. req.method = "PROPFIND";
  7652. req.path = "/dav-re/123";
  7653. auto res = cli_.send(req);
  7654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7655. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7656. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7657. }
  7658. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7659. Request req;
  7660. req.method = "MKCOL";
  7661. req.path = "/dav-mkcol";
  7662. auto res = cli_.send(req);
  7663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7664. EXPECT_EQ(StatusCode::Created_201, res->status);
  7665. }
  7666. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7667. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7668. Request req;
  7669. req.method = "REPORT";
  7670. req.path = "/dav-report";
  7671. req.body = xml;
  7672. auto res = cli_.send(req);
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7675. EXPECT_EQ(xml, res->body);
  7676. }
  7677. // A content reader route must fire even when the request carries no body,
  7678. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7679. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7680. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7681. Request req;
  7682. req.method = "REPORT";
  7683. req.path = "/dav-report";
  7684. auto res = cli_.send(req);
  7685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7686. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7687. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7688. }
  7689. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7690. Request req;
  7691. req.method = "PROPFIND";
  7692. req.path = "/not-dav";
  7693. auto res = cli_.send(req);
  7694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7695. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7696. }
  7697. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7698. Request req;
  7699. req.method = "UNLOCK";
  7700. req.path = "/dav/dir";
  7701. cli_.set_keep_alive(true);
  7702. auto res = cli_.send(req);
  7703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7704. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7705. EXPECT_EQ("close", res->get_header_value("Connection"));
  7706. EXPECT_FALSE(cli_.is_socket_open());
  7707. }
  7708. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7709. // The mount point serves this path, but only for GET and HEAD.
  7710. auto get_res = cli_.Get("/dir/index.html");
  7711. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7712. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7713. Request req;
  7714. req.method = "PROPFIND";
  7715. req.path = "/dir/index.html";
  7716. auto res = cli_.send(req);
  7717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7718. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7719. }
  7720. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7721. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7722. cli_.set_keep_alive(true);
  7723. for (auto i = 0; i < 2; i++) {
  7724. Request req;
  7725. req.method = "PROPFIND";
  7726. req.path = "/dav/dir";
  7727. req.body = xml;
  7728. auto res = cli_.send(req);
  7729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7730. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7731. EXPECT_EQ(xml, res->body);
  7732. EXPECT_TRUE(cli_.is_socket_open());
  7733. }
  7734. // A built-in method must still be served on the same connection.
  7735. cli_.set_keep_alive(false);
  7736. auto res = cli_.Get("/hi");
  7737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7738. EXPECT_EQ(StatusCode::OK_200, res->status);
  7739. EXPECT_EQ("close", res->get_header_value("Connection"));
  7740. }
  7741. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7742. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7743. Request req;
  7744. req.method = "PROPFIND";
  7745. req.path = "/dav/dir";
  7746. req.set_header("Expect", "100-continue");
  7747. req.body = xml;
  7748. auto res = cli_.send(req);
  7749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7750. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7751. EXPECT_EQ(xml, res->body);
  7752. }
  7753. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7754. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7755. TEST_F(ServerTest, Gzip) {
  7756. Headers headers;
  7757. headers.emplace("Accept-Encoding", "gzip, deflate");
  7758. auto res = cli_.Get("/compress", headers);
  7759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7760. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7761. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7762. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7763. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7764. "7890123456789012345678901234567890",
  7765. res->body);
  7766. EXPECT_EQ(StatusCode::OK_200, res->status);
  7767. }
  7768. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7769. Headers headers;
  7770. headers.emplace("Accept-Encoding", "gzip, deflate");
  7771. auto res = cli_.Get("/compress-with-charset", headers);
  7772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7773. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7774. EXPECT_EQ("application/json; charset=utf-8",
  7775. res->get_header_value("Content-Type"));
  7776. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7777. "7890123456789012345678901234567890",
  7778. res->body);
  7779. EXPECT_EQ(StatusCode::OK_200, res->status);
  7780. }
  7781. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7782. Headers headers;
  7783. headers.emplace("Accept-Encoding", "");
  7784. auto res = cli_.Get("/compress", headers);
  7785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7786. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7787. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7788. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7789. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7790. "7890123456789012345678901234567890",
  7791. res->body);
  7792. EXPECT_EQ(StatusCode::OK_200, res->status);
  7793. }
  7794. TEST_F(ServerTest, GzipWithContentReceiver) {
  7795. Headers headers;
  7796. headers.emplace("Accept-Encoding", "gzip, deflate");
  7797. std::string body;
  7798. auto res = cli_.Get("/compress", headers,
  7799. [&](const char *data, uint64_t data_length) {
  7800. EXPECT_EQ(100U, data_length);
  7801. body.append(data, data_length);
  7802. return true;
  7803. });
  7804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7805. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7806. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7807. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7808. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7809. "7890123456789012345678901234567890",
  7810. body);
  7811. EXPECT_EQ(StatusCode::OK_200, res->status);
  7812. }
  7813. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7814. Headers headers;
  7815. headers.emplace("Accept-Encoding", "gzip, deflate");
  7816. cli_.set_decompress(false);
  7817. auto res = cli_.Get("/compress", headers);
  7818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7819. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7820. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7821. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7822. EXPECT_EQ(33U, res->body.size());
  7823. EXPECT_EQ(StatusCode::OK_200, res->status);
  7824. }
  7825. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7826. Headers headers;
  7827. headers.emplace("Accept-Encoding", "");
  7828. std::string body;
  7829. auto res = cli_.Get("/compress", headers,
  7830. [&](const char *data, uint64_t data_length) {
  7831. EXPECT_EQ(100U, data_length);
  7832. body.append(data, data_length);
  7833. return true;
  7834. });
  7835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7836. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7837. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7838. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7839. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7840. "7890123456789012345678901234567890",
  7841. body);
  7842. EXPECT_EQ(StatusCode::OK_200, res->status);
  7843. }
  7844. TEST_F(ServerTest, NoGzip) {
  7845. Headers headers;
  7846. headers.emplace("Accept-Encoding", "gzip, deflate");
  7847. auto res = cli_.Get("/nocompress", headers);
  7848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7849. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7850. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7851. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7852. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7853. "7890123456789012345678901234567890",
  7854. res->body);
  7855. EXPECT_EQ(StatusCode::OK_200, res->status);
  7856. }
  7857. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7858. Headers headers;
  7859. headers.emplace("Accept-Encoding", "gzip, deflate");
  7860. std::string body;
  7861. auto res = cli_.Get("/nocompress", headers,
  7862. [&](const char *data, uint64_t data_length) {
  7863. EXPECT_EQ(100U, data_length);
  7864. body.append(data, data_length);
  7865. return true;
  7866. });
  7867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7868. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7869. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7870. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7871. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7872. "7890123456789012345678901234567890",
  7873. body);
  7874. EXPECT_EQ(StatusCode::OK_200, res->status);
  7875. }
  7876. TEST_F(ServerTest, MultipartFormDataGzip) {
  7877. UploadFormDataItems items = {
  7878. {"key1", "test", "", ""},
  7879. {"key2", "--abcdefg123", "", ""},
  7880. };
  7881. cli_.set_compress(true);
  7882. auto res = cli_.Post("/compress-multipart", items);
  7883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7884. EXPECT_EQ(StatusCode::OK_200, res->status);
  7885. }
  7886. #endif
  7887. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7888. // Static file compression is opt-in, so these run their own server rather than
  7889. // flipping it on for the shared ServerTest fixture, which would silently
  7890. // rewrite what every other static file test is asserting.
  7891. class StaticFileCompressionTest : public ::testing::Test {
  7892. protected:
  7893. void TearDown() override {
  7894. if (t_.joinable()) {
  7895. svr_.stop();
  7896. t_.join();
  7897. }
  7898. }
  7899. int start(const std::function<void(Server &)> &configure = nullptr) {
  7900. // Serves the same tree as a directory of build-time compressed assets
  7901. // would be served: the mount point names the coding the files are already
  7902. // stored in. Registered before "/" so it is the one that matches.
  7903. svr_.set_mount_point("/pre-encoded", "./www",
  7904. {{"Content-Encoding", "gzip"}});
  7905. svr_.set_mount_point("/", "./www");
  7906. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7907. res.set_file_content("./www/dir/index.html", "text/html");
  7908. });
  7909. svr_.Get("/pre-encoded-file-content",
  7910. [](const Request & /*req*/, Response &res) {
  7911. res.set_header("Content-Encoding", "gzip");
  7912. res.set_file_content("./www/dir/index.html", "text/html");
  7913. });
  7914. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7915. res.set_content_provider(
  7916. 6, "text/plain",
  7917. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7918. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7919. return true;
  7920. });
  7921. });
  7922. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7923. res.set_content_provider(
  7924. 1000, "text/plain",
  7925. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7926. if (offset < 100) {
  7927. std::string data(100, 'A');
  7928. sink.write(data.data(), data.size());
  7929. return true;
  7930. }
  7931. std::this_thread::sleep_for(std::chrono::seconds(2));
  7932. std::string data(900, 'B');
  7933. sink.write(data.data(), data.size());
  7934. return true;
  7935. });
  7936. });
  7937. if (configure) { configure(svr_); }
  7938. auto port = svr_.bind_to_any_port(HOST);
  7939. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7940. svr_.wait_until_ready();
  7941. return port;
  7942. }
  7943. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7944. // Every file under ./www except 1MB.txt is smaller than the default
  7945. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7946. // it out of the way.
  7947. static void enable_without_floor(Server &svr) {
  7948. svr.set_static_file_compression(true);
  7949. svr.set_static_file_compression_min_length(0);
  7950. }
  7951. Server svr_;
  7952. std::thread t_;
  7953. };
  7954. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7955. auto port = start();
  7956. Client cli(HOST, port);
  7957. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7959. EXPECT_EQ(StatusCode::OK_200, res->status);
  7960. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7961. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7962. EXPECT_EQ(1048576U, res->body.size());
  7963. }
  7964. TEST_F(StaticFileCompressionTest, MountPoint) {
  7965. auto port = start(enable);
  7966. Client cli(HOST, port);
  7967. cli.set_decompress(false);
  7968. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7970. EXPECT_EQ(StatusCode::OK_200, res->status);
  7971. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7972. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7973. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7974. // The response stays self-delimiting: a length, not a chunked body.
  7975. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7976. EXPECT_EQ(std::to_string(res->body.size()),
  7977. res->get_header_value("Content-Length"));
  7978. EXPECT_LT(res->body.size(), 1048576U);
  7979. EXPECT_FALSE(res->body.empty());
  7980. }
  7981. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7982. auto port = start(enable);
  7983. Client cli(HOST, port);
  7984. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ(StatusCode::OK_200, res->status);
  7987. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7988. EXPECT_EQ(1048576U, res->body.size());
  7989. }
  7990. TEST_F(StaticFileCompressionTest, FileContent) {
  7991. auto port = start(enable_without_floor);
  7992. Client cli(HOST, port);
  7993. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7995. EXPECT_EQ(StatusCode::OK_200, res->status);
  7996. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7997. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7998. EXPECT_EQ(104U, res->body.size());
  7999. }
  8000. // A handler that serves an already-encoded file names the coding itself. The
  8001. // file-backed path decided its coding from Accept-Encoding and the content
  8002. // type alone, so it compressed the stored bytes a second time and appended a
  8003. // second Content-Encoding field line.
  8004. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8005. auto port = start(enable_without_floor);
  8006. Client cli(HOST, port);
  8007. cli.set_decompress(false);
  8008. auto res = cli.Get("/pre-encoded-file-content",
  8009. Headers{{"Accept-Encoding", "gzip"}});
  8010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8011. EXPECT_EQ(StatusCode::OK_200, res->status);
  8012. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8013. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8014. // Vary belongs to a coding the server chose, and it chose none here.
  8015. EXPECT_FALSE(res->has_header("Vary"));
  8016. // The file travels exactly as it is stored on disk.
  8017. EXPECT_EQ(104U, res->body.size());
  8018. }
  8019. // The 1MB file clears the default floor, so this one runs the configuration a
  8020. // deployment would actually have.
  8021. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8022. auto port = start(enable);
  8023. Client cli(HOST, port);
  8024. cli.set_decompress(false);
  8025. auto res =
  8026. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8028. EXPECT_EQ(StatusCode::OK_200, res->status);
  8029. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8030. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8031. EXPECT_FALSE(res->has_header("Vary"));
  8032. EXPECT_EQ(1048576U, res->body.size());
  8033. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8034. }
  8035. TEST_F(StaticFileCompressionTest, Head) {
  8036. auto port = start(enable);
  8037. Client cli(HOST, port);
  8038. cli.set_decompress(false);
  8039. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8040. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8041. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8043. EXPECT_EQ(StatusCode::OK_200, res->status);
  8044. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8045. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8046. // HEAD still reports the size a GET would return.
  8047. EXPECT_EQ(get->get_header_value("Content-Length"),
  8048. res->get_header_value("Content-Length"));
  8049. EXPECT_TRUE(res->body.empty());
  8050. }
  8051. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8052. auto port = start(enable);
  8053. Client cli(HOST, port);
  8054. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8055. {"Accept-Encoding", "gzip"}});
  8056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8057. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8058. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8059. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8060. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8061. EXPECT_EQ("cd", res->body);
  8062. }
  8063. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8064. auto port = start(enable);
  8065. Client cli(HOST, port);
  8066. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8068. EXPECT_EQ(StatusCode::OK_200, res->status);
  8069. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8070. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8071. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8072. }
  8073. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8074. auto port = start(enable);
  8075. Client cli(HOST, port);
  8076. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8078. EXPECT_EQ(StatusCode::OK_200, res->status);
  8079. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8080. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8081. EXPECT_TRUE(res->body.empty());
  8082. }
  8083. TEST_F(StaticFileCompressionTest, MinLength) {
  8084. auto port = start(enable);
  8085. Client cli(HOST, port);
  8086. // 104 bytes, well under the default floor. Compressing it would add the
  8087. // gzip header and trailer to a body that already fits in one packet.
  8088. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8090. EXPECT_EQ(StatusCode::OK_200, res->status);
  8091. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8092. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8093. }
  8094. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8095. auto port = start([](Server &svr) {
  8096. svr.set_static_file_compression(true);
  8097. svr.set_static_file_compression_min_length(1);
  8098. });
  8099. Client cli(HOST, port);
  8100. cli.set_decompress(false);
  8101. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8103. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8104. // A 9-byte file comes back larger than it went in, because gzip's header and
  8105. // trailer outweigh anything deflate can save. That is the end of the range
  8106. // the floor exists to keep out.
  8107. EXPECT_GT(res->body.size(), 9U);
  8108. }
  8109. TEST_F(StaticFileCompressionTest, MaxLength) {
  8110. auto port = start([](Server &svr) {
  8111. svr.set_static_file_compression(true);
  8112. svr.set_static_file_compression_min_length(0);
  8113. svr.set_static_file_compression_max_length(1024);
  8114. });
  8115. Client cli(HOST, port);
  8116. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8117. // defines `small` as a macro on Windows.
  8118. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8119. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8120. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8121. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8122. // Under it: compressed.
  8123. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8124. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8125. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8126. }
  8127. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8128. auto port = start(enable_without_floor);
  8129. Client cli(HOST, port);
  8130. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8131. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8132. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8133. auto identity_etag = identity->get_header_value("ETag");
  8134. ASSERT_FALSE(identity_etag.empty());
  8135. auto gzipped =
  8136. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8137. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8138. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8139. auto gzip_etag = gzipped->get_header_value("ETag");
  8140. ASSERT_FALSE(gzip_etag.empty());
  8141. // Two representations, two validators.
  8142. EXPECT_NE(identity_etag, gzip_etag);
  8143. // Each one revalidates against the request that would produce it...
  8144. auto fresh =
  8145. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8146. {"If-None-Match", gzip_etag}});
  8147. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8148. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8149. auto fresh_identity =
  8150. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8151. {"If-None-Match", identity_etag}});
  8152. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8153. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8154. // ...and not against the other representation.
  8155. auto crossed =
  8156. cli.Get("/dir/index.html",
  8157. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8158. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8159. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8160. }
  8161. // The opt-in covers responses the server reads off disk itself. A caller's own
  8162. // known-length provider keeps its Content-Length and, more importantly, keeps
  8163. // delivering incrementally: routing it through a compressor would hold every
  8164. // write back until zlib's window filled.
  8165. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8166. auto port = start(enable);
  8167. Client cli(HOST, port);
  8168. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8170. EXPECT_EQ(StatusCode::OK_200, res->status);
  8171. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8172. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8173. EXPECT_EQ("aaabbb", res->body);
  8174. }
  8175. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8176. auto port = start(enable);
  8177. Client cli(HOST, port);
  8178. cli.set_read_timeout(1, 0);
  8179. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8180. Headers{{"Accept-Encoding", "gzip"}});
  8181. ASSERT_TRUE(handle.is_valid());
  8182. // The provider writes 100 bytes and then stalls for longer than the read
  8183. // timeout. Those first bytes have to arrive anyway: run the response through
  8184. // a compressor and zlib holds them until its window fills, so the read would
  8185. // come back empty instead.
  8186. char buf[256];
  8187. auto n = handle.read(buf, sizeof(buf));
  8188. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8189. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8190. }
  8191. #endif
  8192. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8193. TEST_F(ServerTest, Brotli) {
  8194. Headers headers;
  8195. headers.emplace("Accept-Encoding", "br");
  8196. auto res = cli_.Get("/compress", headers);
  8197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8198. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8199. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8200. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8201. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8202. "7890123456789012345678901234567890",
  8203. res->body);
  8204. EXPECT_EQ(StatusCode::OK_200, res->status);
  8205. }
  8206. #endif
  8207. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8208. TEST_F(ServerTest, Zstd) {
  8209. Headers headers;
  8210. headers.emplace("Accept-Encoding", "zstd");
  8211. auto res = cli_.Get("/compress", headers);
  8212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8213. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8214. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8215. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8216. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8217. "7890123456789012345678901234567890",
  8218. res->body);
  8219. EXPECT_EQ(StatusCode::OK_200, res->status);
  8220. }
  8221. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8222. Headers headers;
  8223. headers.emplace("Accept-Encoding", "");
  8224. auto res = cli_.Get("/compress", headers);
  8225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8226. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8227. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8228. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8229. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8230. "7890123456789012345678901234567890",
  8231. res->body);
  8232. EXPECT_EQ(StatusCode::OK_200, res->status);
  8233. }
  8234. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8235. Headers headers;
  8236. headers.emplace("Accept-Encoding", "zstd");
  8237. std::string body;
  8238. auto res = cli_.Get("/compress", headers,
  8239. [&](const char *data, uint64_t data_length) {
  8240. EXPECT_EQ(100U, data_length);
  8241. body.append(data, data_length);
  8242. return true;
  8243. });
  8244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8245. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8246. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8247. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8248. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8249. "7890123456789012345678901234567890",
  8250. body);
  8251. EXPECT_EQ(StatusCode::OK_200, res->status);
  8252. }
  8253. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8254. Headers headers;
  8255. headers.emplace("Accept-Encoding", "zstd");
  8256. cli_.set_decompress(false);
  8257. auto res = cli_.Get("/compress", headers);
  8258. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8259. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8260. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8261. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8263. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8264. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8265. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8266. EXPECT_EQ(StatusCode::OK_200, res->status);
  8267. ASSERT_EQ(26U, res->body.size());
  8268. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8269. 0);
  8270. }
  8271. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8272. Headers headers;
  8273. headers.emplace("Accept-Encoding", "");
  8274. std::string body;
  8275. auto res = cli_.Get("/compress", headers,
  8276. [&](const char *data, uint64_t data_length) {
  8277. EXPECT_EQ(100U, data_length);
  8278. body.append(data, data_length);
  8279. return true;
  8280. });
  8281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8282. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8283. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8284. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8285. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8286. "7890123456789012345678901234567890",
  8287. body);
  8288. EXPECT_EQ(StatusCode::OK_200, res->status);
  8289. }
  8290. TEST_F(ServerTest, NoZstd) {
  8291. Headers headers;
  8292. headers.emplace("Accept-Encoding", "zstd");
  8293. auto res = cli_.Get("/nocompress", headers);
  8294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8295. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8296. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8297. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8298. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8299. "7890123456789012345678901234567890",
  8300. res->body);
  8301. EXPECT_EQ(StatusCode::OK_200, res->status);
  8302. }
  8303. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8304. Headers headers;
  8305. headers.emplace("Accept-Encoding", "zstd");
  8306. std::string body;
  8307. auto res = cli_.Get("/nocompress", headers,
  8308. [&](const char *data, uint64_t data_length) {
  8309. EXPECT_EQ(100U, data_length);
  8310. body.append(data, data_length);
  8311. return true;
  8312. });
  8313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8314. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8315. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8316. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8317. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8318. "7890123456789012345678901234567890",
  8319. body);
  8320. EXPECT_EQ(StatusCode::OK_200, res->status);
  8321. }
  8322. // TODO: How to enable zstd ??
  8323. TEST_F(ServerTest, MultipartFormDataZstd) {
  8324. UploadFormDataItems items = {
  8325. {"key1", "test", "", ""},
  8326. {"key2", "--abcdefg123", "", ""},
  8327. };
  8328. Headers headers;
  8329. headers.emplace("Accept-Encoding", "zstd");
  8330. cli_.set_compress(true);
  8331. auto res = cli_.Post("/compress-multipart", headers, items);
  8332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8333. EXPECT_EQ(StatusCode::OK_200, res->status);
  8334. }
  8335. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8336. Headers headers;
  8337. headers.emplace("Accept-Encoding", "zstd");
  8338. cli_.set_compress(true);
  8339. auto res = cli_.Put(
  8340. "/put", headers, 3,
  8341. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8342. sink.os << "PUT";
  8343. return true;
  8344. },
  8345. "text/plain");
  8346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8347. EXPECT_EQ(StatusCode::OK_200, res->status);
  8348. EXPECT_EQ("PUT", res->body);
  8349. }
  8350. // Pre-compression logging tests
  8351. TEST_F(ServerTest, PreCompressionLogging) {
  8352. // Test data for compression (matches the actual /compress endpoint content)
  8353. const std::string test_content =
  8354. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8355. "3456789012345678901234567890";
  8356. // Variables to capture logging data
  8357. std::string pre_compression_body;
  8358. std::string pre_compression_content_type;
  8359. std::string pre_compression_content_encoding;
  8360. std::string post_compression_body;
  8361. std::string post_compression_content_type;
  8362. std::string post_compression_content_encoding;
  8363. // Set up pre-compression logger
  8364. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8365. const Response &res) {
  8366. pre_compression_body = res.body;
  8367. pre_compression_content_type = res.get_header_value("Content-Type");
  8368. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8369. });
  8370. // Set up post-compression logger
  8371. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8372. post_compression_body = res.body;
  8373. post_compression_content_type = res.get_header_value("Content-Type");
  8374. post_compression_content_encoding =
  8375. res.get_header_value("Content-Encoding");
  8376. });
  8377. // Test with gzip compression
  8378. Headers headers;
  8379. headers.emplace("Accept-Encoding", "gzip");
  8380. auto res = cli_.Get("/compress", headers);
  8381. // Verify response was compressed
  8382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8383. EXPECT_EQ(StatusCode::OK_200, res->status);
  8384. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8385. // Verify pre-compression logger captured uncompressed content
  8386. EXPECT_EQ(test_content, pre_compression_body);
  8387. EXPECT_EQ("text/plain", pre_compression_content_type);
  8388. EXPECT_TRUE(pre_compression_content_encoding
  8389. .empty()); // No encoding header before compression
  8390. // Verify post-compression logger captured compressed content
  8391. EXPECT_NE(test_content,
  8392. post_compression_body); // Should be different after compression
  8393. EXPECT_EQ("text/plain", post_compression_content_type);
  8394. EXPECT_EQ("gzip", post_compression_content_encoding);
  8395. // Verify compressed content is smaller
  8396. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8397. }
  8398. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8399. const std::string test_content =
  8400. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8401. "3456789012345678901234567890";
  8402. std::string pre_compression_body;
  8403. std::string post_compression_body;
  8404. svr_.set_pre_compression_logger(
  8405. [&](const Request & /*req*/, const Response &res) {
  8406. pre_compression_body = res.body;
  8407. });
  8408. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8409. post_compression_body = res.body;
  8410. });
  8411. Headers headers;
  8412. headers.emplace("Accept-Encoding", "br");
  8413. auto res = cli_.Get("/compress", headers);
  8414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8415. EXPECT_EQ(StatusCode::OK_200, res->status);
  8416. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8417. // Verify pre-compression content is uncompressed
  8418. EXPECT_EQ(test_content, pre_compression_body);
  8419. // Verify post-compression content is compressed
  8420. EXPECT_NE(test_content, post_compression_body);
  8421. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8422. }
  8423. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8424. const std::string test_content =
  8425. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8426. "3456789012345678901234567890";
  8427. std::string pre_compression_body;
  8428. std::string post_compression_body;
  8429. svr_.set_pre_compression_logger(
  8430. [&](const Request & /*req*/, const Response &res) {
  8431. pre_compression_body = res.body;
  8432. });
  8433. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8434. post_compression_body = res.body;
  8435. });
  8436. // Request without compression (use /nocompress endpoint)
  8437. Headers headers;
  8438. auto res = cli_.Get("/nocompress", headers);
  8439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8440. EXPECT_EQ(StatusCode::OK_200, res->status);
  8441. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8442. // Pre-compression logger should not be called when no compression is applied
  8443. EXPECT_TRUE(
  8444. pre_compression_body.empty()); // Pre-compression logger not called
  8445. EXPECT_EQ(
  8446. test_content,
  8447. post_compression_body); // Post-compression logger captures final content
  8448. }
  8449. TEST_F(ServerTest, LoggerSeesContentLength) {
  8450. size_t logged_content_length = 0;
  8451. std::string logged_content_length_header;
  8452. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8453. logged_content_length = res.content_length_;
  8454. logged_content_length_header = res.get_header_value("Content-Length");
  8455. });
  8456. auto res = cli_.Get("/nocompress");
  8457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8458. EXPECT_EQ(StatusCode::OK_200, res->status);
  8459. EXPECT_EQ(res->body.size(), logged_content_length);
  8460. EXPECT_EQ(std::to_string(logged_content_length),
  8461. logged_content_length_header);
  8462. }
  8463. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8464. const std::string test_content =
  8465. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8466. "3456789012345678901234567890";
  8467. std::string pre_compression_body;
  8468. bool pre_logger_called = false;
  8469. // Set only pre-compression logger
  8470. svr_.set_pre_compression_logger(
  8471. [&](const Request & /*req*/, const Response &res) {
  8472. pre_compression_body = res.body;
  8473. pre_logger_called = true;
  8474. });
  8475. Headers headers;
  8476. headers.emplace("Accept-Encoding", "gzip");
  8477. auto res = cli_.Get("/compress", headers);
  8478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8479. EXPECT_EQ(StatusCode::OK_200, res->status);
  8480. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8481. // Verify pre-compression logger was called
  8482. EXPECT_TRUE(pre_logger_called);
  8483. EXPECT_EQ(test_content, pre_compression_body);
  8484. }
  8485. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8486. {
  8487. // Test with Expect: 100-continue header - success case
  8488. // Server returns 100 Continue, client sends body, server returns 200 OK
  8489. Request req;
  8490. req.method = "POST";
  8491. req.path = "/post-large";
  8492. req.set_header("Expect", "100-continue");
  8493. req.body = LARGE_DATA;
  8494. Response res;
  8495. auto error = Error::Success;
  8496. cli_.set_keep_alive(true);
  8497. auto ret = cli_.send(req, res, error);
  8498. EXPECT_TRUE(ret);
  8499. EXPECT_EQ(StatusCode::OK_200, res.status);
  8500. EXPECT_EQ(LARGE_DATA, res.body);
  8501. }
  8502. {
  8503. // Test with Expect: 100-continue header - error case
  8504. // Client should not send the body when server returns an error
  8505. Request req;
  8506. req.method = "POST";
  8507. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8508. req.set_header("Expect", "100-continue");
  8509. req.body = LARGE_DATA;
  8510. Response res;
  8511. auto error = Error::Success;
  8512. auto start = std::chrono::high_resolution_clock::now();
  8513. cli_.set_keep_alive(true);
  8514. auto ret = cli_.send(req, res, error);
  8515. auto end = std::chrono::high_resolution_clock::now();
  8516. auto elapsed =
  8517. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8518. .count();
  8519. // With Expect: 100-continue, request completes successfully but with error
  8520. EXPECT_TRUE(ret);
  8521. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8522. EXPECT_EQ("close", res.get_header_value("Connection"));
  8523. EXPECT_FALSE(cli_.is_socket_open());
  8524. EXPECT_LE(elapsed, 2000);
  8525. }
  8526. {
  8527. // Send an extra GET request to ensure error recovery without hanging
  8528. Request req;
  8529. req.method = "GET";
  8530. req.path = "/hi";
  8531. auto start = std::chrono::high_resolution_clock::now();
  8532. auto res = cli_.send(req);
  8533. auto end = std::chrono::high_resolution_clock::now();
  8534. auto elapsed =
  8535. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8536. .count();
  8537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8538. EXPECT_EQ(StatusCode::OK_200, res->status);
  8539. EXPECT_EQ("Hello World!", res->body);
  8540. EXPECT_LE(elapsed, 500);
  8541. }
  8542. }
  8543. TEST(ZstdDecompressor, ChunkedDecompression) {
  8544. std::string data;
  8545. for (size_t i = 0; i < 32 * 1024; ++i) {
  8546. data.push_back(static_cast<char>('a' + i % 26));
  8547. }
  8548. std::string compressed_data;
  8549. {
  8550. httplib::detail::zstd_compressor compressor;
  8551. bool result = compressor.compress(
  8552. data.data(), data.size(),
  8553. /*last=*/true,
  8554. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8555. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8556. compressed_data_size);
  8557. return true;
  8558. });
  8559. ASSERT_TRUE(result);
  8560. }
  8561. std::string decompressed_data;
  8562. {
  8563. httplib::detail::zstd_decompressor decompressor;
  8564. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8565. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8566. size_t chunk_size = 130;
  8567. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8568. chunk_begin += chunk_size) {
  8569. size_t current_chunk_size =
  8570. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8571. bool result = decompressor.decompress(
  8572. compressed_data.data() + chunk_begin, current_chunk_size,
  8573. [&](const char *decompressed_data_chunk,
  8574. size_t decompressed_data_chunk_size) {
  8575. decompressed_data.insert(decompressed_data.size(),
  8576. decompressed_data_chunk,
  8577. decompressed_data_chunk_size);
  8578. return true;
  8579. });
  8580. ASSERT_TRUE(result);
  8581. }
  8582. }
  8583. ASSERT_EQ(data, decompressed_data);
  8584. }
  8585. TEST(ZstdDecompressor, Decompress) {
  8586. std::string original_text = "Compressed with ZSTD";
  8587. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8588. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8589. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8590. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8591. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8592. std::string decompressed_data;
  8593. {
  8594. httplib::detail::zstd_decompressor decompressor;
  8595. bool result = decompressor.decompress(
  8596. compressed_data.data(), compressed_data.size(),
  8597. [&](const char *decompressed_data_chunk,
  8598. size_t decompressed_data_chunk_size) {
  8599. decompressed_data.insert(decompressed_data.size(),
  8600. decompressed_data_chunk,
  8601. decompressed_data_chunk_size);
  8602. return true;
  8603. });
  8604. ASSERT_TRUE(result);
  8605. }
  8606. ASSERT_EQ(original_text, decompressed_data);
  8607. }
  8608. #endif
  8609. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8610. // separate chunks so that the server sees each part in its own read(). Used to
  8611. // place a read boundary at a specific offset of a request body.
  8612. static bool send_request_in_parts(time_t read_timeout_sec,
  8613. const std::vector<std::string> &parts,
  8614. std::string *resp = nullptr,
  8615. int port = PORT) {
  8616. auto error = Error::Success;
  8617. auto client_sock = detail::create_client_socket(
  8618. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8619. /*connection_timeout_sec=*/5, 0,
  8620. /*read_timeout_sec=*/5, 0,
  8621. /*write_timeout_sec=*/5, 0, std::string(), error);
  8622. if (client_sock == INVALID_SOCKET) { return false; }
  8623. auto ret = detail::process_client_socket(
  8624. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8625. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8626. for (size_t i = 0; i < parts.size(); i++) {
  8627. const auto &part = parts[i];
  8628. if (part.size() !=
  8629. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8630. return false;
  8631. }
  8632. if (i + 1 < parts.size()) {
  8633. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8634. }
  8635. }
  8636. char buf[512];
  8637. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8638. while (line_reader.getline()) {
  8639. if (resp) { *resp += line_reader.ptr(); }
  8640. }
  8641. return true;
  8642. });
  8643. detail::close_socket(client_sock);
  8644. return ret;
  8645. }
  8646. // Sends a raw request to a server listening at HOST:PORT.
  8647. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8648. std::string *resp = nullptr, int port = PORT) {
  8649. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8650. }
  8651. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8652. Server svr;
  8653. std::string header_value;
  8654. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8655. header_value = req.get_header_value("foo");
  8656. res.set_content("ok", "text/plain");
  8657. });
  8658. thread t = thread([&] { svr.listen(HOST, PORT); });
  8659. auto se = detail::scope_exit([&] {
  8660. svr.stop();
  8661. t.join();
  8662. ASSERT_FALSE(svr.is_running());
  8663. });
  8664. svr.wait_until_ready();
  8665. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8666. // like characters are not treated the same - use vertical tab and escape.
  8667. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8668. "foo: \t \v bar \x1B\t \r\n"
  8669. "Connection: close\r\n"
  8670. "\r\n";
  8671. std::string res;
  8672. ASSERT_TRUE(send_request(5, req, &res));
  8673. EXPECT_EQ(header_value, "");
  8674. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8675. }
  8676. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8677. Server svr;
  8678. std::string received;
  8679. svr.Get("/order", [&](const Request &req, Response &res) {
  8680. received = entries_to_string(req.headers);
  8681. res.set_content("ok", "text/plain");
  8682. });
  8683. auto port = svr.bind_to_any_port(HOST);
  8684. thread t = thread([&] { svr.listen_after_bind(); });
  8685. auto se = detail::scope_exit([&] {
  8686. svr.stop();
  8687. t.join();
  8688. ASSERT_FALSE(svr.is_running());
  8689. });
  8690. svr.wait_until_ready();
  8691. const std::string req = "GET /order HTTP/1.1\r\n"
  8692. "X-First: 1\r\n"
  8693. "X-Dup: a\r\n"
  8694. "X-Second: 2\r\n"
  8695. "X-Dup: b\r\n"
  8696. "Connection: close\r\n"
  8697. "\r\n";
  8698. std::string res;
  8699. ASSERT_TRUE(send_request(5, req, &res, port));
  8700. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8701. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8702. }
  8703. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8704. Server svr;
  8705. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8706. res.set_header("Set-Cookie", "first=1");
  8707. res.set_header("X-Between", "y");
  8708. res.set_header("Set-Cookie", "second=2");
  8709. res.set_content("ok", "text/plain");
  8710. });
  8711. auto port = svr.bind_to_any_port(HOST);
  8712. thread t = thread([&] { svr.listen_after_bind(); });
  8713. auto se = detail::scope_exit([&] {
  8714. svr.stop();
  8715. t.join();
  8716. ASSERT_FALSE(svr.is_running());
  8717. });
  8718. svr.wait_until_ready();
  8719. Client cli(HOST, port);
  8720. auto res = cli.Get("/cookies");
  8721. ASSERT_TRUE(res);
  8722. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8723. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8724. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8725. }
  8726. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8727. Server svr;
  8728. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8729. auto i = new int(0);
  8730. res.set_header("Trailer", "X-Safe, X-Reflected");
  8731. res.set_chunked_content_provider(
  8732. "text/plain",
  8733. [i](size_t /*offset*/, DataSink &sink) {
  8734. if (*i == 0) {
  8735. sink.os << "body";
  8736. } else {
  8737. Headers trailer;
  8738. // A valid trailer that must survive.
  8739. trailer.emplace("X-Safe", "safe");
  8740. // Attacker-controlled value carrying CR/LF (response splitting).
  8741. trailer.emplace("X-Reflected",
  8742. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8743. // Attacker-controlled name carrying CR/LF.
  8744. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8745. sink.done_with_trailer(trailer);
  8746. }
  8747. (*i)++;
  8748. return true;
  8749. },
  8750. [i](bool /*success*/) { delete i; });
  8751. });
  8752. thread t = thread([&] { svr.listen(HOST, PORT); });
  8753. auto se = detail::scope_exit([&] {
  8754. svr.stop();
  8755. t.join();
  8756. ASSERT_FALSE(svr.is_running());
  8757. });
  8758. svr.wait_until_ready();
  8759. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8760. "Host: " + HOST +
  8761. "\r\n"
  8762. "Connection: close\r\n"
  8763. "\r\n";
  8764. std::string res;
  8765. ASSERT_TRUE(send_request(5, req, &res));
  8766. // The injected fields must not appear anywhere in the raw response.
  8767. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8768. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8769. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8770. // Invalid trailers are dropped entirely, matching set_header().
  8771. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8772. // The valid trailer still passes through.
  8773. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8774. }
  8775. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8776. Server svr;
  8777. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8778. // res.headers is a public field an application can populate directly,
  8779. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8780. // A valid header that must survive.
  8781. res.headers.emplace("X-Safe", "safe");
  8782. // Attacker-controlled value carrying CR/LF (response splitting).
  8783. res.headers.emplace("X-Reflected",
  8784. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8785. // Attacker-controlled name carrying CR/LF.
  8786. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8787. res.set_content("body", "text/plain");
  8788. });
  8789. thread t = thread([&] { svr.listen(HOST, PORT); });
  8790. auto se = detail::scope_exit([&] {
  8791. svr.stop();
  8792. t.join();
  8793. ASSERT_FALSE(svr.is_running());
  8794. });
  8795. svr.wait_until_ready();
  8796. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8797. "Host: " + HOST +
  8798. "\r\n"
  8799. "Connection: close\r\n"
  8800. "\r\n";
  8801. std::string res;
  8802. ASSERT_TRUE(send_request(5, req, &res));
  8803. // The injected fields must not appear anywhere in the raw response.
  8804. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8805. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8806. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8807. // Invalid headers are dropped entirely, matching set_header().
  8808. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8809. // The valid header still passes through.
  8810. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8811. }
  8812. // Forward declaration: in split builds split.py strips `inline` and moves the
  8813. // definition into httplib.cc, so detail::write_request_line is not visible from
  8814. // the public httplib.h. Re-declaring it here lets the tests link against the
  8815. // symbol in both header-only and split builds.
  8816. namespace httplib {
  8817. namespace detail {
  8818. ssize_t write_request_line(Stream &strm, const std::string &method,
  8819. const std::string &path);
  8820. } // namespace detail
  8821. } // namespace httplib
  8822. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8823. // A well-formed target is written verbatim.
  8824. {
  8825. detail::BufferStream strm;
  8826. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8827. EXPECT_GT(n, 0);
  8828. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8829. }
  8830. // A target carrying CR/LF, SP or other control octets must be rejected
  8831. // before anything reaches the wire, otherwise it splits the request line and
  8832. // injects a header or a whole request.
  8833. const std::string evil_targets[] = {
  8834. "/a\r\nInjected: pwned",
  8835. "/a\rInjected",
  8836. "/a\nInjected",
  8837. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8838. "/a b",
  8839. "/a\tb",
  8840. "/a\x7f",
  8841. };
  8842. for (const auto &evil : evil_targets) {
  8843. detail::BufferStream strm;
  8844. auto n = detail::write_request_line(strm, "GET", evil);
  8845. EXPECT_LT(n, 0);
  8846. EXPECT_TRUE(strm.get_buffer().empty());
  8847. }
  8848. }
  8849. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8850. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8851. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8852. // target reaches write_request. The client must fail cleanly with
  8853. // Error::Write instead of putting a request-line-less, header-injecting
  8854. // request on the wire.
  8855. Server svr;
  8856. svr.Get("/a", [](const Request &, Response &res) {
  8857. res.set_content("ok", "text/plain");
  8858. });
  8859. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8860. auto se = detail::scope_exit([&] {
  8861. svr.stop();
  8862. thread.join();
  8863. ASSERT_FALSE(svr.is_running());
  8864. });
  8865. svr.wait_until_ready();
  8866. {
  8867. Client cli(HOST, PORT);
  8868. cli.set_path_encode(false);
  8869. // The request is rejected before anything is written, so the connection
  8870. // stays silent and the subsequent response read would otherwise block for
  8871. // the full default read timeout. Shorten it -- the assertion is on the
  8872. // error, not the timeout.
  8873. cli.set_read_timeout(1, 0);
  8874. auto res = cli.Get("/a\r\nInjected: pwned");
  8875. EXPECT_FALSE(res);
  8876. EXPECT_EQ(Error::Write, res.error());
  8877. }
  8878. }
  8879. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8880. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8881. // including extension methods.
  8882. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8883. for (const auto &method : good_methods) {
  8884. detail::BufferStream strm;
  8885. auto n = detail::write_request_line(strm, method, "/");
  8886. EXPECT_GT(n, 0);
  8887. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8888. }
  8889. // A method carrying CR/LF would split the request line and smuggle a whole
  8890. // request ahead of the real one. A space or an empty method corrupts the
  8891. // request line. All must be rejected before anything reaches the wire.
  8892. const std::string evil_methods[] = {
  8893. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8894. "GET\r\nInjected: pwned",
  8895. "GET\r",
  8896. "GET\n",
  8897. "GE T",
  8898. "",
  8899. };
  8900. for (const auto &evil : evil_methods) {
  8901. detail::BufferStream strm;
  8902. auto n = detail::write_request_line(strm, evil, "/");
  8903. EXPECT_LT(n, 0);
  8904. EXPECT_TRUE(strm.get_buffer().empty());
  8905. }
  8906. }
  8907. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8908. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8909. // through Client::send must fail with Error::Write and no request, neither
  8910. // the smuggled one nor the real one, may reach the server.
  8911. Server svr;
  8912. std::atomic<int> request_count(0);
  8913. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8914. request_count++;
  8915. res.status = StatusCode::OK_200;
  8916. return Server::HandlerResponse::Handled;
  8917. });
  8918. auto port = svr.bind_to_any_port(HOST);
  8919. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8920. auto se = detail::scope_exit([&] {
  8921. svr.stop();
  8922. thread.join();
  8923. ASSERT_FALSE(svr.is_running());
  8924. });
  8925. svr.wait_until_ready();
  8926. {
  8927. Client cli(HOST, port);
  8928. const std::string evil_methods[] = {
  8929. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8930. "GE T",
  8931. "",
  8932. };
  8933. for (const auto &evil : evil_methods) {
  8934. Request req;
  8935. req.method = evil;
  8936. req.path = "/";
  8937. auto res = cli.send(req);
  8938. EXPECT_FALSE(res);
  8939. EXPECT_EQ(Error::Write, res.error());
  8940. }
  8941. auto handle =
  8942. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8943. EXPECT_FALSE(handle.is_valid());
  8944. EXPECT_EQ(Error::Write, handle.error);
  8945. // A valid request on the same client still goes through.
  8946. auto res = cli.Get("/");
  8947. ASSERT_TRUE(res);
  8948. EXPECT_EQ(StatusCode::OK_200, res->status);
  8949. }
  8950. EXPECT_EQ(1, request_count.load());
  8951. }
  8952. // Sends a raw request and verifies that there isn't a crash or exception.
  8953. static void test_raw_request(const std::string &req,
  8954. std::string *out = nullptr) {
  8955. Server svr;
  8956. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8957. res.set_content("ok", "text/plain");
  8958. });
  8959. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8960. res.set_content("ok", "text/plain");
  8961. });
  8962. svr.Get("/header_field_value_check",
  8963. [&](const Request & /*req*/, Response &res) {
  8964. res.set_content("ok", "text/plain");
  8965. });
  8966. svr.CustomRoute("PROPFIND", "/dav",
  8967. [&](const Request & /*req*/, Response &res) {
  8968. res.status = StatusCode::MultiStatus_207;
  8969. });
  8970. // Server read timeout must be longer than the client read timeout for the
  8971. // bug to reproduce, probably to force the server to process a request
  8972. // without a trailing blank line.
  8973. const time_t client_read_timeout_sec = 1;
  8974. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8975. bool listen_thread_ok = false;
  8976. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8977. auto se = detail::scope_exit([&] {
  8978. svr.stop();
  8979. t.join();
  8980. ASSERT_FALSE(svr.is_running());
  8981. EXPECT_TRUE(listen_thread_ok);
  8982. });
  8983. svr.wait_until_ready();
  8984. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8985. }
  8986. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8987. // A certain header line causes an exception if the header property is parsed
  8988. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8989. test_raw_request(
  8990. "GET /hi HTTP/1.1\r\n"
  8991. " : "
  8992. " "
  8993. " ");
  8994. }
  8995. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8996. // A certain header line causes an exception if the header property *name* is
  8997. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8998. // greedy matcher and requires backtracking when there are a lot of ":"
  8999. // characters.
  9000. // This occurs with libc++ but not libstdc++.
  9001. test_raw_request(
  9002. "GET /hi HTTP/1.1\r\n"
  9003. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9004. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9005. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9006. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9007. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9008. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9009. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9010. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9011. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9012. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9013. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9014. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9015. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9016. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9017. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9018. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9019. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9020. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9021. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9022. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9023. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9024. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9025. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9026. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9027. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9028. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9029. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9030. "&&&%%%");
  9031. }
  9032. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9033. // Make sure this doesn't crash the server.
  9034. // In a previous version of the header line regex, the "\r" rendered the line
  9035. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9036. // a new position where the leading white space ended and the field value
  9037. // began.
  9038. // The crash occurs with libc++ but not libstdc++.
  9039. test_raw_request("GET /hi HTTP/1.1\r\n"
  9040. "a:" +
  9041. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9042. "\r\n"
  9043. "\r\n");
  9044. }
  9045. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9046. std::string out;
  9047. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9048. "Content-Type: text/plain\r\n"
  9049. "Transfer-Encoding: chunked\r\n"
  9050. "\r\n"
  9051. "nothex\r\n",
  9052. &out);
  9053. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9054. }
  9055. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9056. std::string out;
  9057. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9058. "Content-Type: text/plain\r\n"
  9059. "Transfer-Encoding: chunked\r\n"
  9060. "\r\n"
  9061. "3\r\n"
  9062. "xyz\r\n"
  9063. "NaN\r\n",
  9064. &out);
  9065. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9066. }
  9067. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9068. std::string out;
  9069. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9070. "Content-Type: text/plain\r\n"
  9071. "Transfer-Encoding: chunked\r\n"
  9072. "\r\n"
  9073. // Length is too large for 64 bits.
  9074. "1ffffffffffffffff\r\n"
  9075. "xyz\r\n",
  9076. &out);
  9077. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9078. }
  9079. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9080. test_raw_request("GET /hi HTTP/1.1\r\n"
  9081. "Content-Type: text/plain\r\n\r");
  9082. }
  9083. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9084. std::string out;
  9085. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9086. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9087. }
  9088. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9089. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9090. std::string out;
  9091. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9092. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9093. }
  9094. }
  9095. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9096. std::string out;
  9097. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9098. "Connection: close\r\n\r\n",
  9099. &out);
  9100. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9101. }
  9102. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9103. Server svr;
  9104. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9105. EXPECT_TRUE(!req.remote_addr.empty());
  9106. });
  9107. thread t = thread([&] { svr.listen(HOST, PORT); });
  9108. auto se = detail::scope_exit([&] {
  9109. svr.stop();
  9110. t.join();
  9111. ASSERT_FALSE(svr.is_running());
  9112. });
  9113. svr.wait_until_ready();
  9114. // Send an invalid request line to trigger Bad Request
  9115. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9116. std::string out;
  9117. ASSERT_TRUE(send_request(5, bad_req, &out));
  9118. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9119. }
  9120. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9121. // answered right away rather than blocking on a read that waits for EOF.
  9122. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9123. std::string out;
  9124. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9125. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9126. }
  9127. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9128. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9129. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9130. for (const auto *method : methods) {
  9131. Server svr;
  9132. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9133. EXPECT_FALSE(svr.is_valid()) << method;
  9134. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9135. }
  9136. }
  9137. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9138. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9139. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9140. for (const auto *method : methods) {
  9141. Server svr;
  9142. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9143. EXPECT_FALSE(svr.is_valid()) << method;
  9144. }
  9145. }
  9146. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9147. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9148. "COPY", "MOVE", "LOCK",
  9149. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9150. Server svr;
  9151. for (const auto *method : methods) {
  9152. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9153. }
  9154. EXPECT_TRUE(svr.is_valid());
  9155. }
  9156. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9157. Server svr;
  9158. svr.CustomRoute("POST", "/x",
  9159. [](const Request &, Response &, const ContentReader &) {});
  9160. EXPECT_FALSE(svr.is_valid());
  9161. }
  9162. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9163. Server svr;
  9164. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9165. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9166. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9167. EXPECT_FALSE(svr.is_valid());
  9168. }
  9169. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9170. Server svr;
  9171. auto captured = Error::Success;
  9172. svr.set_error_logger(
  9173. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9174. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9175. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9176. }
  9177. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9178. std::string out;
  9179. std::string request(
  9180. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9181. test_raw_request(request, &out);
  9182. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9183. }
  9184. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9185. std::string out;
  9186. std::string request(
  9187. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9188. test_raw_request(request, &out);
  9189. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9190. }
  9191. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9192. std::string out;
  9193. std::string request(
  9194. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9195. test_raw_request(request, &out);
  9196. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9197. }
  9198. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9199. std::string out;
  9200. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9201. "Test: \r\n\r\n",
  9202. &out);
  9203. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9204. }
  9205. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9206. Server svr;
  9207. std::string x_custom;
  9208. std::string cookie;
  9209. std::string xff;
  9210. std::string x_unicode;
  9211. std::string x_iis;
  9212. svr.Get("/check", [&](const Request &req, Response &res) {
  9213. x_custom = req.get_header_value("X-Custom");
  9214. cookie = req.get_header_value("Cookie");
  9215. xff = req.get_header_value("X-Forwarded-For");
  9216. x_unicode = req.get_header_value("X-Unicode");
  9217. x_iis = req.get_header_value("X-IIS");
  9218. res.set_content("ok", "text/plain");
  9219. });
  9220. thread t = thread([&] { svr.listen(HOST, PORT); });
  9221. auto se = detail::scope_exit([&] {
  9222. svr.stop();
  9223. t.join();
  9224. ASSERT_FALSE(svr.is_running());
  9225. });
  9226. svr.wait_until_ready();
  9227. const std::string req = "GET /check HTTP/1.1\r\n"
  9228. "Host: localhost\r\n"
  9229. "X-Custom: a%0D%0AInjected: b\r\n"
  9230. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9231. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9232. "X-Unicode: %E3%81%82\r\n"
  9233. "X-IIS: %u00E9\r\n"
  9234. "Connection: close\r\n"
  9235. "\r\n";
  9236. std::string res;
  9237. ASSERT_TRUE(send_request(5, req, &res));
  9238. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9239. // Every value must be returned verbatim (wire form), with no decoding.
  9240. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9241. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9242. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9243. EXPECT_EQ("%E3%81%82", x_unicode);
  9244. EXPECT_EQ("%u00E9", x_iis);
  9245. }
  9246. // Applications that previously relied on automatic percent-decoding can
  9247. // reproduce the old behavior by explicitly calling decode_path_component()
  9248. // or, for RFC 3986 conformance, decode_uri_component().
  9249. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9250. Server svr;
  9251. std::string decoded;
  9252. svr.Get("/check", [&](const Request &req, Response &res) {
  9253. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9254. res.set_content("ok", "text/plain");
  9255. });
  9256. thread t = thread([&] { svr.listen(HOST, PORT); });
  9257. auto se = detail::scope_exit([&] {
  9258. svr.stop();
  9259. t.join();
  9260. ASSERT_FALSE(svr.is_running());
  9261. });
  9262. svr.wait_until_ready();
  9263. const std::string req = "GET /check HTTP/1.1\r\n"
  9264. "Host: localhost\r\n"
  9265. "X-Custom: hello%20world\r\n"
  9266. "Connection: close\r\n"
  9267. "\r\n";
  9268. std::string res;
  9269. ASSERT_TRUE(send_request(5, req, &res));
  9270. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9271. EXPECT_EQ("hello world", decoded);
  9272. }
  9273. // Regression test for #2033. Browsers send Referer values that include
  9274. // percent-encoded characters such as %0A inside the URL. Decoding the
  9275. // header value would either trip the post-decode CR/LF/NUL guard (the
  9276. // original bug, returning 400) or, after that guard was relaxed, silently
  9277. // store a literal LF — both unacceptable. The wire form must round-trip.
  9278. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9279. Server svr;
  9280. std::string referer;
  9281. svr.Get("/check", [&](const Request &req, Response &res) {
  9282. referer = req.get_header_value("Referer");
  9283. res.set_content("ok", "text/plain");
  9284. });
  9285. thread t = thread([&] { svr.listen(HOST, PORT); });
  9286. auto se = detail::scope_exit([&] {
  9287. svr.stop();
  9288. t.join();
  9289. ASSERT_FALSE(svr.is_running());
  9290. });
  9291. svr.wait_until_ready();
  9292. const std::string req = "GET /check HTTP/1.1\r\n"
  9293. "Host: localhost\r\n"
  9294. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9295. "Connection: close\r\n"
  9296. "\r\n";
  9297. std::string res;
  9298. ASSERT_TRUE(send_request(5, req, &res));
  9299. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9300. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9301. }
  9302. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9303. Server svr;
  9304. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9305. res.set_header("Cache-Control", "no-cache");
  9306. res.set_chunked_content_provider(
  9307. "text/event-stream", [](size_t offset, DataSink &sink) {
  9308. std::string s = "data:";
  9309. s += std::to_string(offset);
  9310. s += "\n\n";
  9311. auto ret = sink.write(s.data(), s.size());
  9312. EXPECT_TRUE(ret);
  9313. std::this_thread::sleep_for(std::chrono::seconds(1));
  9314. return true;
  9315. });
  9316. });
  9317. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9318. svr.wait_until_ready();
  9319. Client client(HOST, PORT);
  9320. const Headers headers = {{"Accept", "text/event-stream"}};
  9321. auto get_thread = std::thread([&client, &headers]() {
  9322. auto res = client.Get(
  9323. "/events", headers,
  9324. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9325. });
  9326. auto se = detail::scope_exit([&] {
  9327. svr.stop();
  9328. get_thread.join();
  9329. listen_thread.join();
  9330. ASSERT_FALSE(svr.is_running());
  9331. });
  9332. // Give GET time to get a few messages.
  9333. std::this_thread::sleep_for(std::chrono::seconds(2));
  9334. }
  9335. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9336. httplib::Server svr;
  9337. svr.Post("/hi",
  9338. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9339. res.status = StatusCode::OK_200;
  9340. });
  9341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9342. svr.wait_until_ready();
  9343. Client cli(HOST, PORT);
  9344. auto res = cli.Post("/hi", "data", "text/plain");
  9345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9346. EXPECT_EQ(StatusCode::OK_200, res->status);
  9347. svr.stop();
  9348. thread.join();
  9349. ASSERT_FALSE(svr.is_running());
  9350. res = cli.Post("/hi", "data", "text/plain");
  9351. ASSERT_FALSE(res);
  9352. }
  9353. TEST(ServerStopTest, ListenFailure) {
  9354. Server svr;
  9355. auto t = thread([&]() {
  9356. auto ret = svr.listen("????", PORT);
  9357. EXPECT_FALSE(ret);
  9358. });
  9359. svr.wait_until_ready();
  9360. svr.stop();
  9361. t.join();
  9362. }
  9363. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9364. TEST(ServerStopTest, Decommision) {
  9365. Server svr;
  9366. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9367. for (int i = 0; i < 4; i++) {
  9368. auto is_even = !(i % 2);
  9369. std::thread t{[&] {
  9370. try {
  9371. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9372. if (is_even) {
  9373. throw std::runtime_error("Some thing that happens to go wrong.");
  9374. }
  9375. svr.listen(HOST, PORT);
  9376. } catch (...) { svr.decommission(); }
  9377. }};
  9378. svr.wait_until_ready();
  9379. // Server is up
  9380. {
  9381. Client cli(HOST, PORT);
  9382. auto res = cli.Get("/hi");
  9383. if (is_even) {
  9384. EXPECT_FALSE(res);
  9385. } else {
  9386. EXPECT_TRUE(res);
  9387. EXPECT_EQ("hi...", res->body);
  9388. }
  9389. }
  9390. svr.stop();
  9391. t.join();
  9392. // Server is down...
  9393. {
  9394. Client cli(HOST, PORT);
  9395. auto res = cli.Get("/hi");
  9396. EXPECT_FALSE(res);
  9397. }
  9398. }
  9399. }
  9400. #endif
  9401. // Helper function for string body upload progress tests
  9402. template <typename SetupHandler, typename ClientCall>
  9403. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9404. ClientCall &&client_call,
  9405. const string &body) {
  9406. Server svr;
  9407. setup_handler(svr);
  9408. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9409. auto se = detail::scope_exit([&] {
  9410. svr.stop();
  9411. t.join();
  9412. });
  9413. svr.wait_until_ready();
  9414. Client cli(HOST, PORT);
  9415. vector<uint64_t> progress_values;
  9416. bool progress_called = false;
  9417. auto res =
  9418. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9419. progress_values.push_back(current);
  9420. progress_called = true;
  9421. return true;
  9422. });
  9423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9424. EXPECT_EQ(200, res->status);
  9425. EXPECT_TRUE(progress_called);
  9426. }
  9427. TEST(UploadProgressTest, PostStringBodyBasic) {
  9428. TestStringBodyUploadProgress(
  9429. [](Server &svr) {
  9430. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9431. res.set_content("received", "text/plain");
  9432. });
  9433. },
  9434. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9435. return cli.Post("/test", body, "text/plain", progress_callback);
  9436. },
  9437. "test data for upload progress");
  9438. }
  9439. TEST(UploadProgressTest, PutStringBodyBasic) {
  9440. TestStringBodyUploadProgress(
  9441. [](Server &svr) {
  9442. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9443. res.set_content("put received", "text/plain");
  9444. });
  9445. },
  9446. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9447. return cli.Put("/test", body, "text/plain", progress_callback);
  9448. },
  9449. "put test data for upload progress");
  9450. }
  9451. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9452. TestStringBodyUploadProgress(
  9453. [](Server &svr) {
  9454. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9455. res.set_content("patch received", "text/plain");
  9456. });
  9457. },
  9458. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9459. return cli.Patch("/test", body, "text/plain", progress_callback);
  9460. },
  9461. "patch test data for upload progress");
  9462. }
  9463. // Helper function for content provider upload progress tests
  9464. template <typename SetupHandler, typename ClientCall>
  9465. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9466. ClientCall &&client_call) {
  9467. Server svr;
  9468. setup_handler(svr);
  9469. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9470. auto se = detail::scope_exit([&] {
  9471. svr.stop();
  9472. t.join();
  9473. });
  9474. svr.wait_until_ready();
  9475. Client cli(HOST, PORT);
  9476. vector<uint64_t> progress_values;
  9477. auto res =
  9478. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9479. progress_values.push_back(current);
  9480. return true;
  9481. });
  9482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9483. EXPECT_EQ(200, res->status);
  9484. EXPECT_FALSE(progress_values.empty());
  9485. }
  9486. TEST(UploadProgressTest, PostContentProviderProgress) {
  9487. TestContentProviderUploadProgress(
  9488. [](Server &svr) {
  9489. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9490. res.set_content("provider received", "text/plain");
  9491. });
  9492. },
  9493. [](Client &cli, UploadProgress progress_callback) {
  9494. return cli.Post(
  9495. "/test", 10,
  9496. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9497. sink.os << "test data";
  9498. return true;
  9499. },
  9500. "text/plain", progress_callback);
  9501. });
  9502. }
  9503. // Helper function for multipart upload progress tests
  9504. template <typename SetupHandler, typename ClientCall>
  9505. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9506. ClientCall &&client_call,
  9507. const string &endpoint) {
  9508. Server svr;
  9509. setup_handler(svr);
  9510. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9511. auto se = detail::scope_exit([&] {
  9512. svr.stop();
  9513. t.join();
  9514. });
  9515. svr.wait_until_ready();
  9516. Client cli(HOST, PORT);
  9517. vector<uint64_t> progress_values;
  9518. UploadFormDataItems items = {
  9519. {"field1", "value1", "", ""},
  9520. {"field2", "longer value for progress tracking test", "", ""},
  9521. {"file1", "file content data for upload progress", "test.txt",
  9522. "text/plain"}};
  9523. auto res = client_call(cli, endpoint, items,
  9524. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9525. progress_values.push_back(current);
  9526. return true;
  9527. });
  9528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9529. EXPECT_EQ(200, res->status);
  9530. EXPECT_FALSE(progress_values.empty());
  9531. }
  9532. TEST(UploadProgressTest, PostMultipartProgress) {
  9533. TestMultipartUploadProgress(
  9534. [](Server &svr) {
  9535. svr.Post("/multipart", [](const Request &req, Response &res) {
  9536. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9537. res.set_content("multipart received", "text/plain");
  9538. });
  9539. },
  9540. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9541. UploadProgress progress_callback) {
  9542. return cli.Post(endpoint, items, progress_callback);
  9543. },
  9544. "/multipart");
  9545. }
  9546. // Helper function for basic download progress tests
  9547. template <typename SetupHandler, typename ClientCall>
  9548. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9549. ClientCall &&client_call, const string &endpoint,
  9550. size_t expected_content_size) {
  9551. Server svr;
  9552. setup_handler(svr);
  9553. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9554. auto se = detail::scope_exit([&] {
  9555. svr.stop();
  9556. t.join();
  9557. });
  9558. svr.wait_until_ready();
  9559. Client cli(HOST, PORT);
  9560. vector<uint64_t> progress_values;
  9561. auto res = client_call(cli, endpoint,
  9562. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9563. progress_values.push_back(current);
  9564. return true;
  9565. });
  9566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9567. EXPECT_EQ(200, res->status);
  9568. EXPECT_FALSE(progress_values.empty());
  9569. EXPECT_EQ(expected_content_size, res->body.size());
  9570. }
  9571. TEST(DownloadProgressTest, GetBasic) {
  9572. TestBasicDownloadProgress(
  9573. [](Server &svr) {
  9574. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9575. string content(1000, 'D');
  9576. res.set_content(content, "text/plain");
  9577. });
  9578. },
  9579. [](Client &cli, const string &endpoint,
  9580. DownloadProgress progress_callback) {
  9581. return cli.Get(endpoint, progress_callback);
  9582. },
  9583. "/download", 1000u);
  9584. }
  9585. // Helper function for content receiver download progress tests
  9586. template <typename SetupHandler, typename ClientCall>
  9587. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9588. ClientCall &&client_call,
  9589. const string &endpoint,
  9590. size_t expected_content_size) {
  9591. Server svr;
  9592. setup_handler(svr);
  9593. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9594. auto se = detail::scope_exit([&] {
  9595. svr.stop();
  9596. t.join();
  9597. });
  9598. svr.wait_until_ready();
  9599. Client cli(HOST, PORT);
  9600. vector<uint64_t> progress_values;
  9601. string received_body;
  9602. auto res = client_call(
  9603. cli, endpoint,
  9604. [&](const char *data, size_t data_length) -> bool {
  9605. received_body.append(data, data_length);
  9606. return true;
  9607. },
  9608. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9609. progress_values.push_back(current);
  9610. return true;
  9611. });
  9612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9613. EXPECT_EQ(200, res->status);
  9614. EXPECT_FALSE(progress_values.empty());
  9615. EXPECT_EQ(expected_content_size, received_body.size());
  9616. EXPECT_TRUE(res->body.empty());
  9617. }
  9618. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9619. TestContentReceiverDownloadProgress(
  9620. [](Server &svr) {
  9621. svr.Get("/download-receiver",
  9622. [](const Request & /*req*/, Response &res) {
  9623. string content(2000, 'R');
  9624. res.set_content(content, "text/plain");
  9625. });
  9626. },
  9627. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9628. DownloadProgress progress_callback) {
  9629. return cli.Get(endpoint, content_receiver, progress_callback);
  9630. },
  9631. "/download-receiver", 2000u);
  9632. }
  9633. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9634. // A provider reaching a pass with nothing to hand over - an empty buffer
  9635. // popped off a queue, say - must not be taken to mean the body is finished.
  9636. // It used to end the loop with the terminating chunk unwritten while the
  9637. // server still considered the response complete, so the peer waited for an
  9638. // end that never arrived.
  9639. Server svr;
  9640. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9641. auto step = std::make_shared<int>(0);
  9642. res.set_chunked_content_provider("text/plain",
  9643. [step](size_t /*offset*/, DataSink &sink) {
  9644. switch ((*step)++) {
  9645. case 0: sink.write("", 0); break;
  9646. case 1: sink.write("hello", 5); break;
  9647. default: sink.done(); break;
  9648. }
  9649. return true;
  9650. });
  9651. });
  9652. auto port = svr.bind_to_any_port(HOST);
  9653. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9654. auto listen_se = detail::scope_exit([&] {
  9655. svr.stop();
  9656. listen_thread.join();
  9657. ASSERT_FALSE(svr.is_running());
  9658. });
  9659. svr.wait_until_ready();
  9660. Client cli(HOST, port);
  9661. // Without the fix the body is never terminated, so bound the wait rather
  9662. // than letting the test hang on the default read timeout.
  9663. cli.set_read_timeout(5, 0);
  9664. auto res = cli.Get("/stream");
  9665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9666. EXPECT_EQ(StatusCode::OK_200, res->status);
  9667. EXPECT_EQ("hello", res->body);
  9668. }
  9669. TEST(StreamingTest, NoContentLengthStreaming) {
  9670. Server svr;
  9671. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9672. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9673. if (offset < 6) {
  9674. sink.os << (offset < 3 ? "a" : "b");
  9675. } else {
  9676. sink.done();
  9677. }
  9678. return true;
  9679. });
  9680. });
  9681. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9682. auto listen_se = detail::scope_exit([&] {
  9683. svr.stop();
  9684. listen_thread.join();
  9685. ASSERT_FALSE(svr.is_running());
  9686. });
  9687. svr.wait_until_ready();
  9688. Client client(HOST, PORT);
  9689. auto get_thread = std::thread([&client]() {
  9690. std::string s;
  9691. auto res =
  9692. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9693. s += std::string(data, len);
  9694. return true;
  9695. });
  9696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9697. EXPECT_EQ(StatusCode::OK_200, res->status);
  9698. EXPECT_EQ("aaabbb", s);
  9699. });
  9700. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9701. // Give GET time to get a few messages.
  9702. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9703. }
  9704. TEST(MountTest, Unmount) {
  9705. Server svr;
  9706. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9707. auto se = detail::scope_exit([&] {
  9708. svr.stop();
  9709. listen_thread.join();
  9710. ASSERT_FALSE(svr.is_running());
  9711. });
  9712. svr.wait_until_ready();
  9713. Client cli("localhost", PORT);
  9714. svr.set_mount_point("/mount2", "./www2");
  9715. auto res = cli.Get("/");
  9716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9717. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9718. res = cli.Get("/mount2/dir/test.html");
  9719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9720. EXPECT_EQ(StatusCode::OK_200, res->status);
  9721. svr.set_mount_point("/", "./www");
  9722. res = cli.Get("/dir/");
  9723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9724. EXPECT_EQ(StatusCode::OK_200, res->status);
  9725. svr.remove_mount_point("/");
  9726. res = cli.Get("/dir/");
  9727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9728. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9729. svr.remove_mount_point("/mount2");
  9730. res = cli.Get("/mount2/dir/test.html");
  9731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9732. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9733. }
  9734. TEST(MountTest, PathSegmentBoundary) {
  9735. Server svr;
  9736. svr.set_mount_point("/mount2", "./www2");
  9737. svr.set_mount_point("/", "./www");
  9738. auto port = svr.bind_to_any_port(HOST);
  9739. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9740. auto se = detail::scope_exit([&] {
  9741. svr.stop();
  9742. listen_thread.join();
  9743. ASSERT_FALSE(svr.is_running());
  9744. });
  9745. svr.wait_until_ready();
  9746. Client cli(HOST, port);
  9747. auto res = cli.Get("/mount2/dir/test.html");
  9748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9749. EXPECT_EQ(StatusCode::OK_200, res->status);
  9750. // "/mount2" must not match part-way through a path segment.
  9751. res = cli.Get("/mount2dir/test.html");
  9752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9753. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9754. // A mount point ending in '/' keeps matching every path below it.
  9755. res = cli.Get("/dir/test.html");
  9756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9757. EXPECT_EQ(StatusCode::OK_200, res->status);
  9758. }
  9759. TEST(MountTest, Redicect) {
  9760. Server svr;
  9761. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9762. auto se = detail::scope_exit([&] {
  9763. svr.stop();
  9764. listen_thread.join();
  9765. ASSERT_FALSE(svr.is_running());
  9766. });
  9767. svr.set_mount_point("/", "./www");
  9768. svr.wait_until_ready();
  9769. Client cli("localhost", PORT);
  9770. auto res = cli.Get("/dir/");
  9771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9772. EXPECT_EQ(StatusCode::OK_200, res->status);
  9773. res = cli.Get("/dir");
  9774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9775. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9776. res = cli.Get("/file");
  9777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9778. EXPECT_EQ(StatusCode::OK_200, res->status);
  9779. res = cli.Get("/file/");
  9780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9781. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9782. cli.set_follow_location(true);
  9783. res = cli.Get("/dir");
  9784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9785. EXPECT_EQ(StatusCode::OK_200, res->status);
  9786. }
  9787. TEST(MountTest, MultibytesPathName) {
  9788. Server svr;
  9789. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9790. auto se = detail::scope_exit([&] {
  9791. svr.stop();
  9792. listen_thread.join();
  9793. ASSERT_FALSE(svr.is_running());
  9794. });
  9795. svr.set_mount_point("/", "./www");
  9796. svr.wait_until_ready();
  9797. Client cli("localhost", PORT);
  9798. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9800. EXPECT_EQ(StatusCode::OK_200, res->status);
  9801. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9802. }
  9803. #ifdef _WIN32
  9804. // Issue #2435: mmap::open() must succeed even when another handle holds
  9805. // the file open for writing (e.g. an active log file).
  9806. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9807. const char *path = "mmap_concurrent_writer_test.txt";
  9808. const char *content = "hello";
  9809. {
  9810. std::ofstream f(path, std::ios::binary);
  9811. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9812. }
  9813. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9814. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9815. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9816. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9817. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9818. detail::mmap m(path);
  9819. ASSERT_TRUE(m.is_open());
  9820. EXPECT_EQ(strlen(content), m.size());
  9821. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9822. }
  9823. #endif
  9824. #ifndef _WIN32
  9825. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9826. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9827. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9828. TEST(MmapTest, FailedMappingIsNotOpen) {
  9829. const char *path = "./mmap_failed_mapping_test_dir";
  9830. ASSERT_EQ(0, ::mkdir(path, 0755));
  9831. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9832. detail::mmap m(path);
  9833. EXPECT_FALSE(m.is_open());
  9834. EXPECT_EQ(0U, m.size());
  9835. EXPECT_NE(static_cast<const void *>(m.data()),
  9836. static_cast<const void *>(MAP_FAILED));
  9837. }
  9838. #endif
  9839. TEST(KeepAliveTest, ReadTimeout) {
  9840. Server svr;
  9841. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9842. std::this_thread::sleep_for(std::chrono::seconds(2));
  9843. res.set_content("a", "text/plain");
  9844. });
  9845. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9846. res.set_content("b", "text/plain");
  9847. });
  9848. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9849. auto se = detail::scope_exit([&] {
  9850. svr.stop();
  9851. listen_thread.join();
  9852. ASSERT_FALSE(svr.is_running());
  9853. });
  9854. svr.wait_until_ready();
  9855. Client cli("localhost", PORT);
  9856. cli.set_keep_alive(true);
  9857. cli.set_read_timeout(std::chrono::seconds(1));
  9858. auto resa = cli.Get("/a");
  9859. ASSERT_FALSE(resa);
  9860. EXPECT_EQ(Error::Read, resa.error());
  9861. auto resb = cli.Get("/b");
  9862. ASSERT_TRUE(resb);
  9863. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9864. EXPECT_EQ("b", resb->body);
  9865. }
  9866. TEST(KeepAliveTest, MaxCount) {
  9867. size_t keep_alive_max_count = 3;
  9868. Server svr;
  9869. svr.set_keep_alive_max_count(keep_alive_max_count);
  9870. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9871. res.set_content("Hello World!", "text/plain");
  9872. });
  9873. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9874. auto se = detail::scope_exit([&] {
  9875. svr.stop();
  9876. listen_thread.join();
  9877. ASSERT_FALSE(svr.is_running());
  9878. });
  9879. svr.wait_until_ready();
  9880. Client cli(HOST, PORT);
  9881. cli.set_keep_alive(true);
  9882. for (size_t i = 0; i < 5; i++) {
  9883. auto result = cli.Get("/hi");
  9884. ASSERT_TRUE(result);
  9885. EXPECT_EQ(StatusCode::OK_200, result->status);
  9886. if (i == keep_alive_max_count - 1) {
  9887. EXPECT_EQ("close", result->get_header_value("Connection"));
  9888. } else {
  9889. EXPECT_FALSE(result->has_header("Connection"));
  9890. }
  9891. }
  9892. }
  9893. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9894. // can pull the next one into the server's buffer. The server must serve it
  9895. // without waiting for the socket to become readable again. The keep-alive
  9896. // timeout outlasts the client's read timeout, so a request left waiting for it
  9897. // shows up as a missing response.
  9898. static void serve_pipelining_routes(Server &svr,
  9899. const std::function<void(int)> &client) {
  9900. svr.set_keep_alive_timeout(5);
  9901. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9902. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9903. });
  9904. svr.Post("/echo", [](const Request &req, Response &res) {
  9905. res.set_content("echo " + req.body, "text/plain");
  9906. });
  9907. auto port = svr.bind_to_any_port(HOST);
  9908. thread t = thread([&] { svr.listen_after_bind(); });
  9909. auto se = detail::scope_exit([&] {
  9910. svr.stop();
  9911. t.join();
  9912. });
  9913. svr.wait_until_ready();
  9914. client(port);
  9915. }
  9916. static std::string
  9917. send_pipelined_requests(const std::vector<std::string> &parts) {
  9918. Server svr;
  9919. std::string res;
  9920. serve_pipelining_routes(svr, [&](int port) {
  9921. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9922. });
  9923. return res;
  9924. }
  9925. static void expect_in_order(const std::string &res,
  9926. const std::vector<std::string> &bodies) {
  9927. size_t pos = 0;
  9928. for (const auto &body : bodies) {
  9929. pos = res.find(body, pos);
  9930. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9931. pos += body.size();
  9932. }
  9933. }
  9934. TEST(KeepAliveTest, PipelinedRequests) {
  9935. auto res = send_pipelined_requests(
  9936. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9937. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9938. "Content-Length: 4\r\n\r\nbody"
  9939. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9940. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9941. }
  9942. // The second request starts in the server's buffer and ends on the socket.
  9943. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9944. auto res =
  9945. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9946. "GET /hi/2 HTTP/1.1\r\nHo",
  9947. "st: localhost\r\nConnection: close\r\n\r\n"});
  9948. expect_in_order(res, {"hi 1", "hi 2"});
  9949. }
  9950. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9951. // CRLF after a body does not turn into a 400 for the next request.
  9952. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9953. auto res = send_pipelined_requests(
  9954. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9955. "Content-Length: 4\r\n\r\nbody\r\n"
  9956. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9957. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9958. expect_in_order(res, {"echo body", "hi 2"});
  9959. }
  9960. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9961. // must not be served as the next request.
  9962. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9963. auto res = send_pipelined_requests(
  9964. {"INVALID REQUEST LINE\r\n\r\n"
  9965. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9966. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9967. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9968. }
  9969. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9970. // Over TLS, the next request is held by the TLS library as already decrypted
  9971. // data rather than on the socket.
  9972. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9973. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9974. std::string res;
  9975. serve_pipelining_routes(svr, [&](int port) {
  9976. auto error = Error::Success;
  9977. auto sock = detail::create_client_socket(
  9978. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9979. /*connection_timeout_sec=*/5, 0,
  9980. /*read_timeout_sec=*/2, 0,
  9981. /*write_timeout_sec=*/5, 0, std::string(), error);
  9982. ASSERT_NE(INVALID_SOCKET, sock);
  9983. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9984. auto ctx = SSL_CTX_new(TLS_client_method());
  9985. auto ssl = SSL_new(ctx);
  9986. auto ssl_se = detail::scope_exit([&] {
  9987. SSL_free(ssl);
  9988. SSL_CTX_free(ctx);
  9989. });
  9990. SSL_set_fd(ssl, static_cast<int>(sock));
  9991. ASSERT_EQ(1, SSL_connect(ssl));
  9992. // One write, so all three requests arrive in one TLS record
  9993. const std::string req =
  9994. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9995. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9996. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  9997. ASSERT_EQ(static_cast<int>(req.size()),
  9998. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  9999. char buf[512];
  10000. int n;
  10001. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10002. res.append(buf, static_cast<size_t>(n));
  10003. }
  10004. });
  10005. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10006. }
  10007. #endif
  10008. TEST(KeepAliveTest, Issue1041) {
  10009. Server svr;
  10010. svr.set_keep_alive_timeout(3);
  10011. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10012. res.set_content("Hello World!", "text/plain");
  10013. });
  10014. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10015. auto se = detail::scope_exit([&] {
  10016. svr.stop();
  10017. listen_thread.join();
  10018. ASSERT_FALSE(svr.is_running());
  10019. });
  10020. svr.wait_until_ready();
  10021. Client cli(HOST, PORT);
  10022. cli.set_keep_alive(true);
  10023. auto result = cli.Get("/hi");
  10024. ASSERT_TRUE(result);
  10025. EXPECT_EQ(StatusCode::OK_200, result->status);
  10026. std::this_thread::sleep_for(std::chrono::seconds(5));
  10027. result = cli.Get("/hi");
  10028. ASSERT_TRUE(result);
  10029. EXPECT_EQ(StatusCode::OK_200, result->status);
  10030. }
  10031. TEST(KeepAliveTest, Issue1959) {
  10032. Server svr;
  10033. svr.set_keep_alive_timeout(5);
  10034. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10035. res.set_content("a", "text/plain");
  10036. });
  10037. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10038. auto se = detail::scope_exit([&] {
  10039. if (!svr.is_running()) return;
  10040. svr.stop();
  10041. listen_thread.join();
  10042. ASSERT_FALSE(svr.is_running());
  10043. });
  10044. svr.wait_until_ready();
  10045. Client cli("localhost", PORT);
  10046. cli.set_keep_alive(true);
  10047. using namespace std::chrono;
  10048. auto start = steady_clock::now();
  10049. cli.Get("/a");
  10050. svr.stop();
  10051. listen_thread.join();
  10052. auto end = steady_clock::now();
  10053. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10054. EXPECT_LT(elapsed, 5000);
  10055. }
  10056. #ifdef CPPHTTPLIB_SSL_ENABLED
  10057. TEST(KeepAliveTest, SSLClientReconnection) {
  10058. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10059. ASSERT_TRUE(svr.is_valid());
  10060. svr.set_keep_alive_timeout(1);
  10061. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10062. res.set_content("Hello World!", "text/plain");
  10063. });
  10064. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10065. auto se = detail::scope_exit([&] {
  10066. svr.stop();
  10067. listen_thread.join();
  10068. ASSERT_FALSE(svr.is_running());
  10069. });
  10070. svr.wait_until_ready();
  10071. SSLClient cli(HOST, PORT);
  10072. cli.enable_server_certificate_verification(false);
  10073. cli.set_keep_alive(true);
  10074. auto result = cli.Get("/hi");
  10075. ASSERT_TRUE(result);
  10076. EXPECT_EQ(StatusCode::OK_200, result->status);
  10077. result = cli.Get("/hi");
  10078. ASSERT_TRUE(result);
  10079. EXPECT_EQ(StatusCode::OK_200, result->status);
  10080. std::this_thread::sleep_for(std::chrono::seconds(2));
  10081. // Recoonect
  10082. result = cli.Get("/hi");
  10083. ASSERT_TRUE(result);
  10084. EXPECT_EQ(StatusCode::OK_200, result->status);
  10085. result = cli.Get("/hi");
  10086. ASSERT_TRUE(result);
  10087. EXPECT_EQ(StatusCode::OK_200, result->status);
  10088. }
  10089. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10090. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10091. ASSERT_TRUE(svr.is_valid());
  10092. svr.set_keep_alive_timeout(1);
  10093. std::string content = "reconnect";
  10094. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10095. res.set_content("Hello World!", "text/plain");
  10096. });
  10097. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10098. auto se = detail::scope_exit([&] {
  10099. svr.stop();
  10100. listen_thread.join();
  10101. ASSERT_FALSE(svr.is_running());
  10102. });
  10103. svr.wait_until_ready();
  10104. SSLClient cli(HOST, PORT);
  10105. cli.enable_server_certificate_verification(false);
  10106. cli.set_keep_alive(true);
  10107. auto result = cli.Post(
  10108. "/hi", content.size(),
  10109. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10110. sink.write(content.c_str(), content.size());
  10111. return true;
  10112. },
  10113. "text/plain");
  10114. ASSERT_TRUE(result);
  10115. EXPECT_EQ(200, result->status);
  10116. std::this_thread::sleep_for(std::chrono::seconds(2));
  10117. // Recoonect
  10118. result = cli.Post(
  10119. "/hi", content.size(),
  10120. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10121. sink.write(content.c_str(), content.size());
  10122. return true;
  10123. },
  10124. "text/plain");
  10125. ASSERT_TRUE(result);
  10126. EXPECT_EQ(200, result->status);
  10127. result = cli.Post(
  10128. "/hi", content.size(),
  10129. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10130. sink.write(content.c_str(), content.size());
  10131. return true;
  10132. },
  10133. "text/plain");
  10134. ASSERT_TRUE(result);
  10135. EXPECT_EQ(200, result->status);
  10136. }
  10137. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10138. using namespace httplib::tls;
  10139. {
  10140. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10141. ASSERT_TRUE(svr.is_valid());
  10142. svr.Get("/sni", [&](const Request &req, Response &res) {
  10143. std::string expected = req.sni();
  10144. EXPECT_EQ(expected, req.get_param_value("expected"));
  10145. res.set_content("ok", "text/plain");
  10146. });
  10147. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10148. auto se = detail::scope_exit([&] {
  10149. svr.stop();
  10150. listen_thread.join();
  10151. ASSERT_FALSE(svr.is_running());
  10152. });
  10153. svr.wait_until_ready();
  10154. {
  10155. SSLClient cli("localhost", PORT);
  10156. cli.enable_server_certificate_verification(false);
  10157. auto res = cli.Get("/sni?expected=localhost");
  10158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10159. }
  10160. {
  10161. SSLClient cli("::1", PORT);
  10162. cli.enable_server_certificate_verification(false);
  10163. auto res = cli.Get("/sni?expected=");
  10164. // NOTE: This may fail if the server is listening on IPv4 only
  10165. // (e.g., when localhost resolves to 127.0.0.1 only)
  10166. if (res) {
  10167. EXPECT_EQ(StatusCode::OK_200, res->status);
  10168. } else {
  10169. EXPECT_EQ(Error::Connection, res.error());
  10170. }
  10171. }
  10172. }
  10173. }
  10174. #endif
  10175. TEST(ClientProblemDetectionTest, ContentProvider) {
  10176. Server svr;
  10177. size_t content_length = 1024 * 1024;
  10178. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10179. res.set_content_provider(
  10180. content_length, "text/plain",
  10181. [&](size_t offset, size_t length, DataSink &sink) {
  10182. auto out_len = std::min(length, static_cast<size_t>(1024));
  10183. std::string out(out_len, '@');
  10184. sink.write(out.data(), out_len);
  10185. return offset < 4096;
  10186. },
  10187. [](bool success) { ASSERT_FALSE(success); });
  10188. });
  10189. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10190. res.set_content_provider(
  10191. 0, "text/plain",
  10192. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10193. EXPECT_TRUE(false);
  10194. return true;
  10195. },
  10196. [](bool success) { ASSERT_FALSE(success); });
  10197. });
  10198. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10199. auto se = detail::scope_exit([&] {
  10200. svr.stop();
  10201. listen_thread.join();
  10202. ASSERT_FALSE(svr.is_running());
  10203. });
  10204. svr.wait_until_ready();
  10205. Client cli("localhost", PORT);
  10206. {
  10207. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10208. size_t /*data_length*/) { return false; });
  10209. ASSERT_FALSE(res);
  10210. }
  10211. {
  10212. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10213. size_t /*data_length*/) { return false; });
  10214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10215. }
  10216. }
  10217. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10218. // A provider that reports success without writing anything and without
  10219. // calling done() used to be handed the same offset and length again on every
  10220. // pass, so it spun for as long as the peer stayed connected.
  10221. Server svr;
  10222. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10223. res.set_content("ok", "text/plain");
  10224. });
  10225. auto port = svr.bind_to_any_port(HOST);
  10226. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10227. auto se = detail::scope_exit([&] {
  10228. svr.stop();
  10229. listen_thread.join();
  10230. ASSERT_FALSE(svr.is_running());
  10231. });
  10232. svr.wait_until_ready();
  10233. std::atomic<int> call_count{0};
  10234. Client cli(HOST, port);
  10235. auto res = cli.Post(
  10236. "/", 1024,
  10237. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10238. // Give up after enough passes to show the spin, so that losing the
  10239. // check below fails this test instead of hanging it.
  10240. return ++call_count < 100;
  10241. },
  10242. "text/plain");
  10243. ASSERT_FALSE(res);
  10244. EXPECT_EQ(Error::Write, res.error());
  10245. EXPECT_EQ(1, call_count.load());
  10246. }
  10247. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10248. // A writer only has to assign `write`. The other three used to be left as
  10249. // empty std::functions, so a provider calling one threw
  10250. // std::bad_function_call out of the thread running it and took the whole
  10251. // process down.
  10252. DataSink sink;
  10253. std::string written;
  10254. sink.write = [&](const char *data, size_t data_len) {
  10255. written.append(data, data_len);
  10256. return true;
  10257. };
  10258. EXPECT_TRUE(sink.is_writable());
  10259. sink.done();
  10260. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10261. EXPECT_TRUE(written.empty());
  10262. }
  10263. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10264. // A sink that cannot carry trailers still has to finish.
  10265. DataSink sink;
  10266. auto done_count = 0;
  10267. sink.done = [&]() { done_count++; };
  10268. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10269. EXPECT_EQ(1, done_count);
  10270. }
  10271. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10272. Server svr;
  10273. const std::string body(4096, 'x');
  10274. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10275. res.set_content_provider(body.size(), "text/plain",
  10276. [&](size_t offset, size_t length, DataSink &sink) {
  10277. sink.write(body.data() + offset, length);
  10278. sink.done();
  10279. return true;
  10280. });
  10281. });
  10282. auto port = svr.bind_to_any_port(HOST);
  10283. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10284. auto se = detail::scope_exit([&] {
  10285. svr.stop();
  10286. listen_thread.join();
  10287. ASSERT_FALSE(svr.is_running());
  10288. });
  10289. svr.wait_until_ready();
  10290. Client cli(HOST, port);
  10291. auto res = cli.Get("/");
  10292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10293. EXPECT_EQ(StatusCode::OK_200, res->status);
  10294. EXPECT_EQ(body, res->body);
  10295. }
  10296. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10297. Server svr;
  10298. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10299. res.set_content_provider(
  10300. 1024, "text/plain",
  10301. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10302. sink.write("hello", 5);
  10303. sink.done(); // short of the 1024 bytes the response promised
  10304. return true;
  10305. });
  10306. });
  10307. auto port = svr.bind_to_any_port(HOST);
  10308. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10309. auto se = detail::scope_exit([&] {
  10310. svr.stop();
  10311. listen_thread.join();
  10312. ASSERT_FALSE(svr.is_running());
  10313. });
  10314. svr.wait_until_ready();
  10315. Client cli(HOST, port);
  10316. cli.set_read_timeout(5, 0);
  10317. // The response is short of its Content-Length, so the client cannot read a
  10318. // complete body. What matters is that this returns at all: a no-op done()
  10319. // would leave the writer looping over a provider that never makes progress.
  10320. auto res = cli.Get("/");
  10321. EXPECT_FALSE(res);
  10322. }
  10323. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10324. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10325. // The compressed path builds the whole body before connecting, so this
  10326. // fails client-side and never reaches a server.
  10327. Client cli(HOST, PORT);
  10328. cli.set_compress(true);
  10329. auto res = cli.Post(
  10330. "/", 1024,
  10331. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10332. sink.write("hello", 5);
  10333. sink.done(); // short of the 1024 bytes the request announced
  10334. return true;
  10335. },
  10336. "text/plain");
  10337. ASSERT_FALSE(res);
  10338. EXPECT_EQ(Error::Write, res.error());
  10339. }
  10340. #endif
  10341. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10342. Server svr;
  10343. svr.set_error_handler([](Request const &, Response &res) -> void {
  10344. res.set_chunked_content_provider(
  10345. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10346. sink.os << "hello";
  10347. sink.os << "world";
  10348. sink.done();
  10349. return true;
  10350. });
  10351. });
  10352. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10353. auto se = detail::scope_exit([&] {
  10354. svr.stop();
  10355. listen_thread.join();
  10356. ASSERT_FALSE(svr.is_running());
  10357. });
  10358. svr.wait_until_ready();
  10359. Client cli("localhost", PORT);
  10360. auto res = cli.Get("/");
  10361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10362. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10363. EXPECT_EQ("helloworld", res->body);
  10364. }
  10365. // A body set after a content provider must replace it, not be sent through it.
  10366. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10367. Server svr;
  10368. svr.set_mount_point("/", "./www");
  10369. svr.set_file_request_handler([](const Request &req, Response &res) {
  10370. if (req.path == "/dir/test.html") {
  10371. res.status = StatusCode::Forbidden_403;
  10372. res.set_content(std::string(5000, 'D'), "text/plain");
  10373. } else if (req.path == "/file") {
  10374. res.status = StatusCode::Forbidden_403;
  10375. res.body = "Denied";
  10376. }
  10377. });
  10378. auto port = svr.bind_to_any_port(HOST);
  10379. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10380. auto se = detail::scope_exit([&] {
  10381. svr.stop();
  10382. t.join();
  10383. ASSERT_FALSE(svr.is_running());
  10384. });
  10385. svr.wait_until_ready();
  10386. Client cli(HOST, port);
  10387. {
  10388. auto res = cli.Get("/dir/test.html");
  10389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10390. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10391. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10392. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10393. }
  10394. {
  10395. auto res = cli.Get("/file");
  10396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10397. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10398. EXPECT_EQ("Denied", res->body);
  10399. }
  10400. {
  10401. auto res = cli.Get("/dir/index.html");
  10402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10403. EXPECT_EQ(StatusCode::OK_200, res->status);
  10404. EXPECT_EQ(0U, res->body.find("<html>"));
  10405. }
  10406. }
  10407. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10408. Server svr;
  10409. std::vector<bool> released;
  10410. std::mutex released_mutex;
  10411. auto releaser = [&](bool success) {
  10412. std::lock_guard<std::mutex> guard(released_mutex);
  10413. released.push_back(success);
  10414. };
  10415. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10416. return sink.write(&"hello"[offset], length);
  10417. };
  10418. svr.Get("/sized", [&](const Request &, Response &res) {
  10419. res.status = StatusCode::NotFound_404;
  10420. res.set_content_provider(5, "text/plain", provider, releaser);
  10421. });
  10422. svr.Get("/chunked", [&](const Request &, Response &res) {
  10423. res.status = StatusCode::ServiceUnavailable_503;
  10424. res.set_chunked_content_provider(
  10425. "text/plain",
  10426. [](size_t, DataSink &sink) {
  10427. sink.os << "chunk";
  10428. sink.done();
  10429. return true;
  10430. },
  10431. releaser);
  10432. });
  10433. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10434. res.set_content_provider(5, "text/plain", provider, releaser);
  10435. throw std::runtime_error("after the provider");
  10436. });
  10437. svr.set_error_handler([](const Request &req, Response &res) {
  10438. // Leave the exception handler's content to it.
  10439. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10440. res.set_content(std::string(1000, 'E'), "text/html");
  10441. return Server::HandlerResponse::Handled;
  10442. });
  10443. svr.set_exception_handler(
  10444. [](const Request &, Response &res, std::exception_ptr) {
  10445. res.status = StatusCode::InternalServerError_500;
  10446. res.set_content(std::string(1000, 'X'), "text/html");
  10447. });
  10448. auto port = svr.bind_to_any_port(HOST);
  10449. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10450. auto se = detail::scope_exit([&] {
  10451. svr.stop();
  10452. t.join();
  10453. ASSERT_FALSE(svr.is_running());
  10454. });
  10455. svr.wait_until_ready();
  10456. Client cli(HOST, port);
  10457. {
  10458. auto res = cli.Get("/sized");
  10459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10460. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10461. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10462. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10463. }
  10464. {
  10465. auto res = cli.Get("/chunked");
  10466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10467. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10468. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10469. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10470. }
  10471. {
  10472. auto res = cli.Get("/throw");
  10473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10474. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10475. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10476. }
  10477. std::lock_guard<std::mutex> guard(released_mutex);
  10478. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10479. }
  10480. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10481. Server svr;
  10482. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10483. return sink.write(&"abc"[offset], length);
  10484. };
  10485. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10486. res.set_file_content("./www/dir/test.html");
  10487. res.set_content("body", "text/plain");
  10488. });
  10489. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10490. res.set_content(std::string(100, 'B'), "text/plain");
  10491. res.set_file_content("./www/dir/test.html");
  10492. });
  10493. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10494. res.set_content(std::string(100, 'B'), "text/plain");
  10495. res.set_content_provider(3, "text/plain", abc);
  10496. });
  10497. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10498. res.set_content_provider(3, "text/plain", abc);
  10499. res.set_content(std::string(100, 'B'), "text/plain");
  10500. });
  10501. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10502. res.set_content_provider(3, "text/plain", abc);
  10503. res.body = "direct";
  10504. });
  10505. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10506. res.set_file_content("./www/dir/test.html");
  10507. res.body = "direct";
  10508. });
  10509. auto port = svr.bind_to_any_port(HOST);
  10510. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10511. auto se = detail::scope_exit([&] {
  10512. svr.stop();
  10513. t.join();
  10514. ASSERT_FALSE(svr.is_running());
  10515. });
  10516. svr.wait_until_ready();
  10517. Client cli(HOST, port);
  10518. auto expect_body = [&](const char *path, const std::string &body) {
  10519. // Uncompressed, so Content-Length can be compared with the body.
  10520. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10521. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10522. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10523. EXPECT_EQ(body, res->body) << path;
  10524. EXPECT_EQ(std::to_string(body.size()),
  10525. res->get_header_value("Content-Length"))
  10526. << path;
  10527. };
  10528. expect_body("/file-then-body", "body");
  10529. expect_body("/body-then-file", "test.html");
  10530. expect_body("/body-then-provider", "abc");
  10531. expect_body("/provider-then-body", std::string(100, 'B'));
  10532. expect_body("/provider-then-direct-body", "direct");
  10533. expect_body("/file-then-direct-body", "direct");
  10534. // Ranges are checked against the body, not the dropped provider.
  10535. {
  10536. auto res = cli.Get("/provider-then-direct-body",
  10537. Headers{{make_range_header({{1, 2}})}});
  10538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10539. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10540. EXPECT_EQ("ir", res->body);
  10541. }
  10542. {
  10543. auto res = cli.Get("/file-then-direct-body",
  10544. Headers{{make_range_header({{7, 8}})}});
  10545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10546. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10547. }
  10548. }
  10549. // Forward declaration (see the base64_encode note).
  10550. namespace httplib {
  10551. namespace detail {
  10552. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10553. const std::string &content_type,
  10554. EncodingType encoding);
  10555. } // namespace detail
  10556. } // namespace httplib
  10557. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10558. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10559. ASSERT_TRUE(mm->is_open());
  10560. Response res;
  10561. detail::set_file_content_provider(res, mm, "text/html",
  10562. detail::EncodingType::None);
  10563. std::string out;
  10564. DataSink sink;
  10565. sink.write = [&](const char *d, size_t l) {
  10566. out.append(d, l);
  10567. return true;
  10568. };
  10569. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10570. EXPECT_EQ("test.html", out);
  10571. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10572. EXPECT_EQ("test.html", out);
  10573. }
  10574. TEST(LongPollingTest, ClientCloseDetection) {
  10575. Server svr;
  10576. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10577. res.set_chunked_content_provider(
  10578. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10579. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10580. sink.os << "hello";
  10581. auto count = 10;
  10582. while (count > 0 && sink.is_writable()) {
  10583. this_thread::sleep_for(chrono::milliseconds(10));
  10584. count--;
  10585. }
  10586. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10587. return true;
  10588. });
  10589. });
  10590. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10591. auto se = detail::scope_exit([&] {
  10592. svr.stop();
  10593. listen_thread.join();
  10594. ASSERT_FALSE(svr.is_running());
  10595. });
  10596. svr.wait_until_ready();
  10597. Client cli("localhost", PORT);
  10598. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10599. EXPECT_EQ("hello", string(data, data_length));
  10600. return false; // close the socket immediately.
  10601. });
  10602. ASSERT_FALSE(res);
  10603. }
  10604. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10605. Server svr;
  10606. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10607. res.set_chunked_content_provider(
  10608. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10609. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10610. sink.os << "hello";
  10611. EXPECT_TRUE(sink.os.good());
  10612. // Wait for the client to close the connection
  10613. auto count = 10;
  10614. while (count > 0 && sink.is_writable()) {
  10615. this_thread::sleep_for(chrono::milliseconds(10));
  10616. count--;
  10617. }
  10618. // After client disconnect, write repeatedly until the socket
  10619. // write actually fails (small writes may be absorbed by the
  10620. // kernel buffer)
  10621. std::string chunk(1024, 'x');
  10622. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10623. sink.os << chunk;
  10624. }
  10625. EXPECT_TRUE(sink.os.fail());
  10626. return true;
  10627. });
  10628. });
  10629. auto port = svr.bind_to_any_port("localhost");
  10630. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10631. auto se = detail::scope_exit([&] {
  10632. svr.stop();
  10633. listen_thread.join();
  10634. ASSERT_FALSE(svr.is_running());
  10635. });
  10636. svr.wait_until_ready();
  10637. Client cli("localhost", port);
  10638. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10639. EXPECT_EQ("hello", string(data, data_length));
  10640. return false; // close the socket immediately.
  10641. });
  10642. ASSERT_FALSE(res);
  10643. }
  10644. TEST(GetWithParametersTest, GetWithParameters) {
  10645. Server svr;
  10646. svr.Get("/", [&](const Request &req, Response &) {
  10647. EXPECT_EQ("world", req.get_param_value("hello"));
  10648. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10649. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10650. });
  10651. svr.Get("/params", [&](const Request &req, Response &) {
  10652. EXPECT_EQ("world", req.get_param_value("hello"));
  10653. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10654. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10655. });
  10656. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10657. EXPECT_EQ("resource-id", req.matches[1]);
  10658. EXPECT_EQ("foo", req.get_param_value("param1"));
  10659. EXPECT_EQ("bar", req.get_param_value("param2"));
  10660. });
  10661. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10662. EXPECT_EQ("user-id", req.path_params.at("id"));
  10663. EXPECT_EQ("foo", req.get_param_value("param1"));
  10664. EXPECT_EQ("bar", req.get_param_value("param2"));
  10665. });
  10666. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10667. auto se = detail::scope_exit([&] {
  10668. svr.stop();
  10669. listen_thread.join();
  10670. ASSERT_FALSE(svr.is_running());
  10671. });
  10672. svr.wait_until_ready();
  10673. {
  10674. Client cli(HOST, PORT);
  10675. Params params;
  10676. params.emplace("hello", "world");
  10677. params.emplace("hello2", "world2");
  10678. params.emplace("hello3", "world3");
  10679. auto res = cli.Get("/", params, Headers{});
  10680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10681. EXPECT_EQ(StatusCode::OK_200, res->status);
  10682. }
  10683. {
  10684. Client cli(HOST, PORT);
  10685. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10687. EXPECT_EQ(StatusCode::OK_200, res->status);
  10688. }
  10689. {
  10690. Client cli(HOST, PORT);
  10691. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10693. EXPECT_EQ(StatusCode::OK_200, res->status);
  10694. }
  10695. {
  10696. Client cli(HOST, PORT);
  10697. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10699. EXPECT_EQ(StatusCode::OK_200, res->status);
  10700. }
  10701. }
  10702. TEST(GetWithParametersTest, GetWithParameters2) {
  10703. Server svr;
  10704. svr.Get("/", [&](const Request &req, Response &res) {
  10705. auto text = req.get_param_value("hello");
  10706. res.set_content(text, "text/plain");
  10707. });
  10708. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10709. auto se = detail::scope_exit([&] {
  10710. svr.stop();
  10711. listen_thread.join();
  10712. ASSERT_FALSE(svr.is_running());
  10713. });
  10714. svr.wait_until_ready();
  10715. Client cli("localhost", PORT);
  10716. Params params;
  10717. params.emplace("hello", "world");
  10718. std::string body;
  10719. auto res = cli.Get("/", params, Headers{},
  10720. [&](const char *data, size_t data_length) {
  10721. body.append(data, data_length);
  10722. return true;
  10723. });
  10724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10725. EXPECT_EQ(StatusCode::OK_200, res->status);
  10726. EXPECT_EQ("world", body);
  10727. }
  10728. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10729. Server svr;
  10730. svr.Get("/search", [&](const Request &req, Response &res) {
  10731. auto q = req.get_param_value("q");
  10732. res.set_content(q, "text/plain");
  10733. });
  10734. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10735. auto se = detail::scope_exit([&] {
  10736. svr.stop();
  10737. listen_thread.join();
  10738. ASSERT_FALSE(svr.is_running());
  10739. });
  10740. svr.wait_until_ready();
  10741. Client cli("localhost", PORT);
  10742. // Verify that Get(path, params) works without requiring Headers argument
  10743. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10745. EXPECT_EQ(StatusCode::OK_200, res->status);
  10746. EXPECT_EQ("cpp-httplib", res->body);
  10747. }
  10748. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10749. auto host = "httpbingo.org";
  10750. auto path = std::string{"/range/32"};
  10751. #ifdef CPPHTTPLIB_SSL_ENABLED
  10752. SSLClient cli(host);
  10753. #else
  10754. Client cli(host);
  10755. #endif
  10756. cli.set_default_headers({make_range_header({{1, 10}})});
  10757. cli.set_connection_timeout(5);
  10758. {
  10759. auto res = cli.Get(path);
  10760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10761. EXPECT_EQ("bcdefghijk", res->body);
  10762. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10763. }
  10764. {
  10765. auto res = cli.Get(path);
  10766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10767. EXPECT_EQ("bcdefghijk", res->body);
  10768. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10769. }
  10770. }
  10771. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10772. Server svr;
  10773. svr.set_default_headers({{"Hello", "World"}});
  10774. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10775. res.set_content("ok", "text/plain");
  10776. });
  10777. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10778. auto se = detail::scope_exit([&] {
  10779. svr.stop();
  10780. listen_thread.join();
  10781. ASSERT_FALSE(svr.is_running());
  10782. });
  10783. svr.wait_until_ready();
  10784. Client cli("localhost", PORT);
  10785. auto res = cli.Get("/");
  10786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10787. EXPECT_EQ(StatusCode::OK_200, res->status);
  10788. EXPECT_EQ("ok", res->body);
  10789. EXPECT_EQ("World", res->get_header_value("Hello"));
  10790. }
  10791. #ifdef CPPHTTPLIB_SSL_ENABLED
  10792. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10793. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10794. ASSERT_TRUE(svr.is_valid());
  10795. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10796. std::this_thread::sleep_for(std::chrono::seconds(2));
  10797. res.set_content("a", "text/plain");
  10798. });
  10799. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10800. res.set_content("b", "text/plain");
  10801. });
  10802. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10803. auto se = detail::scope_exit([&] {
  10804. svr.stop();
  10805. listen_thread.join();
  10806. ASSERT_FALSE(svr.is_running());
  10807. });
  10808. svr.wait_until_ready();
  10809. SSLClient cli("localhost", PORT);
  10810. cli.enable_server_certificate_verification(false);
  10811. cli.set_keep_alive(true);
  10812. cli.set_read_timeout(std::chrono::seconds(1));
  10813. auto resa = cli.Get("/a");
  10814. ASSERT_TRUE(!resa);
  10815. EXPECT_EQ(Error::Read, resa.error());
  10816. auto resb = cli.Get("/b");
  10817. ASSERT_TRUE(resb);
  10818. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10819. EXPECT_EQ("b", resb->body);
  10820. }
  10821. // Closing an idle keep-alive connection sends close_notify and returns. The
  10822. // server must not wait for the client's close_notify: an idle client never
  10823. // sends one, so the worker would be held until the read timeout expires, and
  10824. // stop() would wait for it.
  10825. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10826. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10827. ASSERT_TRUE(svr.is_valid());
  10828. svr.set_keep_alive_timeout(1);
  10829. svr.set_read_timeout(10, 0);
  10830. svr.Get("/", [](const Request &, Response &res) {
  10831. res.set_content("ok", "text/plain");
  10832. });
  10833. auto port = svr.bind_to_any_port(HOST);
  10834. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10835. auto se = detail::scope_exit([&] {
  10836. if (listen_thread.joinable()) {
  10837. svr.stop();
  10838. listen_thread.join();
  10839. }
  10840. });
  10841. svr.wait_until_ready();
  10842. SSLClient cli(HOST, port);
  10843. cli.enable_server_certificate_verification(false);
  10844. cli.set_keep_alive(true);
  10845. auto res = cli.Get("/");
  10846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10847. EXPECT_EQ(StatusCode::OK_200, res->status);
  10848. // Stay idle past the keep-alive timeout so the server closes the connection.
  10849. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10850. auto start = std::chrono::steady_clock::now();
  10851. svr.stop();
  10852. listen_thread.join();
  10853. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10854. std::chrono::steady_clock::now() - start)
  10855. .count();
  10856. EXPECT_LT(elapsed, 3000);
  10857. }
  10858. #endif
  10859. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10860. protected:
  10861. ServerTestWithAI_PASSIVE()
  10862. : cli_(HOST, PORT)
  10863. #ifdef CPPHTTPLIB_SSL_ENABLED
  10864. ,
  10865. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10866. #endif
  10867. {
  10868. #ifdef CPPHTTPLIB_SSL_ENABLED
  10869. cli_.enable_server_certificate_verification(false);
  10870. #endif
  10871. }
  10872. virtual void SetUp() {
  10873. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10874. res.set_content("Hello World!", "text/plain");
  10875. });
  10876. t_ = thread(
  10877. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10878. svr_.wait_until_ready();
  10879. }
  10880. virtual void TearDown() {
  10881. svr_.stop();
  10882. t_.join();
  10883. }
  10884. #ifdef CPPHTTPLIB_SSL_ENABLED
  10885. SSLClient cli_;
  10886. SSLServer svr_;
  10887. #else
  10888. Client cli_;
  10889. Server svr_;
  10890. #endif
  10891. thread t_;
  10892. };
  10893. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10894. auto res = cli_.Get("/hi");
  10895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10896. EXPECT_EQ(StatusCode::OK_200, res->status);
  10897. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10898. EXPECT_EQ("Hello World!", res->body);
  10899. }
  10900. class ServerUpDownTest : public ::testing::Test {
  10901. protected:
  10902. ServerUpDownTest() : cli_(HOST, PORT) {}
  10903. virtual void SetUp() {
  10904. t_ = thread([&]() {
  10905. svr_.bind_to_any_port(HOST);
  10906. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10907. ASSERT_TRUE(svr_.listen_after_bind());
  10908. });
  10909. svr_.wait_until_ready();
  10910. }
  10911. virtual void TearDown() {
  10912. svr_.stop();
  10913. t_.join();
  10914. }
  10915. Client cli_;
  10916. Server svr_;
  10917. thread t_;
  10918. };
  10919. TEST_F(ServerUpDownTest, QuickStartStop) {
  10920. // Should not crash, especially when run with
  10921. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10922. }
  10923. class PayloadMaxLengthTest : public ::testing::Test {
  10924. protected:
  10925. PayloadMaxLengthTest()
  10926. : cli_(HOST, PORT)
  10927. #ifdef CPPHTTPLIB_SSL_ENABLED
  10928. ,
  10929. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10930. #endif
  10931. {
  10932. #ifdef CPPHTTPLIB_SSL_ENABLED
  10933. cli_.enable_server_certificate_verification(false);
  10934. #endif
  10935. }
  10936. virtual void SetUp() {
  10937. svr_.set_payload_max_length(8);
  10938. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10939. res.set_content("test", "text/plain");
  10940. });
  10941. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10942. svr_.wait_until_ready();
  10943. }
  10944. virtual void TearDown() {
  10945. svr_.stop();
  10946. t_.join();
  10947. }
  10948. #ifdef CPPHTTPLIB_SSL_ENABLED
  10949. SSLClient cli_;
  10950. SSLServer svr_;
  10951. #else
  10952. Client cli_;
  10953. Server svr_;
  10954. #endif
  10955. thread t_;
  10956. };
  10957. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10958. auto res = cli_.Post("/test", "123456789", "text/plain");
  10959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10960. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10961. res = cli_.Post("/test", "12345678", "text/plain");
  10962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10963. EXPECT_EQ(StatusCode::OK_200, res->status);
  10964. }
  10965. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10966. // Test chunked encoding with payload exceeding the 8-byte limit
  10967. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10968. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10970. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10971. }
  10972. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10973. // Test chunked encoding with payload within the 8-byte limit
  10974. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10975. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10977. EXPECT_EQ(StatusCode::OK_200, res->status);
  10978. }
  10979. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10980. // Test using send_request to send chunked data exceeding payload limit
  10981. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10982. "Host: " +
  10983. std::string(HOST) + ":" + std::to_string(PORT) +
  10984. "\r\n"
  10985. "Transfer-Encoding: chunked\r\n"
  10986. "Connection: close\r\n"
  10987. "\r\n"
  10988. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10989. "0123456789\r\n"
  10990. "0\r\n" // End chunk
  10991. "\r\n";
  10992. std::string response;
  10993. bool result = send_request(1, chunked_request, &response);
  10994. if (!result) {
  10995. // If send_request fails, it might be because the server closed the
  10996. // connection due to payload limit enforcement, which is acceptable
  10997. SUCCEED()
  10998. << "Server rejected oversized chunked request (connection closed)";
  10999. } else {
  11000. // If we got a response, check if it's an error response or connection was
  11001. // closed early Short response length indicates connection was closed due to
  11002. // payload limit
  11003. if (response.length() <= 10) {
  11004. SUCCEED() << "Server closed connection for oversized chunked request";
  11005. } else {
  11006. // Check for error status codes
  11007. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11008. response.find("Payload Too Large") != std::string::npos ||
  11009. response.find("400") != std::string::npos);
  11010. }
  11011. }
  11012. }
  11013. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11014. // Test request without Content-Length header exceeding payload limit
  11015. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11016. "Host: " +
  11017. std::string(HOST) + ":" +
  11018. std::to_string(PORT) +
  11019. "\r\n"
  11020. "Connection: close\r\n"
  11021. "\r\n";
  11022. // Add payload exceeding the 8-byte limit
  11023. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11024. request_without_content_length += large_payload;
  11025. std::string response;
  11026. bool result = send_request(1, request_without_content_length, &response);
  11027. if (!result) {
  11028. // If send_request fails, server likely closed connection due to payload
  11029. // limit
  11030. SUCCEED() << "Server rejected oversized request without Content-Length "
  11031. "(connection closed)";
  11032. } else {
  11033. // Check if server responded with error or closed connection early
  11034. if (response.length() <= 10) {
  11035. SUCCEED() << "Server closed connection for oversized request without "
  11036. "Content-Length";
  11037. } else {
  11038. // Check for error status codes
  11039. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11040. response.find("Payload Too Large") != std::string::npos ||
  11041. response.find("400") != std::string::npos);
  11042. }
  11043. }
  11044. }
  11045. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11046. // Test request without Content-Length header within payload limit
  11047. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11048. "Host: " +
  11049. std::string(HOST) + ":" +
  11050. std::to_string(PORT) +
  11051. "\r\n"
  11052. "Connection: close\r\n"
  11053. "\r\n";
  11054. // Add payload within the 8-byte limit
  11055. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11056. request_without_content_length += small_payload;
  11057. std::string response;
  11058. bool result = send_request(1, request_without_content_length, &response);
  11059. // For requests without Content-Length, the server may have different behavior
  11060. // The key is that it should not reject due to payload limit for small
  11061. // payloads
  11062. if (result) {
  11063. // Check for any HTTP response (success or error, but not connection closed)
  11064. if (response.length() > 10) {
  11065. SUCCEED()
  11066. << "Server processed request without Content-Length within limit";
  11067. } else {
  11068. // Short response might indicate connection closed, which is acceptable
  11069. SUCCEED() << "Server closed connection for request without "
  11070. "Content-Length (acceptable behavior)";
  11071. }
  11072. } else {
  11073. // Connection failure might be due to protocol requirements
  11074. SUCCEED() << "Connection issue with request without Content-Length "
  11075. "(environment-specific)";
  11076. }
  11077. }
  11078. class LargePayloadMaxLengthTest : public ::testing::Test {
  11079. protected:
  11080. LargePayloadMaxLengthTest()
  11081. : cli_(HOST, PORT)
  11082. #ifdef CPPHTTPLIB_SSL_ENABLED
  11083. ,
  11084. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11085. #endif
  11086. {
  11087. #ifdef CPPHTTPLIB_SSL_ENABLED
  11088. cli_.enable_server_certificate_verification(false);
  11089. #endif
  11090. }
  11091. virtual void SetUp() {
  11092. // Set 10MB payload limit
  11093. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11094. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11095. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11096. res.set_content("Large payload test", "text/plain");
  11097. });
  11098. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11099. svr_.wait_until_ready();
  11100. }
  11101. virtual void TearDown() {
  11102. svr_.stop();
  11103. t_.join();
  11104. }
  11105. #ifdef CPPHTTPLIB_SSL_ENABLED
  11106. SSLClient cli_;
  11107. SSLServer svr_;
  11108. #else
  11109. Client cli_;
  11110. Server svr_;
  11111. #endif
  11112. thread t_;
  11113. };
  11114. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11115. // Test chunked encoding with payload within 10MB limit
  11116. std::string medium_payload(5 * 1024 * 1024,
  11117. 'A'); // 5MB payload, within 10MB limit
  11118. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11120. EXPECT_EQ(StatusCode::OK_200, res->status);
  11121. }
  11122. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11123. // Test chunked encoding with payload exceeding 10MB limit
  11124. std::string large_payload(12 * 1024 * 1024,
  11125. 'B'); // 12MB payload, exceeds 10MB limit
  11126. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11127. // Server may either return 413 or close the connection
  11128. if (res) {
  11129. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11130. } else {
  11131. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11132. }
  11133. }
  11134. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11135. // Test request without Content-Length header within 10MB limit
  11136. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11137. "Host: " +
  11138. std::string(HOST) + ":" +
  11139. std::to_string(PORT) +
  11140. "\r\n"
  11141. "Connection: close\r\n"
  11142. "\r\n";
  11143. // Add 1MB payload (within 10MB limit)
  11144. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11145. request_without_content_length += medium_payload;
  11146. std::string response;
  11147. bool result = send_request(5, request_without_content_length, &response);
  11148. if (result) {
  11149. // Should get a proper HTTP response for payloads within limit
  11150. if (response.length() > 10) {
  11151. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11152. "10MB limit";
  11153. } else {
  11154. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11155. "Content-Length)";
  11156. }
  11157. } else {
  11158. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11159. }
  11160. }
  11161. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11162. // Test request without Content-Length header exceeding 10MB limit
  11163. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11164. "Host: " +
  11165. std::string(HOST) + ":" +
  11166. std::to_string(PORT) +
  11167. "\r\n"
  11168. "Connection: close\r\n"
  11169. "\r\n";
  11170. // Add 12MB payload (exceeds 10MB limit)
  11171. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11172. request_without_content_length += large_payload;
  11173. std::string response;
  11174. bool result = send_request(10, request_without_content_length, &response);
  11175. if (!result) {
  11176. // Server should close connection due to payload limit
  11177. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11178. "(connection closed)";
  11179. } else {
  11180. // Check for error response
  11181. if (response.length() <= 10) {
  11182. SUCCEED()
  11183. << "Server closed connection for 12MB request exceeding 10MB limit";
  11184. } else {
  11185. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11186. response.find("Payload Too Large") != std::string::npos ||
  11187. response.find("400") != std::string::npos);
  11188. }
  11189. }
  11190. }
  11191. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11192. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11193. // path.
  11194. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11195. Server svr;
  11196. const size_t LIMIT = 64 * 1024; // 64KB
  11197. svr.set_payload_max_length(LIMIT);
  11198. size_t total = 0;
  11199. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11200. const ContentReader &content_reader) {
  11201. content_reader([&](const char * /*data*/, size_t len) {
  11202. total += len;
  11203. return true;
  11204. });
  11205. res.status = 200;
  11206. res.set_content("stream_ok", "text/plain");
  11207. });
  11208. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11209. auto se = detail::scope_exit([&] {
  11210. svr.stop();
  11211. thread.join();
  11212. ASSERT_FALSE(svr.is_running());
  11213. });
  11214. svr.wait_until_ready();
  11215. // Prepare 256KB raw data and gzip-compress it
  11216. std::string raw(256 * 1024, 'A');
  11217. std::string gz;
  11218. {
  11219. z_stream zs{};
  11220. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11221. Z_DEFAULT_STRATEGY);
  11222. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11223. zs.avail_in = static_cast<uInt>(raw.size());
  11224. char outbuf[4096];
  11225. int ret;
  11226. do {
  11227. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11228. zs.avail_out = sizeof(outbuf);
  11229. ret = deflate(&zs, Z_FINISH);
  11230. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11231. } while (ret != Z_STREAM_END);
  11232. deflateEnd(&zs);
  11233. }
  11234. Client cli(HOST, PORT);
  11235. cli.set_connection_timeout(std::chrono::seconds(5));
  11236. Headers headers = {{"Content-Encoding", "gzip"}};
  11237. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11238. "application/octet-stream");
  11239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11240. // Server must reject oversized decompressed payloads with 413.
  11241. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11242. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11243. EXPECT_LE(total, LIMIT);
  11244. }
  11245. #ifndef CPPHTTPLIB_SSL_ENABLED
  11246. // For a request with neither Content-Length nor Transfer-Encoding, the
  11247. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11248. // compressed wire bytes straight to the ContentReader without ever routing
  11249. // them through the decompressor, so payload_max_length_ only bounded the
  11250. // compressed size on the wire, not the decompressed size.
  11251. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11252. Server svr;
  11253. const size_t LIMIT = 64 * 1024; // 64KB
  11254. svr.set_payload_max_length(LIMIT);
  11255. size_t total = 0;
  11256. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11257. const ContentReader &content_reader) {
  11258. content_reader([&](const char * /*data*/, size_t len) {
  11259. total += len;
  11260. return true;
  11261. });
  11262. res.status = 200;
  11263. res.set_content("stream_ok", "text/plain");
  11264. });
  11265. auto port = svr.bind_to_any_port(HOST);
  11266. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11267. auto se = detail::scope_exit([&] {
  11268. svr.stop();
  11269. thread.join();
  11270. ASSERT_FALSE(svr.is_running());
  11271. });
  11272. svr.wait_until_ready();
  11273. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11274. // StreamingGzipDecompression test above.
  11275. std::string raw(256 * 1024, 'A');
  11276. std::string gz;
  11277. {
  11278. httplib::detail::gzip_compressor compressor;
  11279. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11280. [&](const char *chunk, size_t len) {
  11281. gz.append(chunk, len);
  11282. return true;
  11283. });
  11284. ASSERT_TRUE(result);
  11285. }
  11286. // Send the gzip body over raw TCP with neither Content-Length nor
  11287. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11288. // kicks in.
  11289. std::string req = "POST /stream HTTP/1.1\r\n"
  11290. "Host: " +
  11291. std::string(HOST) + ":" + std::to_string(port) +
  11292. "\r\n"
  11293. "Content-Encoding: gzip\r\n"
  11294. "Connection: close\r\n"
  11295. "\r\n" +
  11296. gz;
  11297. std::string response;
  11298. ASSERT_TRUE(send_request(5, req, &response, port));
  11299. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11300. EXPECT_LE(total, LIMIT);
  11301. }
  11302. #endif
  11303. #endif
  11304. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11305. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11306. // the payload must be passed through untouched instead of being rejected.
  11307. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11308. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11309. Server svr;
  11310. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11311. res.set_content(body, "image/jpeg");
  11312. res.set_header("Content-Encoding", "UTF-8");
  11313. });
  11314. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11315. res.set_content(body, "image/jpeg");
  11316. res.set_header("Content-Encoding", "identity");
  11317. });
  11318. svr.Post("/echo", [](const Request &req, Response &res) {
  11319. res.set_content(req.body, "image/jpeg");
  11320. });
  11321. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11322. auto se = detail::scope_exit([&] {
  11323. svr.stop();
  11324. t.join();
  11325. ASSERT_FALSE(svr.is_running());
  11326. });
  11327. svr.wait_until_ready();
  11328. Client cli(HOST, PORT);
  11329. {
  11330. auto res = cli.Get("/image");
  11331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11332. EXPECT_EQ(StatusCode::OK_200, res->status);
  11333. EXPECT_EQ(body, res->body);
  11334. }
  11335. {
  11336. auto res = cli.Get("/identity");
  11337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11338. EXPECT_EQ(StatusCode::OK_200, res->status);
  11339. EXPECT_EQ(body, res->body);
  11340. }
  11341. {
  11342. // The same applies to a request body reaching the server.
  11343. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11344. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11346. EXPECT_EQ(StatusCode::OK_200, res->status);
  11347. EXPECT_EQ(body, res->body);
  11348. }
  11349. }
  11350. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11351. // gzip-encoded response even when the build has no zlib support.
  11352. static const char GZIPPED_HELLO_WORLD[] = {
  11353. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11354. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11355. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11356. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11357. // A content coding is a whole token, not something the field value merely
  11358. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11359. // as "fibre" look like Brotli, and turned a multi-coding value like
  11360. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11361. // it was never meant to see.
  11362. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11363. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11364. Server svr;
  11365. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11366. res.set_content(body, "image/jpeg");
  11367. res.set_header("Content-Encoding", "fibre");
  11368. });
  11369. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11370. res.set_content(body, "image/jpeg");
  11371. res.set_header("Content-Encoding", "gzip, br");
  11372. });
  11373. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11374. res.set_content(body, "image/jpeg");
  11375. res.set_header("Content-Encoding", "x-zstd-ish");
  11376. });
  11377. auto port = svr.bind_to_any_port(HOST);
  11378. thread t = thread([&]() { svr.listen_after_bind(); });
  11379. auto se = detail::scope_exit([&] {
  11380. svr.stop();
  11381. t.join();
  11382. ASSERT_FALSE(svr.is_running());
  11383. });
  11384. svr.wait_until_ready();
  11385. Client cli(HOST, port);
  11386. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11387. auto res = cli.Get(path);
  11388. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11389. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11390. // Not a coding we recognize, so the payload comes back untouched
  11391. EXPECT_EQ(body, res->body) << path;
  11392. }
  11393. }
  11394. // A content coding cpp-httplib recognizes but was not built with must be
  11395. // reported as such. Handing the still-compressed payload back to the caller
  11396. // would silently corrupt it.
  11397. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11398. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11399. Server svr;
  11400. // "image/jpeg" keeps the server from applying a content coding of its own,
  11401. // so the hand-crafted Content-Encoding below survives.
  11402. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11403. res.set_content(gzipped, "image/jpeg");
  11404. res.set_header("Content-Encoding", "gzip");
  11405. });
  11406. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11407. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11408. res.set_content(gzipped, "image/jpeg");
  11409. res.set_header("Content-Encoding", "GZIP");
  11410. });
  11411. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11412. auto se = detail::scope_exit([&] {
  11413. svr.stop();
  11414. t.join();
  11415. ASSERT_FALSE(svr.is_running());
  11416. });
  11417. svr.wait_until_ready();
  11418. Client cli(HOST, PORT);
  11419. {
  11420. auto res = cli.Get("/gzipped");
  11421. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11423. EXPECT_EQ("Hello World!", res->body);
  11424. #else
  11425. ASSERT_FALSE(res);
  11426. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11427. #endif
  11428. }
  11429. {
  11430. // open_stream() must behave the same way.
  11431. auto handle = cli.open_stream("GET", "/gzipped");
  11432. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11433. ASSERT_TRUE(handle.is_valid());
  11434. std::string received;
  11435. char buf[256];
  11436. ssize_t n;
  11437. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11438. received.append(buf, static_cast<size_t>(n));
  11439. }
  11440. EXPECT_EQ("Hello World!", received);
  11441. #else
  11442. EXPECT_FALSE(handle.is_valid());
  11443. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11444. #endif
  11445. }
  11446. {
  11447. // A differently-cased coding must not be mistaken for an unknown one, or
  11448. // the body would be handed back still compressed.
  11449. auto res = cli.Get("/gzipped-uppercase");
  11450. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11452. EXPECT_EQ("Hello World!", res->body);
  11453. #else
  11454. ASSERT_FALSE(res);
  11455. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11456. #endif
  11457. }
  11458. }
  11459. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11460. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11461. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11462. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11463. // body a second time and appending a second Content-Encoding field line, so
  11464. // clients that decode one coding per listed value handed back raw gzip bytes.
  11465. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11466. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11467. Server svr;
  11468. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11469. // keeps the server from applying a coding of its own.
  11470. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11471. res.set_content(gzipped, "text/plain");
  11472. res.set_header("Content-Encoding", "gzip");
  11473. });
  11474. auto port = svr.bind_to_any_port(HOST);
  11475. thread t = thread([&]() { svr.listen_after_bind(); });
  11476. auto se = detail::scope_exit([&] {
  11477. svr.stop();
  11478. t.join();
  11479. ASSERT_FALSE(svr.is_running());
  11480. });
  11481. svr.wait_until_ready();
  11482. Client cli(HOST, port);
  11483. Headers headers = {{"Accept-Encoding", "gzip"}};
  11484. auto res = cli.Get("/pre-gzipped", headers);
  11485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11486. EXPECT_EQ(StatusCode::OK_200, res->status);
  11487. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11488. EXPECT_EQ("Hello World!", res->body);
  11489. }
  11490. // A chunked provider settles its coding where the headers are written and
  11491. // reuses it at write time. Both ends of that have to hold: a handler's own
  11492. // Content-Encoding suppresses the coding, and a response without one is still
  11493. // compressed as it always was.
  11494. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11495. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11496. const std::string plain = "Hello World! Hello World! Hello World!";
  11497. Server svr;
  11498. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11499. res.set_header("Content-Encoding", "gzip");
  11500. res.set_chunked_content_provider(
  11501. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11502. sink.write(gzipped.data(), gzipped.size());
  11503. sink.done();
  11504. return true;
  11505. });
  11506. });
  11507. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11508. res.set_chunked_content_provider(
  11509. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11510. sink.write(plain.data(), plain.size());
  11511. sink.done();
  11512. return true;
  11513. });
  11514. });
  11515. auto port = svr.bind_to_any_port(HOST);
  11516. thread t = thread([&]() { svr.listen_after_bind(); });
  11517. auto se = detail::scope_exit([&] {
  11518. svr.stop();
  11519. t.join();
  11520. ASSERT_FALSE(svr.is_running());
  11521. });
  11522. svr.wait_until_ready();
  11523. Client cli(HOST, port);
  11524. Headers headers = {{"Accept-Encoding", "gzip"}};
  11525. {
  11526. auto res = cli.Get("/pre-gzipped", headers);
  11527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11528. EXPECT_EQ(StatusCode::OK_200, res->status);
  11529. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11530. EXPECT_EQ("Hello World!", res->body);
  11531. }
  11532. {
  11533. auto res = cli.Get("/negotiated", headers);
  11534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11535. EXPECT_EQ(StatusCode::OK_200, res->status);
  11536. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11537. EXPECT_EQ(plain, res->body);
  11538. }
  11539. }
  11540. #endif
  11541. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11542. // the same message as the comma-joined one, so both have to be read the same
  11543. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11544. // single gzip coding, and a body the sender says was encoded twice was handed
  11545. // back after one pass, still compressed but presented as decoded.
  11546. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11547. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11548. Server svr;
  11549. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11550. res.set_content(body, "image/jpeg");
  11551. res.headers.emplace("Content-Encoding", "gzip");
  11552. res.headers.emplace("Content-Encoding", "gzip");
  11553. });
  11554. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11555. res.set_content(body, "image/jpeg");
  11556. res.set_header("Content-Encoding", "gzip, gzip");
  11557. });
  11558. auto port = svr.bind_to_any_port(HOST);
  11559. thread t = thread([&]() { svr.listen_after_bind(); });
  11560. auto se = detail::scope_exit([&] {
  11561. svr.stop();
  11562. t.join();
  11563. ASSERT_FALSE(svr.is_running());
  11564. });
  11565. svr.wait_until_ready();
  11566. Client cli(HOST, port);
  11567. // Two codings is not something cpp-httplib decodes, so both representations
  11568. // take the pass-through path rather than one of them being gunzipped once.
  11569. for (const char *path : {"/split", "/joined"}) {
  11570. auto res = cli.Get(path);
  11571. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11572. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11573. EXPECT_EQ(body, res->body) << path;
  11574. }
  11575. }
  11576. // Regression test for DoS vulnerability: a malicious server sending a response
  11577. // without Content-Length header must not cause unbounded memory consumption on
  11578. // the client side. The client should stop reading after a reasonable limit,
  11579. // similar to the server-side set_payload_max_length protection.
  11580. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11581. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11582. #ifndef _WIN32
  11583. signal(SIGPIPE, SIG_IGN);
  11584. #endif
  11585. auto server_thread = std::thread([] {
  11586. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11587. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11588. default_socket_options(srv);
  11589. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11590. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11591. sockaddr_in addr{};
  11592. addr.sin_family = AF_INET;
  11593. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11594. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11595. int opt = 1;
  11596. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11597. #ifdef _WIN32
  11598. reinterpret_cast<const char *>(&opt),
  11599. #else
  11600. &opt,
  11601. #endif
  11602. sizeof(opt));
  11603. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11604. ::listen(srv, 1);
  11605. sockaddr_in cli_addr{};
  11606. socklen_t cli_len = sizeof(cli_addr);
  11607. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11608. if (cli != INVALID_SOCKET) {
  11609. char buf[4096];
  11610. ::recv(cli, buf, sizeof(buf), 0);
  11611. // Malicious response: no Content-Length, no chunked encoding
  11612. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11613. "Connection: close\r\n"
  11614. "\r\n";
  11615. ::send(cli,
  11616. #ifdef _WIN32
  11617. static_cast<const char *>(response_header.c_str()),
  11618. static_cast<int>(response_header.size()),
  11619. #else
  11620. response_header.c_str(), response_header.size(),
  11621. #endif
  11622. 0);
  11623. // Send 10MB of data
  11624. std::string chunk(64 * 1024, 'A');
  11625. size_t total_sent = 0;
  11626. while (total_sent < MALICIOUS_DATA_SIZE) {
  11627. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11628. auto sent = ::send(cli,
  11629. #ifdef _WIN32
  11630. static_cast<const char *>(chunk.c_str()),
  11631. static_cast<int>(to_send),
  11632. #else
  11633. chunk.c_str(), to_send,
  11634. #endif
  11635. 0);
  11636. if (sent <= 0) break;
  11637. total_sent += static_cast<size_t>(sent);
  11638. }
  11639. detail::close_socket(cli);
  11640. }
  11641. detail::close_socket(srv);
  11642. });
  11643. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11644. size_t total_read = 0;
  11645. {
  11646. Client cli("127.0.0.1", PORT + 2);
  11647. cli.set_read_timeout(5, 0);
  11648. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11649. auto stream = cli.open_stream("GET", "/malicious");
  11650. ASSERT_TRUE(stream.is_valid());
  11651. char buffer[64 * 1024];
  11652. ssize_t n;
  11653. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11654. total_read += static_cast<size_t>(n);
  11655. }
  11656. } // StreamHandle and Client destroyed here, closing the socket
  11657. server_thread.join();
  11658. // With set_payload_max_length, the client must stop reading before consuming
  11659. // all 10MB. The read loop should be cut off at or near the configured limit.
  11660. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11661. << "Client read " << total_read << " bytes, exceeding the configured "
  11662. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11663. }
  11664. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11665. // the entire response body without truncation.
  11666. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11667. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11668. #ifndef _WIN32
  11669. signal(SIGPIPE, SIG_IGN);
  11670. #endif
  11671. auto server_thread = std::thread([] {
  11672. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11673. default_socket_options(srv);
  11674. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11675. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11676. sockaddr_in addr{};
  11677. addr.sin_family = AF_INET;
  11678. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11679. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11680. int opt = 1;
  11681. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11682. #ifdef _WIN32
  11683. reinterpret_cast<const char *>(&opt),
  11684. #else
  11685. &opt,
  11686. #endif
  11687. sizeof(opt));
  11688. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11689. ::listen(srv, 1);
  11690. sockaddr_in cli_addr{};
  11691. socklen_t cli_len = sizeof(cli_addr);
  11692. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11693. if (cli != INVALID_SOCKET) {
  11694. char buf[4096];
  11695. ::recv(cli, buf, sizeof(buf), 0);
  11696. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11697. "Connection: close\r\n"
  11698. "\r\n";
  11699. ::send(cli,
  11700. #ifdef _WIN32
  11701. static_cast<const char *>(response_header.c_str()),
  11702. static_cast<int>(response_header.size()),
  11703. #else
  11704. response_header.c_str(), response_header.size(),
  11705. #endif
  11706. 0);
  11707. std::string chunk(64 * 1024, 'A');
  11708. size_t total_sent = 0;
  11709. while (total_sent < DATA_SIZE) {
  11710. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11711. auto sent = ::send(cli,
  11712. #ifdef _WIN32
  11713. static_cast<const char *>(chunk.c_str()),
  11714. static_cast<int>(to_send),
  11715. #else
  11716. chunk.c_str(), to_send,
  11717. #endif
  11718. 0);
  11719. if (sent <= 0) break;
  11720. total_sent += static_cast<size_t>(sent);
  11721. }
  11722. #ifdef _WIN32
  11723. ::shutdown(cli, SD_SEND);
  11724. #else
  11725. ::shutdown(cli, SHUT_WR);
  11726. #endif
  11727. // Drain until the client closes its end, ensuring all data is delivered
  11728. char drain[1024];
  11729. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11730. detail::close_socket(cli);
  11731. }
  11732. detail::close_socket(srv);
  11733. });
  11734. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11735. size_t total_read = 0;
  11736. {
  11737. Client cli("127.0.0.1", PORT + 2);
  11738. cli.set_read_timeout(5, 0);
  11739. cli.set_payload_max_length(0); // 0 means no limit
  11740. auto stream = cli.open_stream("GET", "/data");
  11741. ASSERT_TRUE(stream.is_valid());
  11742. char buffer[64 * 1024];
  11743. ssize_t n;
  11744. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11745. total_read += static_cast<size_t>(n);
  11746. }
  11747. }
  11748. server_thread.join();
  11749. EXPECT_EQ(total_read, DATA_SIZE)
  11750. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11751. << " bytes without truncation, but only read " << total_read << " bytes.";
  11752. }
  11753. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11754. // enormous Content-Length must not cause the client to pre-allocate a huge
  11755. // response body buffer. The reservation is capped at payload_max_length_, and
  11756. // the read itself fails when the body exceeds the limit.
  11757. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11758. #ifndef _WIN32
  11759. signal(SIGPIPE, SIG_IGN);
  11760. #endif
  11761. auto server_thread = std::thread([] {
  11762. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11763. default_socket_options(srv);
  11764. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11765. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11766. sockaddr_in addr{};
  11767. addr.sin_family = AF_INET;
  11768. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11769. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11770. int opt = 1;
  11771. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11772. #ifdef _WIN32
  11773. reinterpret_cast<const char *>(&opt),
  11774. #else
  11775. &opt,
  11776. #endif
  11777. sizeof(opt));
  11778. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11779. ::listen(srv, 1);
  11780. sockaddr_in cli_addr{};
  11781. socklen_t cli_len = sizeof(cli_addr);
  11782. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11783. if (cli != INVALID_SOCKET) {
  11784. char buf[4096];
  11785. ::recv(cli, buf, sizeof(buf), 0);
  11786. // Malicious response: claim a 20GB body but send only a tiny payload.
  11787. std::string response = "HTTP/1.1 200 OK\r\n"
  11788. "Content-Length: 20000000000\r\n"
  11789. "\r\n"
  11790. "abc";
  11791. ::send(cli,
  11792. #ifdef _WIN32
  11793. static_cast<const char *>(response.c_str()),
  11794. static_cast<int>(response.size()),
  11795. #else
  11796. response.c_str(), response.size(),
  11797. #endif
  11798. 0);
  11799. detail::close_socket(cli);
  11800. }
  11801. detail::close_socket(srv);
  11802. });
  11803. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11804. {
  11805. Client cli("127.0.0.1", PORT + 2);
  11806. cli.set_read_timeout(5, 0);
  11807. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11808. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11809. // (server claims more bytes than payload_max_length permits), but it must
  11810. // not exhaust memory before getting there.
  11811. auto res = cli.Get("/malicious");
  11812. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11813. }
  11814. server_thread.join();
  11815. }
  11816. // Verify that content_receiver bypasses the default payload_max_length,
  11817. // allowing streaming downloads larger than 100MB without requiring an explicit
  11818. // set_payload_max_length call.
  11819. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11820. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11821. #ifndef _WIN32
  11822. signal(SIGPIPE, SIG_IGN);
  11823. #endif
  11824. auto server_thread = std::thread([] {
  11825. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11826. default_socket_options(srv);
  11827. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11828. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11829. sockaddr_in addr{};
  11830. addr.sin_family = AF_INET;
  11831. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11832. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11833. int opt = 1;
  11834. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11835. #ifdef _WIN32
  11836. reinterpret_cast<const char *>(&opt),
  11837. #else
  11838. &opt,
  11839. #endif
  11840. sizeof(opt));
  11841. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11842. ::listen(srv, 1);
  11843. sockaddr_in cli_addr{};
  11844. socklen_t cli_len = sizeof(cli_addr);
  11845. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11846. if (cli != INVALID_SOCKET) {
  11847. char buf[4096];
  11848. ::recv(cli, buf, sizeof(buf), 0);
  11849. // Response with Content-Length larger than default 100MB limit
  11850. auto content_length = std::to_string(DATA_SIZE);
  11851. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11852. "Content-Length: " +
  11853. content_length +
  11854. "\r\n"
  11855. "Connection: close\r\n"
  11856. "\r\n";
  11857. ::send(cli,
  11858. #ifdef _WIN32
  11859. static_cast<const char *>(response_header.c_str()),
  11860. static_cast<int>(response_header.size()),
  11861. #else
  11862. response_header.c_str(), response_header.size(),
  11863. #endif
  11864. 0);
  11865. std::string chunk(64 * 1024, 'A');
  11866. size_t total_sent = 0;
  11867. while (total_sent < DATA_SIZE) {
  11868. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11869. auto sent = ::send(cli,
  11870. #ifdef _WIN32
  11871. static_cast<const char *>(chunk.c_str()),
  11872. static_cast<int>(to_send),
  11873. #else
  11874. chunk.c_str(), to_send,
  11875. #endif
  11876. 0);
  11877. if (sent <= 0) break;
  11878. total_sent += static_cast<size_t>(sent);
  11879. }
  11880. detail::close_socket(cli);
  11881. }
  11882. detail::close_socket(srv);
  11883. });
  11884. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11885. size_t total_received = 0;
  11886. {
  11887. Client cli("127.0.0.1", PORT + 2);
  11888. cli.set_read_timeout(10, 0);
  11889. // Do NOT call set_payload_max_length — use the default 100MB limit
  11890. auto res =
  11891. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11892. total_received += data_length;
  11893. return true;
  11894. });
  11895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11896. EXPECT_EQ(StatusCode::OK_200, res->status);
  11897. }
  11898. server_thread.join();
  11899. EXPECT_EQ(total_received, DATA_SIZE)
  11900. << "With content_receiver, the client should read all " << DATA_SIZE
  11901. << " bytes despite the default 100MB payload_max_length, but only read "
  11902. << total_received << " bytes.";
  11903. }
  11904. // Verify that an explicit set_payload_max_length smaller than the response is
  11905. // enforced even when a content_receiver is used.
  11906. TEST(ClientVulnerabilityTest,
  11907. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11908. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11909. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11910. #ifndef _WIN32
  11911. signal(SIGPIPE, SIG_IGN);
  11912. #endif
  11913. auto server_thread = std::thread([] {
  11914. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11915. default_socket_options(srv);
  11916. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11917. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11918. sockaddr_in addr{};
  11919. addr.sin_family = AF_INET;
  11920. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11921. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11922. int opt = 1;
  11923. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11924. #ifdef _WIN32
  11925. reinterpret_cast<const char *>(&opt),
  11926. #else
  11927. &opt,
  11928. #endif
  11929. sizeof(opt));
  11930. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11931. ::listen(srv, 1);
  11932. sockaddr_in cli_addr{};
  11933. socklen_t cli_len = sizeof(cli_addr);
  11934. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11935. if (cli != INVALID_SOCKET) {
  11936. char buf[4096];
  11937. ::recv(cli, buf, sizeof(buf), 0);
  11938. auto content_length = std::to_string(DATA_SIZE);
  11939. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11940. "Content-Length: " +
  11941. content_length +
  11942. "\r\n"
  11943. "Connection: close\r\n"
  11944. "\r\n";
  11945. ::send(cli,
  11946. #ifdef _WIN32
  11947. static_cast<const char *>(response_header.c_str()),
  11948. static_cast<int>(response_header.size()),
  11949. #else
  11950. response_header.c_str(), response_header.size(),
  11951. #endif
  11952. 0);
  11953. std::string chunk(64 * 1024, 'A');
  11954. size_t total_sent = 0;
  11955. while (total_sent < DATA_SIZE) {
  11956. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11957. auto sent = ::send(cli,
  11958. #ifdef _WIN32
  11959. static_cast<const char *>(chunk.c_str()),
  11960. static_cast<int>(to_send),
  11961. #else
  11962. chunk.c_str(), to_send,
  11963. #endif
  11964. 0);
  11965. if (sent <= 0) break;
  11966. total_sent += static_cast<size_t>(sent);
  11967. }
  11968. detail::close_socket(cli);
  11969. }
  11970. detail::close_socket(srv);
  11971. });
  11972. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11973. size_t total_received = 0;
  11974. {
  11975. Client cli("127.0.0.1", PORT + 2);
  11976. cli.set_read_timeout(10, 0);
  11977. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11978. auto res =
  11979. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11980. total_received += data_length;
  11981. return true;
  11982. });
  11983. // Should fail because 200MB exceeds the explicit 150MB limit
  11984. EXPECT_FALSE(res);
  11985. }
  11986. server_thread.join();
  11987. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11988. << "Client with content_receiver should respect the explicit "
  11989. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11990. << total_received << " bytes.";
  11991. }
  11992. // Verify that an explicit set_payload_max_length larger than the response
  11993. // allows the content_receiver to read all data successfully.
  11994. TEST(ClientVulnerabilityTest,
  11995. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11996. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11997. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11998. #ifndef _WIN32
  11999. signal(SIGPIPE, SIG_IGN);
  12000. #endif
  12001. auto server_thread = std::thread([] {
  12002. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12003. default_socket_options(srv);
  12004. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12005. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12006. sockaddr_in addr{};
  12007. addr.sin_family = AF_INET;
  12008. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12009. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12010. int opt = 1;
  12011. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12012. #ifdef _WIN32
  12013. reinterpret_cast<const char *>(&opt),
  12014. #else
  12015. &opt,
  12016. #endif
  12017. sizeof(opt));
  12018. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12019. ::listen(srv, 1);
  12020. sockaddr_in cli_addr{};
  12021. socklen_t cli_len = sizeof(cli_addr);
  12022. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12023. if (cli != INVALID_SOCKET) {
  12024. char buf[4096];
  12025. ::recv(cli, buf, sizeof(buf), 0);
  12026. auto content_length = std::to_string(DATA_SIZE);
  12027. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12028. "Content-Length: " +
  12029. content_length +
  12030. "\r\n"
  12031. "Connection: close\r\n"
  12032. "\r\n";
  12033. ::send(cli,
  12034. #ifdef _WIN32
  12035. static_cast<const char *>(response_header.c_str()),
  12036. static_cast<int>(response_header.size()),
  12037. #else
  12038. response_header.c_str(), response_header.size(),
  12039. #endif
  12040. 0);
  12041. std::string chunk(64 * 1024, 'A');
  12042. size_t total_sent = 0;
  12043. while (total_sent < DATA_SIZE) {
  12044. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12045. auto sent = ::send(cli,
  12046. #ifdef _WIN32
  12047. static_cast<const char *>(chunk.c_str()),
  12048. static_cast<int>(to_send),
  12049. #else
  12050. chunk.c_str(), to_send,
  12051. #endif
  12052. 0);
  12053. if (sent <= 0) break;
  12054. total_sent += static_cast<size_t>(sent);
  12055. }
  12056. #ifdef _WIN32
  12057. ::shutdown(cli, SD_SEND);
  12058. #else
  12059. ::shutdown(cli, SHUT_WR);
  12060. #endif
  12061. char drain[1024];
  12062. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12063. detail::close_socket(cli);
  12064. }
  12065. detail::close_socket(srv);
  12066. });
  12067. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12068. size_t total_received = 0;
  12069. {
  12070. Client cli("127.0.0.1", PORT + 2);
  12071. cli.set_read_timeout(10, 0);
  12072. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12073. auto res =
  12074. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12075. total_received += data_length;
  12076. return true;
  12077. });
  12078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12079. EXPECT_EQ(StatusCode::OK_200, res->status);
  12080. }
  12081. server_thread.join();
  12082. EXPECT_EQ(total_received, DATA_SIZE)
  12083. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12084. << " bytes (larger than " << DATA_SIZE
  12085. << " bytes response), content_receiver should read all data, but only "
  12086. "read "
  12087. << total_received << " bytes.";
  12088. }
  12089. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12090. // Regression test for "zip bomb" attack on the client side: a malicious server
  12091. // sends a small gzip-compressed response that decompresses to a huge payload.
  12092. // The client must enforce payload_max_length on the decompressed size.
  12093. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12094. constexpr size_t DECOMPRESSED_SIZE =
  12095. 10 * 1024 * 1024; // 10MB after decompression
  12096. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12097. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12098. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12099. std::string compressed;
  12100. {
  12101. httplib::detail::gzip_compressor compressor;
  12102. bool ok =
  12103. compressor.compress(uncompressed.data(), uncompressed.size(),
  12104. /*last=*/true, [&](const char *buf, size_t len) {
  12105. compressed.append(buf, len);
  12106. return true;
  12107. });
  12108. ASSERT_TRUE(ok);
  12109. }
  12110. // Sanity: compressed data should be much smaller than the decompressed size
  12111. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12112. #ifndef _WIN32
  12113. signal(SIGPIPE, SIG_IGN);
  12114. #endif
  12115. // Set up the listening socket in the main thread so the server is guaranteed
  12116. // to be ready before the client connects (eliminates race condition).
  12117. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12118. default_socket_options(srv);
  12119. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12120. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12121. sockaddr_in addr{};
  12122. addr.sin_family = AF_INET;
  12123. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12124. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12125. int opt = 1;
  12126. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12127. #ifdef _WIN32
  12128. reinterpret_cast<const char *>(&opt),
  12129. #else
  12130. &opt,
  12131. #endif
  12132. sizeof(opt));
  12133. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12134. ASSERT_EQ(0, ::listen(srv, 1));
  12135. auto server_thread = std::thread([&compressed, srv] {
  12136. sockaddr_in cli_addr{};
  12137. socklen_t cli_len = sizeof(cli_addr);
  12138. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12139. if (cli != INVALID_SOCKET) {
  12140. // Read the full HTTP request (until \r\n\r\n)
  12141. char buf[4096];
  12142. size_t total = 0;
  12143. while (total < sizeof(buf)) {
  12144. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12145. if (n <= 0) break;
  12146. total += static_cast<size_t>(n);
  12147. // Check for end of headers
  12148. if (total >= 4) {
  12149. std::string req(buf, total);
  12150. if (req.find("\r\n\r\n") != std::string::npos) break;
  12151. }
  12152. }
  12153. // Malicious response: gzip-compressed body, no Content-Length
  12154. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12155. "Content-Encoding: gzip\r\n"
  12156. "Connection: close\r\n"
  12157. "\r\n";
  12158. ::send(cli,
  12159. #ifdef _WIN32
  12160. static_cast<const char *>(response_header.c_str()),
  12161. static_cast<int>(response_header.size()),
  12162. #else
  12163. response_header.c_str(), response_header.size(),
  12164. #endif
  12165. 0);
  12166. // Send the compressed payload (small on the wire, huge when decompressed)
  12167. size_t total_sent = 0;
  12168. while (total_sent < compressed.size()) {
  12169. auto to_send = std::min(compressed.size() - total_sent,
  12170. static_cast<size_t>(64 * 1024));
  12171. auto sent =
  12172. ::send(cli,
  12173. #ifdef _WIN32
  12174. static_cast<const char *>(compressed.c_str() + total_sent),
  12175. static_cast<int>(to_send),
  12176. #else
  12177. compressed.c_str() + total_sent, to_send,
  12178. #endif
  12179. 0);
  12180. if (sent <= 0) break;
  12181. total_sent += static_cast<size_t>(sent);
  12182. }
  12183. detail::close_socket(cli);
  12184. }
  12185. });
  12186. auto se = detail::scope_exit([&] {
  12187. detail::close_socket(srv);
  12188. server_thread.join();
  12189. });
  12190. size_t total_decompressed = 0;
  12191. {
  12192. Client cli("127.0.0.1", PORT + 3);
  12193. cli.set_read_timeout(5, 0);
  12194. cli.set_decompress(true);
  12195. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12196. auto stream = cli.open_stream("GET", "/zipbomb");
  12197. ASSERT_TRUE(stream.is_valid());
  12198. char buffer[64 * 1024];
  12199. ssize_t n;
  12200. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12201. total_decompressed += static_cast<size_t>(n);
  12202. }
  12203. }
  12204. // The decompressed size must be capped by payload_max_length. Without
  12205. // protection, the client would decompress the full 10MB from a tiny
  12206. // compressed payload, enabling a zip bomb DoS attack.
  12207. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12208. << "Client decompressed " << total_decompressed
  12209. << " bytes from a gzip response. The decompressed size should be "
  12210. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12211. }
  12212. #endif
  12213. TEST(HostAndPortPropertiesTest, NoSSL) {
  12214. httplib::Client cli("www.google.com", 1234);
  12215. ASSERT_EQ("www.google.com", cli.host());
  12216. ASSERT_EQ(1234, cli.port());
  12217. }
  12218. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12219. httplib::Client cli("www.google.com:1234");
  12220. ASSERT_EQ("www.google.com", cli.host());
  12221. ASSERT_EQ(1234, cli.port());
  12222. }
  12223. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12224. // Port number that overflows int — should not crash, client becomes invalid
  12225. httplib::Client cli("http://www.google.com:99999999999999999999");
  12226. ASSERT_FALSE(cli.is_valid());
  12227. }
  12228. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12229. // Port 99999 exceeds valid range (1-65535) — should not crash
  12230. httplib::Client cli("http://www.google.com:99999");
  12231. ASSERT_FALSE(cli.is_valid());
  12232. }
  12233. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12234. httplib::Client cli("http://www.google.com:80abc");
  12235. ASSERT_FALSE(cli.is_valid());
  12236. }
  12237. #ifdef CPPHTTPLIB_SSL_ENABLED
  12238. TEST(HostAndPortPropertiesTest, SSL) {
  12239. httplib::SSLClient cli("www.google.com");
  12240. ASSERT_EQ("www.google.com", cli.host());
  12241. ASSERT_EQ(443, cli.port());
  12242. }
  12243. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12244. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12245. std::string cert;
  12246. read_file(CA_CERT_FILE, cert);
  12247. httplib::SSLClient httplib_client("www.google.com");
  12248. // Load CA store first time
  12249. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12250. // Load CA store second time (update)
  12251. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12252. // Verify client is still valid and can make connections
  12253. httplib_client.enable_server_certificate_verification(true);
  12254. auto res = httplib_client.Get("/");
  12255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12256. // Google may return 200 or 301 depending on various factors
  12257. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12258. res->status == StatusCode::MovedPermanently_301);
  12259. }
  12260. TEST(SSLClientTest, ServerNameIndication_Online) {
  12261. auto host = "httpbingo.org";
  12262. auto path = std::string{"/get"};
  12263. SSLClient cli(host, 443);
  12264. auto res = cli.Get(path);
  12265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12266. ASSERT_EQ(StatusCode::OK_200, res->status);
  12267. }
  12268. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12269. // Use a site that will cause SSL verification failure due to self-signed cert
  12270. SSLClient cli("self-signed.badssl.com", 443);
  12271. cli.enable_server_certificate_verification(true);
  12272. auto res = cli.Get("/");
  12273. ASSERT_TRUE(!res);
  12274. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12275. // Verify backend error is captured for SSLServerVerification
  12276. // This occurs when certificate verification fails
  12277. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12278. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12279. EXPECT_NE(0UL, res.ssl_backend_error());
  12280. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12281. // For OpenSSL, ssl_error is 0 for verification errors
  12282. EXPECT_EQ(0, res.ssl_error());
  12283. #if !defined(_WIN32) || \
  12284. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12285. // On non-Windows or when Windows Schannel is disabled, the error comes
  12286. // from OpenSSL's verification
  12287. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12288. res.ssl_backend_error());
  12289. #endif
  12290. #endif
  12291. }
  12292. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12293. // Use a site where hostname doesn't match the certificate
  12294. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12295. SSLClient cli("wrong.host.badssl.com", 443);
  12296. cli.enable_server_certificate_verification(true);
  12297. cli.enable_server_hostname_verification(true);
  12298. auto res = cli.Get("/");
  12299. ASSERT_TRUE(!res);
  12300. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12301. // Verify backend error is captured for hostname verification failure
  12302. EXPECT_NE(0UL, res.ssl_backend_error());
  12303. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12304. // For OpenSSL, ssl_error is 0 for verification errors
  12305. EXPECT_EQ(0, res.ssl_error());
  12306. #if !defined(_WIN32) || \
  12307. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12308. // On non-Windows or when Windows Schannel is disabled, the error comes
  12309. // from OpenSSL's hostname verification
  12310. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12311. res.ssl_backend_error());
  12312. #endif
  12313. #endif
  12314. }
  12315. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12316. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12317. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12318. SSLClient cli("www.google.com", 443);
  12319. cli.enable_server_certificate_verification(true);
  12320. auto res = cli.Get("/");
  12321. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12322. }
  12323. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12324. SSLClient cli("www.google.com", 443);
  12325. cli.enable_server_certificate_verification(true);
  12326. cli.enable_windows_certificate_verification(false);
  12327. auto res = cli.Get("/");
  12328. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12329. }
  12330. // The server sends an intermediate cross-signed by a root Windows trusts,
  12331. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12332. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12333. SSLClient cli("accounts.spotify.com", 443);
  12334. auto res = cli.Get("/");
  12335. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12336. << " ssl_backend_error=" << res.ssl_backend_error();
  12337. }
  12338. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12339. // policy status, which no backend reports for a self-signed certificate.
  12340. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12341. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12342. ASSERT_TRUE(svr.is_valid());
  12343. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12344. auto se = detail::scope_exit([&] {
  12345. svr.stop();
  12346. t.join();
  12347. ASSERT_FALSE(svr.is_running());
  12348. });
  12349. svr.wait_until_ready();
  12350. SSLClient cli("127.0.0.1", PORT);
  12351. cli.set_connection_timeout(30);
  12352. auto res = cli.Get("/");
  12353. ASSERT_FALSE(res);
  12354. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12355. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12356. }
  12357. #endif
  12358. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12359. Client cli("https://google.com");
  12360. auto res = cli.Get("/");
  12361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12362. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12363. }
  12364. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12365. SSLClient cli("google.com");
  12366. cli.set_ca_cert_path(CA_CERT_FILE);
  12367. auto res = cli.Get("/");
  12368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12369. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12370. }
  12371. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12372. SSLClient cli("google.com");
  12373. cli.enable_server_certificate_verification(true);
  12374. cli.set_ca_cert_path("hello");
  12375. auto res = cli.Get("/");
  12376. ASSERT_TRUE(!res);
  12377. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12378. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12379. // should be set
  12380. EXPECT_EQ(0, res.ssl_error());
  12381. // Verify backend error is captured for SSLLoadingCerts
  12382. // This error occurs when loading CA certificates fails
  12383. EXPECT_NE(0UL, res.ssl_backend_error());
  12384. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12385. // OpenSSL specific error codes:
  12386. // > openssl errstr 0x80000002
  12387. // error:80000002:system library::No such file or directory
  12388. // > openssl errstr 0xA000126
  12389. // error:0A000126:SSL routines::unexpected eof while reading
  12390. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12391. res.ssl_backend_error() == 0xA000126);
  12392. #endif
  12393. }
  12394. TEST(SSLClientTest, ServerCertificateVerification4) {
  12395. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12396. ASSERT_TRUE(svr.is_valid());
  12397. svr.Get("/test", [&](const Request &, Response &res) {
  12398. res.set_content("test", "text/plain");
  12399. svr.stop();
  12400. ASSERT_TRUE(true);
  12401. });
  12402. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12403. auto se = detail::scope_exit([&] {
  12404. t.join();
  12405. ASSERT_FALSE(svr.is_running());
  12406. });
  12407. svr.wait_until_ready();
  12408. SSLClient cli("127.0.0.1", PORT);
  12409. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12410. cli.enable_server_certificate_verification(true);
  12411. cli.set_connection_timeout(30);
  12412. auto res = cli.Get("/test");
  12413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12414. ASSERT_EQ(StatusCode::OK_200, res->status);
  12415. }
  12416. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12417. std::string cert;
  12418. read_file(CA_CERT_FILE, cert);
  12419. SSLClient cli("google.com");
  12420. cli.load_ca_cert_store(cert.data(), cert.size());
  12421. const auto res = cli.Get("/");
  12422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12423. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12424. }
  12425. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12426. // clang-format off
  12427. static constexpr char cert[] =
  12428. "GlobalSign Root CA\n"
  12429. "==================\n"
  12430. "-----BEGIN CERTIFICATE-----\n"
  12431. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12432. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12433. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12434. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12435. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12436. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12437. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12438. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12439. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12440. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12441. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12442. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12443. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12444. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12445. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12446. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12447. "-----END CERTIFICATE-----\n";
  12448. // clang-format on
  12449. SSLClient cli("google.com");
  12450. cli.load_ca_cert_store(cert, sizeof(cert));
  12451. const auto res = cli.Get("/");
  12452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12453. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12454. }
  12455. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12456. SSLClient cli("www.youtube.com");
  12457. cli.set_ca_cert_path(CA_CERT_FILE);
  12458. cli.enable_server_certificate_verification(true);
  12459. cli.set_follow_location(true);
  12460. auto res = cli.Get("/");
  12461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12462. ASSERT_EQ(StatusCode::OK_200, res->status);
  12463. }
  12464. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12465. SSLClient cli("wWw.YouTube.Com");
  12466. cli.set_ca_cert_path(CA_CERT_FILE);
  12467. cli.enable_server_certificate_verification(true);
  12468. cli.enable_server_hostname_verification(true);
  12469. cli.set_follow_location(true);
  12470. auto res = cli.Get("/");
  12471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12472. ASSERT_EQ(StatusCode::OK_200, res->status);
  12473. }
  12474. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12475. SSLClient cli("gOoGlE.COm");
  12476. cli.enable_server_certificate_verification(true);
  12477. cli.enable_server_hostname_verification(true);
  12478. cli.set_follow_location(true);
  12479. auto res = cli.Get("/");
  12480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12481. ASSERT_EQ(StatusCode::OK_200, res->status);
  12482. }
  12483. TEST(SSLClientTest, Issue2004_Online) {
  12484. Client client("https://google.com");
  12485. client.set_follow_location(true);
  12486. auto res = client.Get("/");
  12487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12488. ASSERT_EQ(StatusCode::OK_200, res->status);
  12489. auto body = res->body;
  12490. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12491. }
  12492. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12493. // Create SSLClient with invalid cert/key to make is_valid() return false
  12494. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12495. "nonexistent_key.pem");
  12496. // is_valid() should be false due to cert loading failure
  12497. ASSERT_FALSE(cli.is_valid());
  12498. auto res = cli.Get("/");
  12499. ASSERT_FALSE(res);
  12500. EXPECT_EQ(Error::SSLConnection, res.error());
  12501. }
  12502. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12503. // Test for Issue #2251: SSL error not properly reported when client cert
  12504. // and key paths are swapped or mismatched
  12505. // This simulates the scenario where user accidentally swaps the cert and key
  12506. // files
  12507. // Using client cert file as private key and vice versa (completely wrong)
  12508. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12509. // Should fail validation due to cert/key mismatch
  12510. ASSERT_FALSE(cli.is_valid());
  12511. // Attempt to make a request should fail with proper error
  12512. auto res = cli.Get("/");
  12513. ASSERT_FALSE(res);
  12514. EXPECT_EQ(Error::SSLConnection, res.error());
  12515. // SSL error should be recorded in the Result object (this is the key fix for
  12516. // Issue #2251)
  12517. auto backend_error = res.ssl_backend_error();
  12518. EXPECT_NE(0u, backend_error);
  12519. }
  12520. // Tests cert/key mismatch detection at the TLS context level
  12521. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12522. // Test that using mismatched cert/key causes connection failure.
  12523. // We verify this at the SSLClient level rather than through internal
  12524. // TLS API functions.
  12525. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12526. cli.enable_server_certificate_verification(false);
  12527. cli.set_connection_timeout(2);
  12528. // The mismatch should cause a connection or handshake error
  12529. auto res = cli.Get("/test");
  12530. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12531. // Either way, the request should fail
  12532. EXPECT_FALSE(res);
  12533. }
  12534. #endif
  12535. #if 0
  12536. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12537. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12538. ASSERT_TRUE(cli != nullptr);
  12539. cli->set_address_family(AF_INET6);
  12540. cli->set_interface("en0");
  12541. auto res = cli->Get("/get");
  12542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12543. ASSERT_EQ(StatusCode::OK_200, res->status);
  12544. }
  12545. #endif
  12546. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12547. #ifdef CPPHTTPLIB_SSL_ENABLED
  12548. void ClientCertPresent(
  12549. const std::string &client_cert_file,
  12550. const std::string &client_private_key_file,
  12551. const std::string &client_encrypted_private_key_pass = std::string()) {
  12552. using namespace httplib::tls;
  12553. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12554. CLIENT_CA_CERT_DIR);
  12555. ASSERT_TRUE(svr.is_valid());
  12556. svr.Get("/test", [&](const Request &req, Response &res) {
  12557. res.set_content("test", "text/plain");
  12558. auto cert = req.peer_cert();
  12559. ASSERT_TRUE(static_cast<bool>(cert));
  12560. std::string common_name = cert.subject_cn();
  12561. EXPECT_EQ("Common Name", common_name);
  12562. });
  12563. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12564. auto se = detail::scope_exit([&] {
  12565. svr.stop();
  12566. t.join();
  12567. ASSERT_FALSE(svr.is_running());
  12568. });
  12569. svr.wait_until_ready();
  12570. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12571. client_encrypted_private_key_pass);
  12572. cli.enable_server_certificate_verification(false);
  12573. cli.set_connection_timeout(30);
  12574. auto res = cli.Get("/test");
  12575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12576. ASSERT_EQ(StatusCode::OK_200, res->status);
  12577. }
  12578. TEST(SSLClientServerTest, ClientCertPresent) {
  12579. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12580. }
  12581. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12582. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12583. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12584. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12585. }
  12586. // PEM memory-based constructor tests (works with all TLS backends)
  12587. void PemMemoryClientCertPresent(
  12588. const std::string &client_cert_file,
  12589. const std::string &client_private_key_file,
  12590. const std::string &client_encrypted_private_key_pass = std::string()) {
  12591. // Read PEM files into memory
  12592. std::string server_cert_pem, server_key_pem;
  12593. std::string client_ca_pem;
  12594. std::string client_cert_pem, client_key_pem;
  12595. read_file(SERVER_CERT_FILE, server_cert_pem);
  12596. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12597. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12598. read_file(client_cert_file, client_cert_pem);
  12599. read_file(client_private_key_file, client_key_pem);
  12600. // Create server with PEM memory
  12601. SSLServer::PemMemory server_pem = {
  12602. server_cert_pem.c_str(),
  12603. server_cert_pem.size(),
  12604. server_key_pem.c_str(),
  12605. server_key_pem.size(),
  12606. client_ca_pem.c_str(),
  12607. client_ca_pem.size(),
  12608. nullptr // no password for server key
  12609. };
  12610. SSLServer svr(server_pem);
  12611. ASSERT_TRUE(svr.is_valid());
  12612. svr.Get("/test", [&](const Request &, Response &res) {
  12613. res.set_content("test", "text/plain");
  12614. });
  12615. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12616. auto se = detail::scope_exit([&] {
  12617. svr.stop();
  12618. t.join();
  12619. ASSERT_FALSE(svr.is_running());
  12620. });
  12621. svr.wait_until_ready();
  12622. // Create client with PEM memory
  12623. const char *password = client_encrypted_private_key_pass.empty()
  12624. ? nullptr
  12625. : client_encrypted_private_key_pass.c_str();
  12626. SSLClient::PemMemory client_pem = {
  12627. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12628. client_key_pem.size(), password};
  12629. SSLClient cli(HOST, PORT, client_pem);
  12630. cli.enable_server_certificate_verification(false);
  12631. cli.set_connection_timeout(30);
  12632. auto res = cli.Get("/test");
  12633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12634. ASSERT_EQ(StatusCode::OK_200, res->status);
  12635. }
  12636. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12637. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12638. }
  12639. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12640. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12641. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12642. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12643. }
  12644. TEST(SSLClientServerTest, ClientCertMissing) {
  12645. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12646. CLIENT_CA_CERT_DIR);
  12647. ASSERT_TRUE(svr.is_valid());
  12648. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12649. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12650. auto se = detail::scope_exit([&] {
  12651. svr.stop();
  12652. t.join();
  12653. ASSERT_FALSE(svr.is_running());
  12654. });
  12655. svr.wait_until_ready();
  12656. SSLClient cli(HOST, PORT);
  12657. cli.set_connection_timeout(30);
  12658. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12659. // the chain check on Windows, so the result does not depend on the order.
  12660. cli.enable_server_hostname_verification(false);
  12661. auto res = cli.Get("/test");
  12662. ASSERT_TRUE(!res);
  12663. // When client cert is missing and server requires it, connection fails
  12664. // Error type depends on backend implementation
  12665. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12666. res.error() == Error::SSLConnection);
  12667. // Verify backend error is captured
  12668. // Note: This test may have different error codes depending on the exact
  12669. // verification failure
  12670. EXPECT_NE(0UL, res.ssl_backend_error());
  12671. }
  12672. TEST(SSLClientServerTest, TrustDirOptional) {
  12673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12674. ASSERT_TRUE(svr.is_valid());
  12675. svr.Get("/test", [&](const Request &, Response &res) {
  12676. res.set_content("test", "text/plain");
  12677. });
  12678. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12679. auto se = detail::scope_exit([&] {
  12680. svr.stop();
  12681. t.join();
  12682. ASSERT_FALSE(svr.is_running());
  12683. });
  12684. svr.wait_until_ready();
  12685. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12686. cli.enable_server_certificate_verification(false);
  12687. cli.set_connection_timeout(30);
  12688. auto res = cli.Get("/test");
  12689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12690. ASSERT_EQ(StatusCode::OK_200, res->status);
  12691. }
  12692. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12693. class NoListenSSLServer : public SSLServer {
  12694. public:
  12695. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12696. const char *client_ca_cert_file_path,
  12697. const char *client_ca_cert_dir_path = nullptr)
  12698. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12699. client_ca_cert_dir_path),
  12700. stop_(false) {}
  12701. std::atomic_bool stop_;
  12702. private:
  12703. bool process_and_close_socket(socket_t /*sock*/) override {
  12704. // Don't create SSL context
  12705. while (!stop_.load()) {
  12706. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12707. }
  12708. return true;
  12709. }
  12710. };
  12711. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12712. CLIENT_CA_CERT_FILE);
  12713. ASSERT_TRUE(svr.is_valid());
  12714. svr.Get("/test", [&](const Request &, Response &res) {
  12715. res.set_content("test", "text/plain");
  12716. });
  12717. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12718. auto se = detail::scope_exit([&] {
  12719. svr.stop_ = true;
  12720. svr.stop();
  12721. t.join();
  12722. ASSERT_FALSE(svr.is_running());
  12723. });
  12724. svr.wait_until_ready();
  12725. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12726. cli.enable_server_certificate_verification(false);
  12727. cli.set_connection_timeout(1);
  12728. auto res = cli.Get("/test");
  12729. ASSERT_TRUE(!res);
  12730. EXPECT_EQ(Error::SSLConnection, res.error());
  12731. // Timeout results in WantRead error code (maps to backend-specific value)
  12732. EXPECT_NE(0, res.ssl_error());
  12733. }
  12734. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12735. // Test SSLServer with client certificate verification using the standard
  12736. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12737. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12738. CLIENT_CA_CERT_DIR);
  12739. ASSERT_TRUE(svr.is_valid());
  12740. svr.Get("/test", [&](const Request &req, Response &res) {
  12741. res.set_content("test", "text/plain");
  12742. auto cert = req.peer_cert();
  12743. ASSERT_TRUE(static_cast<bool>(cert));
  12744. auto common_name = cert.subject_cn();
  12745. EXPECT_EQ("Common Name", common_name);
  12746. });
  12747. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12748. auto se = detail::scope_exit([&] {
  12749. svr.stop();
  12750. t.join();
  12751. ASSERT_FALSE(svr.is_running());
  12752. });
  12753. svr.wait_until_ready();
  12754. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12755. cli.enable_server_certificate_verification(false);
  12756. cli.set_connection_timeout(30);
  12757. auto res = cli.Get("/test");
  12758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12759. ASSERT_EQ(StatusCode::OK_200, res->status);
  12760. }
  12761. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12762. // Verifies that wildcard matching and exact matching work consistently
  12763. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12764. using namespace httplib::tls;
  12765. // We need a running server to test against
  12766. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12767. ASSERT_TRUE(svr.is_valid());
  12768. svr.Get("/test", [](const Request &, Response &res) {
  12769. res.set_content("ok", "text/plain");
  12770. });
  12771. thread t([&]() { svr.listen(HOST, PORT); });
  12772. auto se = detail::scope_exit([&] {
  12773. svr.stop();
  12774. t.join();
  12775. });
  12776. svr.wait_until_ready();
  12777. bool verify_callback_called = false;
  12778. bool verify_result_wrong = false;
  12779. SSLClient cli(HOST, PORT);
  12780. cli.enable_server_certificate_verification(true);
  12781. cli.set_ca_cert_path(CA_CERT_FILE);
  12782. cli.set_connection_timeout(5);
  12783. // Note: Test certificate has CN="Common Name", not "localhost"
  12784. bool verify_result_cn = false;
  12785. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12786. verify_callback_called = true;
  12787. if (!ctx.cert) return false;
  12788. // Test 1: "Common Name" should match (our test server cert CN)
  12789. verify_result_cn = ctx.check_hostname("Common Name");
  12790. // Test 2: wrong hostname should not match
  12791. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12792. return true; // Accept for the purpose of this test
  12793. });
  12794. auto res = cli.Get("/test");
  12795. // The request may succeed or fail depending on cert configuration
  12796. // but the callback should have been called
  12797. ASSERT_TRUE(verify_callback_called)
  12798. << "Verify callback should have been called";
  12799. // CN="Common Name" should match our test certificate
  12800. //
  12801. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12802. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12803. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12804. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12805. // <openssl/base.h>, which is included transitively when
  12806. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12807. #if defined(OPENSSL_IS_BORINGSSL)
  12808. EXPECT_FALSE(verify_result_cn)
  12809. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12810. #else
  12811. EXPECT_TRUE(verify_result_cn)
  12812. << "verify_hostname should match 'Common Name' (certificate CN)";
  12813. #endif
  12814. // Wrong hostname should not match
  12815. EXPECT_FALSE(verify_result_wrong)
  12816. << "verify_hostname should not match 'wronghost.example.com'";
  12817. }
  12818. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12819. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12820. // X509_check_ip behavior and must hold for every backend.
  12821. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12822. using namespace httplib::tls;
  12823. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12824. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12825. ASSERT_TRUE(svr.is_valid());
  12826. svr.Get("/test", [](const Request &, Response &res) {
  12827. res.set_content("ok", "text/plain");
  12828. });
  12829. thread t([&]() { svr.listen(HOST, PORT); });
  12830. auto se = detail::scope_exit([&] {
  12831. svr.stop();
  12832. t.join();
  12833. });
  12834. svr.wait_until_ready();
  12835. bool verify_callback_called = false;
  12836. bool ip_matched_via_cn = true;
  12837. SSLClient cli(HOST, PORT);
  12838. cli.enable_server_certificate_verification(true);
  12839. cli.set_ca_cert_path(CA_CERT_FILE);
  12840. cli.set_connection_timeout(5);
  12841. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12842. verify_callback_called = true;
  12843. if (!ctx.cert) return false;
  12844. // The IP appears only in the CN, so it must NOT be accepted.
  12845. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12846. return true; // Accept for the purpose of this test
  12847. });
  12848. cli.Get("/test");
  12849. ASSERT_TRUE(verify_callback_called)
  12850. << "Verify callback should have been called";
  12851. EXPECT_FALSE(ip_matched_via_cn)
  12852. << "An IP host must not be authenticated via the certificate CN";
  12853. }
  12854. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12855. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12856. using namespace httplib::tls;
  12857. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12858. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12859. ASSERT_TRUE(svr.is_valid());
  12860. svr.Get("/test", [](const Request &, Response &res) {
  12861. res.set_content("ok", "text/plain");
  12862. });
  12863. thread t([&]() { svr.listen(HOST, PORT); });
  12864. auto se = detail::scope_exit([&] {
  12865. svr.stop();
  12866. t.join();
  12867. });
  12868. svr.wait_until_ready();
  12869. bool verify_callback_called = false;
  12870. bool san_matched = false;
  12871. bool wrong_ipv6_matched = true;
  12872. bool cn_ipv6_matched = true;
  12873. SSLClient cli(HOST, PORT);
  12874. cli.enable_server_certificate_verification(true);
  12875. cli.set_ca_cert_path(CA_CERT_FILE);
  12876. cli.set_connection_timeout(5);
  12877. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12878. verify_callback_called = true;
  12879. if (!ctx.cert) return false;
  12880. // Matches the IPv6 iPAddress SAN.
  12881. san_matched = ctx.check_hostname("2001:db8::1");
  12882. // A different IPv6 address must not match.
  12883. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12884. // "::1" lives only in the CN, so it must not be accepted.
  12885. cn_ipv6_matched = ctx.check_hostname("::1");
  12886. return true; // Accept for the purpose of this test
  12887. });
  12888. cli.Get("/test");
  12889. ASSERT_TRUE(verify_callback_called)
  12890. << "Verify callback should have been called";
  12891. EXPECT_TRUE(san_matched)
  12892. << "verify_hostname should match an IPv6 iPAddress SAN";
  12893. EXPECT_FALSE(wrong_ipv6_matched)
  12894. << "verify_hostname should not match a non-matching IPv6 address";
  12895. EXPECT_FALSE(cn_ipv6_matched)
  12896. << "An IPv6 host must not be authenticated via the certificate CN";
  12897. }
  12898. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12899. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12900. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12901. using namespace httplib::tls;
  12902. // SANs: DNS:a.zz, IP:42.46.122.122
  12903. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12904. ASSERT_TRUE(svr.is_valid());
  12905. svr.Get("/test", [](const Request &, Response &res) {
  12906. res.set_content("ok", "text/plain");
  12907. });
  12908. auto port = svr.bind_to_any_port(HOST);
  12909. thread t([&]() { svr.listen_after_bind(); });
  12910. auto se = detail::scope_exit([&] {
  12911. svr.stop();
  12912. t.join();
  12913. });
  12914. svr.wait_until_ready();
  12915. bool verify_callback_called = false;
  12916. bool dns_san_matched = false;
  12917. bool ip_san_matched = false;
  12918. bool ip_matched_via_dns_san = true;
  12919. bool dns_matched_via_ip_san = true;
  12920. SSLClient cli(HOST, port);
  12921. cli.enable_server_certificate_verification(true);
  12922. cli.set_ca_cert_path(CA_CERT_FILE);
  12923. cli.set_connection_timeout(5);
  12924. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12925. verify_callback_called = true;
  12926. if (!ctx.cert) return false;
  12927. dns_san_matched = ctx.check_hostname("a.zz");
  12928. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12929. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12930. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12931. return true; // Accept for the purpose of this test
  12932. });
  12933. cli.Get("/test");
  12934. ASSERT_TRUE(verify_callback_called)
  12935. << "Verify callback should have been called";
  12936. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12937. EXPECT_TRUE(ip_san_matched)
  12938. << "verify_hostname should match an iPAddress SAN";
  12939. EXPECT_FALSE(ip_matched_via_dns_san)
  12940. << "An IP host must not be authenticated via a dNSName SAN";
  12941. EXPECT_FALSE(dns_matched_via_ip_san)
  12942. << "A DNS host must not be authenticated via an iPAddress SAN";
  12943. }
  12944. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  12945. // "www.*.example.test" names one host and not every host under example.test.
  12946. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  12947. using namespace httplib::tls;
  12948. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  12949. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  12950. ASSERT_TRUE(svr.is_valid());
  12951. svr.Get("/test", [](const Request &, Response &res) {
  12952. res.set_content("ok", "text/plain");
  12953. });
  12954. auto port = svr.bind_to_any_port(HOST);
  12955. thread t([&]() { svr.listen_after_bind(); });
  12956. auto se = detail::scope_exit([&] {
  12957. svr.stop();
  12958. t.join();
  12959. });
  12960. svr.wait_until_ready();
  12961. bool verify_callback_called = false;
  12962. bool leftmost_wildcard_matched = false;
  12963. bool wildcard_spanned_labels = true;
  12964. bool inner_wildcard_matched = true;
  12965. SSLClient cli(HOST, port);
  12966. cli.enable_server_certificate_verification(true);
  12967. cli.set_ca_cert_path(CA_CERT_FILE);
  12968. cli.set_connection_timeout(5);
  12969. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12970. verify_callback_called = true;
  12971. if (!ctx.cert) return false;
  12972. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  12973. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  12974. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  12975. return true; // Accept for the purpose of this test
  12976. });
  12977. cli.Get("/test");
  12978. ASSERT_TRUE(verify_callback_called)
  12979. << "Verify callback should have been called";
  12980. EXPECT_TRUE(leftmost_wildcard_matched)
  12981. << "A leftmost wildcard should match a single label";
  12982. EXPECT_FALSE(wildcard_spanned_labels)
  12983. << "A wildcard label must not match more than one label";
  12984. EXPECT_FALSE(inner_wildcard_matched)
  12985. << "A wildcard outside the leftmost label must not be honoured";
  12986. }
  12987. // sans() must report each SAN entry under its own type.
  12988. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  12989. using namespace httplib::tls;
  12990. // SANs: DNS:a.zz, IP:42.46.122.122
  12991. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12992. ASSERT_TRUE(svr.is_valid());
  12993. svr.Get("/test", [](const Request &, Response &res) {
  12994. res.set_content("ok", "text/plain");
  12995. });
  12996. auto port = svr.bind_to_any_port(HOST);
  12997. thread t([&]() { svr.listen_after_bind(); });
  12998. auto se = detail::scope_exit([&] {
  12999. svr.stop();
  13000. t.join();
  13001. });
  13002. svr.wait_until_ready();
  13003. bool verify_callback_called = false;
  13004. std::vector<SanEntry> sans;
  13005. SSLClient cli(HOST, port);
  13006. cli.enable_server_certificate_verification(true);
  13007. cli.set_ca_cert_path(CA_CERT_FILE);
  13008. cli.set_connection_timeout(5);
  13009. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13010. verify_callback_called = true;
  13011. if (!ctx.cert) return false;
  13012. sans = ctx.sans();
  13013. return true; // Accept for the purpose of this test
  13014. });
  13015. cli.Get("/test");
  13016. ASSERT_TRUE(verify_callback_called)
  13017. << "Verify callback should have been called";
  13018. auto has_san = [&](SanType type, const std::string &value) {
  13019. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13020. return san.type == type && san.value == value;
  13021. });
  13022. };
  13023. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13024. << "sans() should report the dNSName SAN";
  13025. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13026. << "sans() should report the iPAddress SAN";
  13027. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13028. << "sans() must not report the dNSName SAN as an address";
  13029. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13030. << "sans() must not report the iPAddress SAN as a DNS name";
  13031. }
  13032. #endif
  13033. // mbedTLS-specific callback constructor test
  13034. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13035. #ifdef CPPHTTPLIB_SSL_ENABLED
  13036. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13037. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13038. ASSERT_TRUE(svr.is_valid());
  13039. // Set up a handler to verify client certificate is present
  13040. bool client_cert_verified = false;
  13041. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13042. // Verify that client certificate was provided
  13043. client_cert_verified = true;
  13044. res.set_content("success", "text/plain");
  13045. });
  13046. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13047. auto se = detail::scope_exit([&] {
  13048. svr.stop();
  13049. t.join();
  13050. ASSERT_FALSE(svr.is_running());
  13051. });
  13052. svr.wait_until_ready();
  13053. // Client with certificate
  13054. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13055. cli.enable_server_certificate_verification(false);
  13056. cli.set_connection_timeout(30);
  13057. auto res = cli.Get("/test");
  13058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13059. ASSERT_EQ(StatusCode::OK_200, res->status);
  13060. ASSERT_TRUE(client_cert_verified);
  13061. EXPECT_EQ("success", res->body);
  13062. }
  13063. #endif
  13064. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13065. // backends
  13066. #ifdef CPPHTTPLIB_SSL_ENABLED
  13067. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13068. using namespace httplib::tls;
  13069. // Test that when client CA cert file is provided,
  13070. // the server properly requests and validates client certificates
  13071. // Create a server with client authentication
  13072. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13073. ASSERT_TRUE(svr.is_valid());
  13074. bool handler_called = false;
  13075. svr.Get("/test", [&](const Request &req, Response &res) {
  13076. handler_called = true;
  13077. // Verify that a client certificate was provided
  13078. auto cert = req.peer_cert();
  13079. ASSERT_TRUE(static_cast<bool>(cert));
  13080. // Get the issuer name
  13081. std::string issuer_str = cert.issuer_name();
  13082. ASSERT_FALSE(issuer_str.empty());
  13083. // The client certificate should be issued by our test CA
  13084. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13085. res.set_content("authenticated", "text/plain");
  13086. });
  13087. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13088. auto se = detail::scope_exit([&] {
  13089. svr.stop();
  13090. t.join();
  13091. ASSERT_FALSE(svr.is_running());
  13092. });
  13093. svr.wait_until_ready();
  13094. // Connect with a client certificate issued by the CA
  13095. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13096. cli.enable_server_certificate_verification(false);
  13097. cli.set_connection_timeout(30);
  13098. auto res = cli.Get("/test");
  13099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13100. ASSERT_EQ(StatusCode::OK_200, res->status);
  13101. ASSERT_TRUE(handler_called);
  13102. EXPECT_EQ("authenticated", res->body);
  13103. }
  13104. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13105. using namespace httplib::tls;
  13106. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13107. ASSERT_TRUE(svr.is_valid());
  13108. svr.Get("/test", [](const Request &, Response &res) {
  13109. res.set_content("ok", "text/plain");
  13110. });
  13111. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13112. auto se = detail::scope_exit([&] {
  13113. svr.stop();
  13114. t.join();
  13115. });
  13116. svr.wait_until_ready();
  13117. SSLClient cli(HOST, PORT);
  13118. cli.enable_server_certificate_verification(false);
  13119. cli.set_connection_timeout(30);
  13120. bool cert_checked = false;
  13121. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13122. if (ctx.cert) {
  13123. auto sans = ctx.sans();
  13124. // Test certificate may or may not have SANs - just verify the API
  13125. // works If SANs exist, verify the types are valid
  13126. for (const auto &san : sans) {
  13127. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13128. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13129. san.type == SanType::OTHER);
  13130. EXPECT_FALSE(san.value.empty());
  13131. }
  13132. cert_checked = true;
  13133. }
  13134. return true;
  13135. });
  13136. auto res = cli.Get("/test");
  13137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13138. EXPECT_TRUE(cert_checked);
  13139. }
  13140. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13141. using namespace httplib::tls;
  13142. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13143. ASSERT_TRUE(svr.is_valid());
  13144. svr.Get("/test", [](const Request &, Response &res) {
  13145. res.set_content("ok", "text/plain");
  13146. });
  13147. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13148. auto se = detail::scope_exit([&] {
  13149. svr.stop();
  13150. t.join();
  13151. });
  13152. svr.wait_until_ready();
  13153. SSLClient cli(HOST, PORT);
  13154. cli.enable_server_certificate_verification(false);
  13155. cli.set_connection_timeout(30);
  13156. bool validity_checked = false;
  13157. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13158. if (ctx.cert) {
  13159. time_t not_before = 0, not_after = 0;
  13160. bool result = ctx.validity(not_before, not_after);
  13161. EXPECT_TRUE(result);
  13162. // Verify that not_before < now < not_after for a valid cert
  13163. time_t now = time(nullptr);
  13164. EXPECT_LT(not_before, now);
  13165. EXPECT_GT(not_after, now);
  13166. validity_checked = true;
  13167. }
  13168. return true;
  13169. });
  13170. auto res = cli.Get("/test");
  13171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13172. EXPECT_TRUE(validity_checked);
  13173. }
  13174. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13175. using namespace httplib::tls;
  13176. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13177. ASSERT_TRUE(svr.is_valid());
  13178. svr.Get("/test", [](const Request &, Response &res) {
  13179. res.set_content("ok", "text/plain");
  13180. });
  13181. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13182. auto se = detail::scope_exit([&] {
  13183. svr.stop();
  13184. t.join();
  13185. });
  13186. svr.wait_until_ready();
  13187. SSLClient cli(HOST, PORT);
  13188. cli.enable_server_certificate_verification(false);
  13189. cli.set_connection_timeout(30);
  13190. bool serial_checked = false;
  13191. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13192. if (ctx.cert) {
  13193. std::string serial = ctx.serial();
  13194. EXPECT_FALSE(serial.empty());
  13195. // Serial should be a hex string
  13196. for (char c : serial) {
  13197. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13198. (c >= 'a' && c <= 'f'));
  13199. }
  13200. serial_checked = true;
  13201. }
  13202. return true;
  13203. });
  13204. auto res = cli.Get("/test");
  13205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13206. EXPECT_TRUE(serial_checked);
  13207. }
  13208. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13209. // Test 1: Valid CA file - no error should be recorded
  13210. {
  13211. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13212. CLIENT_CA_CERT_FILE);
  13213. ASSERT_TRUE(svr.is_valid());
  13214. // With valid setup, last_ssl_error should be 0
  13215. EXPECT_EQ(0, svr.ssl_last_error());
  13216. }
  13217. // Test 2: Invalid CA file content
  13218. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13219. {
  13220. // Create a temporary file with completely invalid content
  13221. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13222. {
  13223. std::ofstream ofs(temp_invalid_ca);
  13224. ofs << "This is not a certificate file at all\n";
  13225. ofs << "Just plain text content\n";
  13226. }
  13227. // Create server with invalid CA file
  13228. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13229. // Clean up temporary file
  13230. std::remove(temp_invalid_ca);
  13231. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13232. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13233. // Note: SSL_CTX_load_verify_locations typically fails first,
  13234. // but our error handling code path is still exercised
  13235. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13236. }
  13237. }
  13238. TEST(VerifyCallbackTest, VerifyContextFields) {
  13239. using namespace httplib::tls;
  13240. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13241. ASSERT_TRUE(svr.is_valid());
  13242. svr.Get("/test", [](const Request &, Response &res) {
  13243. res.set_content("ok", "text/plain");
  13244. });
  13245. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13246. auto se = detail::scope_exit([&] {
  13247. svr.stop();
  13248. t.join();
  13249. });
  13250. svr.wait_until_ready();
  13251. SSLClient cli(HOST, PORT);
  13252. cli.enable_server_certificate_verification(false);
  13253. cli.set_connection_timeout(30);
  13254. int callback_count = 0;
  13255. bool saw_leaf_cert = false;
  13256. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13257. if (ctx.cert) {
  13258. callback_count++;
  13259. // We should see at least one certificate (the leaf)
  13260. std::string cn = ctx.subject_cn();
  13261. if (!cn.empty()) { saw_leaf_cert = true; }
  13262. // Verify context fields are populated
  13263. EXPECT_NE(ctx.session, nullptr);
  13264. EXPECT_GE(ctx.depth, 0);
  13265. }
  13266. return true;
  13267. });
  13268. auto res = cli.Get("/test");
  13269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13270. EXPECT_GT(callback_count, 0);
  13271. EXPECT_TRUE(saw_leaf_cert);
  13272. }
  13273. // A verifier belongs to the client that set it, not to the thread that set it.
  13274. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13275. using namespace httplib::tls;
  13276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13277. ASSERT_TRUE(svr.is_valid());
  13278. svr.Get("/test", [](const Request &, Response &res) {
  13279. res.set_content("ok", "text/plain");
  13280. });
  13281. auto port = svr.bind_to_any_port(HOST);
  13282. thread t([&]() { svr.listen_after_bind(); });
  13283. auto se = detail::scope_exit([&] {
  13284. svr.stop();
  13285. t.join();
  13286. });
  13287. svr.wait_until_ready();
  13288. auto rejecting_calls = 0;
  13289. SSLClient rejecting(HOST, port);
  13290. rejecting.enable_server_certificate_verification(false);
  13291. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13292. rejecting_calls++;
  13293. return false;
  13294. });
  13295. auto accepting_calls = 0;
  13296. SSLClient accepting(HOST, port);
  13297. accepting.enable_server_certificate_verification(false);
  13298. // Set on another thread than the requests below.
  13299. thread([&]() {
  13300. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13301. accepting_calls++;
  13302. return true;
  13303. });
  13304. }).join();
  13305. // Requested on another thread than the verifier was set on.
  13306. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13307. EXPECT_GT(rejecting_calls, 0);
  13308. auto res = accepting.Get("/test");
  13309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13310. EXPECT_GT(accepting_calls, 0);
  13311. }
  13312. // VerifyContext::session is the same handle the other tls:: functions take.
  13313. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13314. using namespace httplib::tls;
  13315. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13316. ASSERT_TRUE(svr.is_valid());
  13317. svr.Get("/test", [](const Request &, Response &res) {
  13318. res.set_content("ok", "text/plain");
  13319. });
  13320. auto port = svr.bind_to_any_port(HOST);
  13321. thread t([&]() { svr.listen_after_bind(); });
  13322. auto se = detail::scope_exit([&] {
  13323. svr.stop();
  13324. t.join();
  13325. });
  13326. svr.wait_until_ready();
  13327. SSLClient cli(HOST, port);
  13328. cli.enable_server_certificate_verification(false);
  13329. session_t verifier_session = nullptr;
  13330. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13331. verifier_session = ctx.session;
  13332. return true;
  13333. });
  13334. session_t session_verifier_session = nullptr;
  13335. cli.set_session_verifier([&](session_t session) {
  13336. session_verifier_session = session;
  13337. return SSLVerifierResponse::NoDecisionMade;
  13338. });
  13339. auto res = cli.Get("/test");
  13340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13341. EXPECT_NE(nullptr, verifier_session);
  13342. EXPECT_EQ(session_verifier_session, verifier_session);
  13343. }
  13344. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13345. using httplib::tls::TlsError;
  13346. // Test that verify_error_to_string returns empty for success
  13347. std::string success_str = TlsError::verify_error_to_string(0);
  13348. EXPECT_TRUE(success_str.empty());
  13349. // Test that verify_error_to_string returns non-empty for error codes
  13350. // Using a common error code (certificate expired)
  13351. std::string error_str =
  13352. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13353. EXPECT_FALSE(error_str.empty());
  13354. }
  13355. TEST(SessionVerifierTest, CertificateAccepted) {
  13356. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13357. ASSERT_TRUE(svr.is_valid());
  13358. svr.Get("/test", [](const Request &, Response &res) {
  13359. res.set_content("ok", "text/plain");
  13360. });
  13361. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13362. auto se = detail::scope_exit([&] {
  13363. svr.stop();
  13364. t.join();
  13365. });
  13366. svr.wait_until_ready();
  13367. SSLClient cli(HOST, PORT);
  13368. cli.enable_server_certificate_verification(false);
  13369. cli.set_connection_timeout(30);
  13370. bool callback_called = false;
  13371. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13372. EXPECT_NE(session, nullptr);
  13373. callback_called = true;
  13374. return SSLVerifierResponse::CertificateAccepted;
  13375. });
  13376. auto res = cli.Get("/test");
  13377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13378. EXPECT_EQ(200, res->status);
  13379. EXPECT_TRUE(callback_called);
  13380. }
  13381. TEST(SessionVerifierTest, CertificateRejected) {
  13382. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13383. ASSERT_TRUE(svr.is_valid());
  13384. svr.Get("/test", [](const Request &, Response &res) {
  13385. res.set_content("ok", "text/plain");
  13386. });
  13387. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13388. auto se = detail::scope_exit([&] {
  13389. svr.stop();
  13390. t.join();
  13391. });
  13392. svr.wait_until_ready();
  13393. SSLClient cli(HOST, PORT);
  13394. cli.enable_server_certificate_verification(false);
  13395. cli.set_connection_timeout(30);
  13396. bool callback_called = false;
  13397. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13398. EXPECT_NE(session, nullptr);
  13399. callback_called = true;
  13400. return SSLVerifierResponse::CertificateRejected;
  13401. });
  13402. auto res = cli.Get("/test");
  13403. EXPECT_FALSE(res);
  13404. EXPECT_TRUE(callback_called);
  13405. }
  13406. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13407. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13408. ASSERT_TRUE(svr.is_valid());
  13409. svr.Get("/test", [](const Request &, Response &res) {
  13410. res.set_content("ok", "text/plain");
  13411. });
  13412. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13413. auto se = detail::scope_exit([&] {
  13414. svr.stop();
  13415. t.join();
  13416. });
  13417. svr.wait_until_ready();
  13418. // NoDecisionMade with verification disabled should succeed (no default check)
  13419. SSLClient cli(HOST, PORT);
  13420. cli.enable_server_certificate_verification(false);
  13421. cli.set_connection_timeout(30);
  13422. bool callback_called = false;
  13423. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13424. EXPECT_NE(session, nullptr);
  13425. callback_called = true;
  13426. return SSLVerifierResponse::NoDecisionMade;
  13427. });
  13428. auto res = cli.Get("/test");
  13429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13430. EXPECT_EQ(200, res->status);
  13431. EXPECT_TRUE(callback_called);
  13432. }
  13433. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13434. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13435. ASSERT_TRUE(svr.is_valid());
  13436. svr.Get("/test", [](const Request &, Response &res) {
  13437. res.set_content("ok", "text/plain");
  13438. });
  13439. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13440. auto se = detail::scope_exit([&] {
  13441. svr.stop();
  13442. t.join();
  13443. });
  13444. svr.wait_until_ready();
  13445. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13446. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13447. // so we only check that the request fails, not whether the callback was
  13448. // called.
  13449. SSLClient cli(HOST, PORT);
  13450. cli.enable_server_certificate_verification(true);
  13451. cli.set_connection_timeout(30);
  13452. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13453. EXPECT_NE(session, nullptr);
  13454. return SSLVerifierResponse::NoDecisionMade;
  13455. });
  13456. auto res = cli.Get("/test");
  13457. EXPECT_FALSE(res);
  13458. }
  13459. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13460. // Test SSL server using PemMemory constructor with client CA certificates
  13461. // Read PEM files
  13462. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13463. read_file(SERVER_CERT_FILE, server_cert_pem);
  13464. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13465. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13466. // Create SSLServer with PemMemory constructor including client CA
  13467. SSLServer::PemMemory server_pem = {
  13468. server_cert_pem.c_str(),
  13469. server_cert_pem.size(),
  13470. server_key_pem.c_str(),
  13471. server_key_pem.size(),
  13472. client_ca_pem.c_str(),
  13473. client_ca_pem.size(),
  13474. nullptr // no password for server key
  13475. };
  13476. SSLServer svr(server_pem);
  13477. ASSERT_TRUE(svr.is_valid());
  13478. // No SSL error should be recorded for valid setup
  13479. EXPECT_EQ(0, svr.ssl_last_error());
  13480. // Set up server endpoints
  13481. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13482. res.set_content("ok", "text/plain");
  13483. });
  13484. // Start server in a thread
  13485. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13486. svr.wait_until_ready();
  13487. // Connect with client certificate (using constructor with paths)
  13488. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13489. cli.enable_server_certificate_verification(false);
  13490. auto res = cli.Get("/test-pem-ca");
  13491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13492. EXPECT_EQ(200, res->status);
  13493. EXPECT_EQ("ok", res->body);
  13494. svr.stop();
  13495. server_thread.join();
  13496. }
  13497. #endif
  13498. #ifdef _WIN32
  13499. TEST(CleanupTest, WSACleanup) {
  13500. int ret = WSACleanup();
  13501. ASSERT_EQ(0, ret);
  13502. }
  13503. #endif
  13504. #ifndef CPPHTTPLIB_SSL_ENABLED
  13505. TEST(NoSSLSupport, SimpleInterface) {
  13506. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13507. }
  13508. #endif
  13509. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13510. TEST(InvalidScheme, SimpleInterface) {
  13511. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13512. }
  13513. #endif
  13514. TEST(NoScheme, SimpleInterface) {
  13515. Client cli("yahoo.com:80");
  13516. ASSERT_TRUE(cli.is_valid());
  13517. }
  13518. TEST(SendAPI, SimpleInterface_Online) {
  13519. Client cli("http://yahoo.com");
  13520. Request req;
  13521. req.method = "GET";
  13522. req.path = "/";
  13523. auto res = cli.send(req);
  13524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13525. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13526. }
  13527. TEST(SendAPI, WithParamsInRequest) {
  13528. Server svr;
  13529. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13530. EXPECT_TRUE(req.has_param("test"));
  13531. EXPECT_EQ("test_value", req.get_param_value("test"));
  13532. });
  13533. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13534. auto se = detail::scope_exit([&] {
  13535. svr.stop();
  13536. t.join();
  13537. ASSERT_FALSE(svr.is_running());
  13538. });
  13539. svr.wait_until_ready();
  13540. Client cli(HOST, PORT);
  13541. {
  13542. Request req;
  13543. req.method = "GET";
  13544. req.path = "/";
  13545. req.params.emplace("test", "test_value");
  13546. auto res = cli.send(req);
  13547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13548. }
  13549. {
  13550. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13552. }
  13553. }
  13554. TEST(ClientImplMethods, GetSocketTest) {
  13555. httplib::Server svr;
  13556. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13557. res.status = StatusCode::OK_200;
  13558. });
  13559. auto port = svr.bind_to_any_port("127.0.0.1");
  13560. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13561. auto se = detail::scope_exit([&] {
  13562. svr.stop();
  13563. thread.join();
  13564. ASSERT_FALSE(svr.is_running());
  13565. });
  13566. svr.wait_until_ready();
  13567. {
  13568. httplib::Client cli("127.0.0.1", port);
  13569. cli.set_keep_alive(true);
  13570. // Use the behavior of cpp-httplib of opening the connection
  13571. // only when the first request happens. If that changes,
  13572. // this test would be obsolete.
  13573. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13574. // This also implicitly tests the server. But other tests would fail much
  13575. // earlier than this one to be considered.
  13576. auto res = cli.Get("/");
  13577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13578. EXPECT_EQ(StatusCode::OK_200, res->status);
  13579. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13580. }
  13581. }
  13582. #ifdef CPPHTTPLIB_SSL_ENABLED
  13583. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13584. Client cli("http://yahoo.com");
  13585. auto res = cli.Get("/");
  13586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13587. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13588. cli.set_follow_location(true);
  13589. res = cli.Get("/");
  13590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13591. EXPECT_EQ(StatusCode::OK_200, res->status);
  13592. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13593. }
  13594. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13595. Client cli("https://yahoo.com");
  13596. auto res = cli.Get("/");
  13597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13598. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13599. cli.set_follow_location(true);
  13600. res = cli.Get("/");
  13601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13602. EXPECT_EQ(StatusCode::OK_200, res->status);
  13603. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13604. }
  13605. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13606. Client cli("https://yahoo.com");
  13607. auto res = cli.Get("/");
  13608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13609. ASSERT_FALSE(!res);
  13610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13611. ASSERT_FALSE(res == nullptr);
  13612. ASSERT_TRUE(res != nullptr);
  13613. EXPECT_EQ(Error::Success, res.error());
  13614. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13615. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13616. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13617. cli.set_follow_location(true);
  13618. res = cli.Get("/");
  13619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13620. EXPECT_EQ(Error::Success, res.error());
  13621. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13622. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13623. EXPECT_EQ(StatusCode::OK_200, res->status);
  13624. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13625. }
  13626. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13627. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13628. Client cli("https://cdnjs.cloudflare.com");
  13629. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13630. Headers{{"Accept-Encoding", "br"}});
  13631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13632. EXPECT_EQ(StatusCode::OK_200, res->status);
  13633. EXPECT_EQ(287630U, res->body.size());
  13634. EXPECT_EQ("application/javascript; charset=utf-8",
  13635. res->get_header_value("Content-Type"));
  13636. }
  13637. #endif
  13638. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13639. #undef REDIR_HOST // Silence compiler warning
  13640. #define REDIR_HOST "https://httpbingo.org"
  13641. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13642. Client cli(REDIR_HOST);
  13643. cli.set_follow_location(true);
  13644. auto res =
  13645. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13647. EXPECT_EQ(StatusCode::OK_200, res->status);
  13648. }
  13649. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13650. Client cli(REDIR_HOST);
  13651. cli.set_follow_location(true);
  13652. Params params;
  13653. params.emplace("url", "http://example.com");
  13654. params.emplace("status_code", "302");
  13655. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13657. EXPECT_EQ(StatusCode::OK_200, res->status);
  13658. }
  13659. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13660. Client cli(REDIR_HOST);
  13661. cli.set_follow_location(true);
  13662. Params params;
  13663. params.emplace("url", "http://example.com");
  13664. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13666. EXPECT_EQ(StatusCode::OK_200, res->status);
  13667. }
  13668. TEST(HttpToHttpsRedirectTest, CertFile) {
  13669. auto ssl_port = PORT + 1;
  13670. Server svr;
  13671. ASSERT_TRUE(svr.is_valid());
  13672. svr.Get("/index", [&](const Request &, Response &res) {
  13673. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13674. "/index");
  13675. svr.stop();
  13676. });
  13677. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13678. ASSERT_TRUE(ssl_svr.is_valid());
  13679. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13680. res.set_content("test", "text/plain");
  13681. ssl_svr.stop();
  13682. });
  13683. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13684. thread t2 =
  13685. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13686. auto se = detail::scope_exit([&] {
  13687. t2.join();
  13688. t.join();
  13689. ASSERT_FALSE(svr.is_running());
  13690. });
  13691. svr.wait_until_ready();
  13692. ssl_svr.wait_until_ready();
  13693. Client cli("127.0.0.1", PORT);
  13694. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13695. cli.enable_server_certificate_verification(true);
  13696. cli.set_follow_location(true);
  13697. cli.set_connection_timeout(30);
  13698. auto res = cli.Get("/index");
  13699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13700. ASSERT_EQ(StatusCode::OK_200, res->status);
  13701. }
  13702. TEST(SSLClientRedirectTest, CertFile) {
  13703. auto ssl_port = PORT + 1;
  13704. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13705. ASSERT_TRUE(ssl_svr1.is_valid());
  13706. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13707. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13708. "/index");
  13709. ssl_svr1.stop();
  13710. });
  13711. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13712. ASSERT_TRUE(ssl_svr2.is_valid());
  13713. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13714. res.set_content("test", "text/plain");
  13715. ssl_svr2.stop();
  13716. });
  13717. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13718. thread t2 =
  13719. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13720. auto se = detail::scope_exit([&] {
  13721. t2.join();
  13722. t.join();
  13723. ASSERT_FALSE(ssl_svr1.is_running());
  13724. });
  13725. ssl_svr1.wait_until_ready();
  13726. ssl_svr2.wait_until_ready();
  13727. SSLClient cli("127.0.0.1", PORT);
  13728. std::string cert;
  13729. read_file(SERVER_CERT2_FILE, cert);
  13730. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13731. cli.enable_server_certificate_verification(true);
  13732. cli.set_follow_location(true);
  13733. cli.set_connection_timeout(30);
  13734. auto res = cli.Get("/index");
  13735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13736. ASSERT_EQ(StatusCode::OK_200, res->status);
  13737. }
  13738. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  13739. // another port, so the client follows it with a new client.
  13740. static Result GetThroughTlsRedirectToDifferentPort(
  13741. const std::function<void(SSLClient &)> &setup,
  13742. const char *target_cert = SERVER_CERT2_FILE) {
  13743. auto ssl_port = PORT + 1;
  13744. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13745. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13746. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13747. "/index");
  13748. });
  13749. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  13750. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13751. res.set_content("test", "text/plain");
  13752. });
  13753. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  13754. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  13755. auto se = detail::scope_exit([&] {
  13756. ssl_svr2.stop();
  13757. ssl_svr1.stop();
  13758. t2.join();
  13759. t.join();
  13760. });
  13761. ssl_svr1.wait_until_ready();
  13762. ssl_svr2.wait_until_ready();
  13763. SSLClient cli("127.0.0.1", PORT);
  13764. cli.set_follow_location(true);
  13765. cli.set_connection_timeout(30);
  13766. setup(cli);
  13767. return cli.Get("/index");
  13768. }
  13769. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  13770. auto calls = 0;
  13771. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  13772. cli.enable_server_certificate_verification(false);
  13773. // Accept the first server only.
  13774. cli.set_session_verifier([&](tls::session_t) {
  13775. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  13776. : SSLVerifierResponse::CertificateRejected;
  13777. });
  13778. });
  13779. EXPECT_FALSE(res);
  13780. EXPECT_EQ(2, calls);
  13781. }
  13782. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  13783. std::string pinned;
  13784. auto res = GetThroughTlsRedirectToDifferentPort(
  13785. [&](SSLClient &cli) {
  13786. cli.enable_server_certificate_verification(false);
  13787. // Pin the first certificate seen.
  13788. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  13789. if (pinned.empty()) { pinned = ctx.serial(); }
  13790. return ctx.serial() == pinned;
  13791. });
  13792. },
  13793. // A certificate other than the first server's.
  13794. SERVER_CERT_FILE);
  13795. EXPECT_FALSE(res);
  13796. EXPECT_FALSE(pinned.empty());
  13797. }
  13798. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  13799. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  13800. std::string cert;
  13801. read_file(SERVER_CERT2_FILE, cert);
  13802. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13803. });
  13804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13805. EXPECT_EQ(StatusCode::OK_200, res->status);
  13806. }
  13807. #endif
  13808. #ifdef CPPHTTPLIB_SSL_ENABLED
  13809. // Test that set_ca_cert_store() skips system certs (consistent with
  13810. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13811. // should be trusted - system certs should NOT be loaded.
  13812. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13813. // Load a specific cert that is NOT a system CA cert
  13814. std::string cert;
  13815. read_file(SERVER_CERT2_FILE, cert);
  13816. SSLClient cli("google.com");
  13817. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13818. cli.enable_server_certificate_verification(true);
  13819. // This should FAIL because:
  13820. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13821. // 2. System certs should NOT be loaded when custom store is set
  13822. // If system certs WERE loaded, this would succeed
  13823. auto res = cli.Get("/");
  13824. ASSERT_FALSE(res);
  13825. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13826. }
  13827. // Same as above, but through the native store handle path. Regression test:
  13828. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13829. // merged system certs into the user-provided store.
  13830. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13831. std::string cert;
  13832. read_file(SERVER_CERT2_FILE, cert);
  13833. SSLClient cli("google.com");
  13834. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13835. cli.enable_server_certificate_verification(true);
  13836. auto res = cli.Get("/");
  13837. ASSERT_FALSE(res);
  13838. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13839. }
  13840. // A custom store set via the native handle must still verify a server whose
  13841. // cert it does contain.
  13842. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13843. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13844. ASSERT_TRUE(svr.is_valid());
  13845. svr.Get("/test", [&](const Request &, Response &res) {
  13846. res.set_content("test", "text/plain");
  13847. });
  13848. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13849. auto se = detail::scope_exit([&] {
  13850. svr.stop();
  13851. t.join();
  13852. ASSERT_FALSE(svr.is_running());
  13853. });
  13854. svr.wait_until_ready();
  13855. SSLClient cli("127.0.0.1", PORT);
  13856. std::string cert;
  13857. read_file(SERVER_CERT2_FILE, cert);
  13858. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13859. cli.enable_server_certificate_verification(true);
  13860. cli.set_connection_timeout(30);
  13861. auto res = cli.Get("/test");
  13862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13863. ASSERT_EQ(StatusCode::OK_200, res->status);
  13864. }
  13865. // CA certs loaded through the universal Client must be transferred to the
  13866. // client created internally for following an HTTPS redirect. Regression test:
  13867. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13868. // the CA data for redirect transfer.
  13869. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13870. auto ssl_port = PORT + 1;
  13871. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13872. ASSERT_TRUE(ssl_svr1.is_valid());
  13873. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13874. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13875. "/index");
  13876. });
  13877. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13878. ASSERT_TRUE(ssl_svr2.is_valid());
  13879. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13880. res.set_content("test", "text/plain");
  13881. });
  13882. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13883. thread t2 =
  13884. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13885. auto se = detail::scope_exit([&] {
  13886. ssl_svr2.stop();
  13887. ssl_svr1.stop();
  13888. t2.join();
  13889. t.join();
  13890. ASSERT_FALSE(ssl_svr1.is_running());
  13891. });
  13892. ssl_svr1.wait_until_ready();
  13893. ssl_svr2.wait_until_ready();
  13894. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13895. std::string cert;
  13896. read_file(SERVER_CERT2_FILE, cert);
  13897. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13898. cli.enable_server_certificate_verification(true);
  13899. cli.set_follow_location(true);
  13900. cli.set_connection_timeout(30);
  13901. auto res = cli.Get("/index");
  13902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13903. ASSERT_EQ(StatusCode::OK_200, res->status);
  13904. }
  13905. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13906. // so a host signed by a system CA verifies even though a custom CA is set
  13907. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13908. std::string cert;
  13909. read_file(SERVER_CERT2_FILE, cert);
  13910. SSLClient cli("google.com");
  13911. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13912. cli.enable_system_ca(true);
  13913. cli.enable_server_certificate_verification(true);
  13914. auto res = cli.Get("/");
  13915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13916. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13917. }
  13918. // The custom CA remains effective when combined with the system CA
  13919. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13920. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13921. ASSERT_TRUE(svr.is_valid());
  13922. svr.Get("/test", [&](const Request &, Response &res) {
  13923. res.set_content("test", "text/plain");
  13924. });
  13925. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13926. auto se = detail::scope_exit([&] {
  13927. svr.stop();
  13928. t.join();
  13929. ASSERT_FALSE(svr.is_running());
  13930. });
  13931. svr.wait_until_ready();
  13932. SSLClient cli("127.0.0.1", PORT);
  13933. std::string cert;
  13934. read_file(SERVER_CERT2_FILE, cert);
  13935. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13936. cli.enable_system_ca(true);
  13937. cli.enable_server_certificate_verification(true);
  13938. cli.set_connection_timeout(30);
  13939. auto res = cli.Get("/test");
  13940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13941. ASSERT_EQ(StatusCode::OK_200, res->status);
  13942. }
  13943. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13944. // skip chain verification entirely (only the certificate identity was
  13945. // checked), so a server presenting an untrusted certificate with a matching
  13946. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13947. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13948. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13949. ASSERT_TRUE(svr.is_valid());
  13950. svr.Get("/test", [&](const Request &, Response &res) {
  13951. res.set_content("test", "text/plain");
  13952. });
  13953. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13954. auto se = detail::scope_exit([&] {
  13955. svr.stop();
  13956. t.join();
  13957. ASSERT_FALSE(svr.is_running());
  13958. });
  13959. svr.wait_until_ready();
  13960. SSLClient cli("127.0.0.1", PORT);
  13961. std::string cert;
  13962. // A trusted CA that did not sign the server certificate. The server cert
  13963. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13964. // this connection.
  13965. read_file(CLIENT_CA_CERT_FILE, cert);
  13966. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13967. cli.enable_server_certificate_verification(true);
  13968. cli.set_connection_timeout(30);
  13969. auto res = cli.Get("/test");
  13970. ASSERT_FALSE(res);
  13971. }
  13972. // enable_system_ca(false) prevents system CA loading entirely
  13973. TEST(SSLClientTest, DisableSystemCa_Online) {
  13974. SSLClient cli("google.com");
  13975. cli.enable_system_ca(false);
  13976. cli.enable_server_certificate_verification(true);
  13977. auto res = cli.Get("/");
  13978. ASSERT_FALSE(res);
  13979. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13980. // itself when the CA chain is empty
  13981. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13982. res.error() == Error::SSLConnection);
  13983. }
  13984. // The universal Client forwards enable_system_ca()
  13985. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13986. std::string cert;
  13987. read_file(SERVER_CERT2_FILE, cert);
  13988. Client cli("https://google.com");
  13989. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13990. cli.enable_system_ca(true);
  13991. cli.enable_server_certificate_verification(true);
  13992. auto res = cli.Get("/");
  13993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13994. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13995. }
  13996. // The system CA policy must carry over to the client created internally for
  13997. // following a cross-host HTTPS redirect
  13998. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13999. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14000. ASSERT_TRUE(svr.is_valid());
  14001. svr.Get("/index", [&](const Request &, Response &res) {
  14002. res.set_redirect("https://www.google.com/");
  14003. });
  14004. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14005. auto se = detail::scope_exit([&] {
  14006. svr.stop();
  14007. t.join();
  14008. ASSERT_FALSE(svr.is_running());
  14009. });
  14010. svr.wait_until_ready();
  14011. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14012. std::string cert;
  14013. read_file(SERVER_CERT2_FILE, cert);
  14014. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14015. cli.enable_system_ca(true);
  14016. cli.enable_server_certificate_verification(true);
  14017. cli.set_follow_location(true);
  14018. cli.set_connection_timeout(30);
  14019. // Receiving any response proves the redirect client completed the TLS
  14020. // handshake with a system-CA-signed host
  14021. auto res = cli.Get("/index");
  14022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14023. }
  14024. TEST(MultipartFormDataTest, LargeData) {
  14025. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14026. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14027. const ContentReader &content_reader) {
  14028. if (req.is_multipart_form_data()) {
  14029. std::vector<FormData> items;
  14030. content_reader(
  14031. [&](const FormData &file) {
  14032. items.push_back(file);
  14033. return true;
  14034. },
  14035. [&](const char *data, size_t data_length) {
  14036. items.back().content.append(data, data_length);
  14037. return true;
  14038. });
  14039. EXPECT_TRUE(std::string(items[0].name) == "document");
  14040. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14041. EXPECT_TRUE(items[0].filename == "2MB_data");
  14042. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14043. EXPECT_TRUE(items[1].name == "hello");
  14044. EXPECT_TRUE(items[1].content == "world");
  14045. EXPECT_TRUE(items[1].filename == "");
  14046. EXPECT_TRUE(items[1].content_type == "");
  14047. } else {
  14048. std::string body;
  14049. content_reader([&](const char *data, size_t data_length) {
  14050. body.append(data, data_length);
  14051. return true;
  14052. });
  14053. }
  14054. });
  14055. auto port = svr.bind_to_any_port(HOST);
  14056. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14057. auto se = detail::scope_exit([&] {
  14058. svr.stop();
  14059. t.join();
  14060. ASSERT_FALSE(svr.is_running());
  14061. });
  14062. svr.wait_until_ready();
  14063. {
  14064. std::string data(1024 * 1024 * 2, '.');
  14065. std::stringstream buffer;
  14066. buffer << data;
  14067. SSLClient cli(HOST, port);
  14068. cli.enable_server_certificate_verification(false);
  14069. UploadFormDataItems items{
  14070. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14071. {"hello", "world", "", ""},
  14072. };
  14073. auto res = cli.Post("/post", items);
  14074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14075. ASSERT_EQ(StatusCode::OK_200, res->status);
  14076. }
  14077. }
  14078. TEST(MultipartFormDataTest, DataProviderItems) {
  14079. std::random_device seed_gen;
  14080. std::mt19937 random(seed_gen());
  14081. std::string rand1;
  14082. rand1.resize(1000);
  14083. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14084. std::string rand2;
  14085. rand2.resize(3000);
  14086. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14087. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14088. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14089. const ContentReader &content_reader) {
  14090. ASSERT_FALSE(req.is_multipart_form_data());
  14091. std::string body;
  14092. content_reader([&](const char *data, size_t data_length) {
  14093. body.append(data, data_length);
  14094. return true;
  14095. });
  14096. EXPECT_EQ(body, "");
  14097. });
  14098. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14099. const ContentReader &content_reader) {
  14100. ASSERT_TRUE(req.is_multipart_form_data());
  14101. std::vector<FormData> items;
  14102. content_reader(
  14103. [&](const FormData &file) {
  14104. items.push_back(file);
  14105. return true;
  14106. },
  14107. [&](const char *data, size_t data_length) {
  14108. items.back().content.append(data, data_length);
  14109. return true;
  14110. });
  14111. ASSERT_TRUE(items.size() == 2);
  14112. EXPECT_EQ(std::string(items[0].name), "name1");
  14113. EXPECT_EQ(items[0].content, "Testing123");
  14114. EXPECT_EQ(items[0].filename, "filename1");
  14115. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14116. EXPECT_EQ(items[1].name, "name2");
  14117. EXPECT_EQ(items[1].content, "Testing456");
  14118. EXPECT_EQ(items[1].filename, "");
  14119. EXPECT_EQ(items[1].content_type, "");
  14120. });
  14121. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14122. const ContentReader &content_reader) {
  14123. ASSERT_TRUE(req.is_multipart_form_data());
  14124. std::vector<FormData> items;
  14125. content_reader(
  14126. [&](const FormData &file) {
  14127. items.push_back(file);
  14128. return true;
  14129. },
  14130. [&](const char *data, size_t data_length) {
  14131. items.back().content.append(data, data_length);
  14132. return true;
  14133. });
  14134. ASSERT_TRUE(items.size() == 2);
  14135. EXPECT_EQ(items[0].name, "name3");
  14136. EXPECT_EQ(items[0].content, rand1);
  14137. EXPECT_EQ(items[0].filename, "filename3");
  14138. EXPECT_EQ(items[0].content_type, "");
  14139. EXPECT_EQ(items[1].name, "name4");
  14140. EXPECT_EQ(items[1].content, rand2);
  14141. EXPECT_EQ(items[1].filename, "filename4");
  14142. EXPECT_EQ(items[1].content_type, "");
  14143. });
  14144. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14145. const ContentReader &content_reader) {
  14146. ASSERT_TRUE(req.is_multipart_form_data());
  14147. std::vector<FormData> items;
  14148. content_reader(
  14149. [&](const FormData &file) {
  14150. items.push_back(file);
  14151. return true;
  14152. },
  14153. [&](const char *data, size_t data_length) {
  14154. items.back().content.append(data, data_length);
  14155. return true;
  14156. });
  14157. ASSERT_TRUE(items.size() == 4);
  14158. EXPECT_EQ(std::string(items[0].name), "name1");
  14159. EXPECT_EQ(items[0].content, "Testing123");
  14160. EXPECT_EQ(items[0].filename, "filename1");
  14161. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14162. EXPECT_EQ(items[1].name, "name2");
  14163. EXPECT_EQ(items[1].content, "Testing456");
  14164. EXPECT_EQ(items[1].filename, "");
  14165. EXPECT_EQ(items[1].content_type, "");
  14166. EXPECT_EQ(items[2].name, "name3");
  14167. EXPECT_EQ(items[2].content, rand1);
  14168. EXPECT_EQ(items[2].filename, "filename3");
  14169. EXPECT_EQ(items[2].content_type, "");
  14170. EXPECT_EQ(items[3].name, "name4");
  14171. EXPECT_EQ(items[3].content, rand2);
  14172. EXPECT_EQ(items[3].filename, "filename4");
  14173. EXPECT_EQ(items[3].content_type, "");
  14174. });
  14175. auto port = svr.bind_to_any_port("localhost");
  14176. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14177. auto se = detail::scope_exit([&] {
  14178. svr.stop();
  14179. t.join();
  14180. ASSERT_FALSE(svr.is_running());
  14181. });
  14182. svr.wait_until_ready();
  14183. {
  14184. SSLClient cli("localhost", port);
  14185. cli.enable_server_certificate_verification(false);
  14186. UploadFormDataItems items{
  14187. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14188. {"name2", "Testing456", "", ""}, // not a file
  14189. };
  14190. {
  14191. auto res = cli.Post("/post-none", {}, {}, {});
  14192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14193. ASSERT_EQ(StatusCode::OK_200, res->status);
  14194. }
  14195. FormDataProviderItems providers;
  14196. {
  14197. auto res =
  14198. cli.Post("/post-items", {}, items, providers); // empty providers
  14199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14200. ASSERT_EQ(StatusCode::OK_200, res->status);
  14201. }
  14202. providers.push_back({"name3",
  14203. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14204. // test the offset is given correctly at each step
  14205. if (!offset)
  14206. sink.os.write(rand1.data(), 30);
  14207. else if (offset == 30)
  14208. sink.os.write(rand1.data() + 30, 300);
  14209. else if (offset == 330)
  14210. sink.os.write(rand1.data() + 330, 670);
  14211. else if (offset == rand1.size())
  14212. sink.done();
  14213. return true;
  14214. },
  14215. "filename3",
  14216. {}});
  14217. providers.push_back({"name4",
  14218. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14219. // test the offset is given correctly at each step
  14220. if (!offset)
  14221. sink.os.write(rand2.data(), 2000);
  14222. else if (offset == 2000)
  14223. sink.os.write(rand2.data() + 2000, 1);
  14224. else if (offset == 2001)
  14225. sink.os.write(rand2.data() + 2001, 999);
  14226. else if (offset == rand2.size())
  14227. sink.done();
  14228. return true;
  14229. },
  14230. "filename4",
  14231. {}});
  14232. {
  14233. auto res = cli.Post("/post-providers", {}, {}, providers);
  14234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14235. ASSERT_EQ(StatusCode::OK_200, res->status);
  14236. }
  14237. {
  14238. auto res = cli.Post("/post-both", {}, items, providers);
  14239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14240. ASSERT_EQ(StatusCode::OK_200, res->status);
  14241. }
  14242. }
  14243. }
  14244. TEST(MultipartFormDataTest, BadHeader) {
  14245. Server svr;
  14246. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14247. res.set_content("ok", "text/plain");
  14248. });
  14249. thread t = thread([&] { svr.listen(HOST, PORT); });
  14250. auto se = detail::scope_exit([&] {
  14251. svr.stop();
  14252. t.join();
  14253. ASSERT_FALSE(svr.is_running());
  14254. });
  14255. svr.wait_until_ready();
  14256. const std::string body =
  14257. "This is the preamble. It is to be ignored, though it\r\n"
  14258. "is a handy place for composition agents to include an\r\n"
  14259. "explanatory note to non-MIME conformant readers.\r\n"
  14260. "\r\n"
  14261. "\r\n"
  14262. "--simple boundary\r\n"
  14263. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14264. ": BAD...\r\n"
  14265. "\r\n"
  14266. "value1\r\n"
  14267. "--simple boundary\r\n"
  14268. "Content-Disposition: form-data; name=\"field2\"; "
  14269. "filename=\"example.txt\"\r\n"
  14270. "\r\n"
  14271. "value2\r\n"
  14272. "--simple boundary--\r\n"
  14273. "This is the epilogue. It is also to be ignored.\r\n";
  14274. std::string content_type =
  14275. R"(multipart/form-data; boundary="simple boundary")";
  14276. Client cli(HOST, PORT);
  14277. auto res = cli.Post("/post", body, content_type.c_str());
  14278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14279. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14280. }
  14281. TEST(MultipartFormDataTest, WithPreamble) {
  14282. Server svr;
  14283. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14284. res.set_content("ok", "text/plain");
  14285. });
  14286. thread t = thread([&] { svr.listen(HOST, PORT); });
  14287. auto se = detail::scope_exit([&] {
  14288. svr.stop();
  14289. t.join();
  14290. ASSERT_FALSE(svr.is_running());
  14291. });
  14292. svr.wait_until_ready();
  14293. const std::string body =
  14294. "This is the preamble. It is to be ignored, though it\r\n"
  14295. "is a handy place for composition agents to include an\r\n"
  14296. "explanatory note to non-MIME conformant readers.\r\n"
  14297. "\r\n"
  14298. "\r\n"
  14299. "--simple boundary\r\n"
  14300. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14301. "\r\n"
  14302. "value1\r\n"
  14303. "--simple boundary\r\n"
  14304. "Content-Disposition: form-data; name=\"field2\"; "
  14305. "filename=\"example.txt\"\r\n"
  14306. "\r\n"
  14307. "value2\r\n"
  14308. "--simple boundary--\r\n"
  14309. "This is the epilogue. It is also to be ignored.\r\n";
  14310. std::string content_type =
  14311. R"(multipart/form-data; boundary="simple boundary")";
  14312. Client cli(HOST, PORT);
  14313. auto res = cli.Post("/post", body, content_type.c_str());
  14314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14315. EXPECT_EQ(StatusCode::OK_200, res->status);
  14316. }
  14317. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14318. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14319. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14320. const ContentReader &content_reader) {
  14321. if (req.is_multipart_form_data()) {
  14322. std::vector<FormData> items;
  14323. content_reader(
  14324. [&](const FormData &file) {
  14325. items.push_back(file);
  14326. return true;
  14327. },
  14328. [&](const char *data, size_t data_length) {
  14329. items.back().content.append(data, data_length);
  14330. return true;
  14331. });
  14332. EXPECT_TRUE(std::string(items[0].name) == "document");
  14333. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14334. EXPECT_TRUE(items[0].filename == "2MB_data");
  14335. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14336. EXPECT_TRUE(items[1].name == "hello");
  14337. EXPECT_TRUE(items[1].content == "world");
  14338. EXPECT_TRUE(items[1].filename == "");
  14339. EXPECT_TRUE(items[1].content_type == "");
  14340. } else {
  14341. std::string body;
  14342. content_reader([&](const char *data, size_t data_length) {
  14343. body.append(data, data_length);
  14344. return true;
  14345. });
  14346. }
  14347. });
  14348. auto port = svr.bind_to_any_port("localhost");
  14349. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14350. auto se = detail::scope_exit([&] {
  14351. svr.stop();
  14352. t.join();
  14353. ASSERT_FALSE(svr.is_running());
  14354. });
  14355. svr.wait_until_ready();
  14356. {
  14357. std::string data(1024 * 1024 * 2, '.');
  14358. std::stringstream buffer;
  14359. buffer << data;
  14360. SSLClient cli("localhost", port);
  14361. cli.enable_server_certificate_verification(false);
  14362. UploadFormDataItems items{
  14363. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14364. {"hello", "world", "", ""},
  14365. };
  14366. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14368. ASSERT_EQ(StatusCode::OK_200, res->status);
  14369. }
  14370. }
  14371. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14372. std::string data(1024 * 1024 * 2, '&');
  14373. std::stringstream buffer;
  14374. buffer << data;
  14375. Client cli("https://localhost:8080");
  14376. UploadFormDataItems items{
  14377. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14378. {"hello", "world", "", ""},
  14379. };
  14380. for (const char &c : " \t\r\n") {
  14381. auto res =
  14382. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14383. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14384. ASSERT_FALSE(res);
  14385. }
  14386. }
  14387. TEST(MultipartFormDataTest, PutFormData) {
  14388. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14389. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14390. const ContentReader &content_reader) {
  14391. if (req.is_multipart_form_data()) {
  14392. std::vector<FormData> items;
  14393. content_reader(
  14394. [&](const FormData &file) {
  14395. items.push_back(file);
  14396. return true;
  14397. },
  14398. [&](const char *data, size_t data_length) {
  14399. items.back().content.append(data, data_length);
  14400. return true;
  14401. });
  14402. EXPECT_TRUE(std::string(items[0].name) == "document");
  14403. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14404. EXPECT_TRUE(items[0].filename == "2MB_data");
  14405. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14406. EXPECT_TRUE(items[1].name == "hello");
  14407. EXPECT_TRUE(items[1].content == "world");
  14408. EXPECT_TRUE(items[1].filename == "");
  14409. EXPECT_TRUE(items[1].content_type == "");
  14410. } else {
  14411. std::string body;
  14412. content_reader([&](const char *data, size_t data_length) {
  14413. body.append(data, data_length);
  14414. return true;
  14415. });
  14416. }
  14417. });
  14418. auto port = svr.bind_to_any_port("localhost");
  14419. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14420. auto se = detail::scope_exit([&] {
  14421. svr.stop();
  14422. t.join();
  14423. ASSERT_FALSE(svr.is_running());
  14424. });
  14425. svr.wait_until_ready();
  14426. {
  14427. std::string data(1024 * 1024 * 2, '&');
  14428. std::stringstream buffer;
  14429. buffer << data;
  14430. SSLClient cli("localhost", port);
  14431. cli.enable_server_certificate_verification(false);
  14432. UploadFormDataItems items{
  14433. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14434. {"hello", "world", "", ""},
  14435. };
  14436. auto res = cli.Put("/put", items);
  14437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14438. ASSERT_EQ(StatusCode::OK_200, res->status);
  14439. }
  14440. }
  14441. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14443. svr.Put("/put_customboundary",
  14444. [&](const Request &req, const Response & /*res*/,
  14445. const ContentReader &content_reader) {
  14446. if (req.is_multipart_form_data()) {
  14447. std::vector<FormData> items;
  14448. content_reader(
  14449. [&](const FormData &file) {
  14450. items.push_back(file);
  14451. return true;
  14452. },
  14453. [&](const char *data, size_t data_length) {
  14454. items.back().content.append(data, data_length);
  14455. return true;
  14456. });
  14457. EXPECT_TRUE(std::string(items[0].name) == "document");
  14458. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14459. EXPECT_TRUE(items[0].filename == "2MB_data");
  14460. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14461. EXPECT_TRUE(items[1].name == "hello");
  14462. EXPECT_TRUE(items[1].content == "world");
  14463. EXPECT_TRUE(items[1].filename == "");
  14464. EXPECT_TRUE(items[1].content_type == "");
  14465. } else {
  14466. std::string body;
  14467. content_reader([&](const char *data, size_t data_length) {
  14468. body.append(data, data_length);
  14469. return true;
  14470. });
  14471. }
  14472. });
  14473. auto port = svr.bind_to_any_port("localhost");
  14474. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14475. auto se = detail::scope_exit([&] {
  14476. svr.stop();
  14477. t.join();
  14478. ASSERT_FALSE(svr.is_running());
  14479. });
  14480. svr.wait_until_ready();
  14481. {
  14482. std::string data(1024 * 1024 * 2, '&');
  14483. std::stringstream buffer;
  14484. buffer << data;
  14485. SSLClient cli("localhost", port);
  14486. cli.enable_server_certificate_verification(false);
  14487. UploadFormDataItems items{
  14488. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14489. {"hello", "world", "", ""},
  14490. };
  14491. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14493. ASSERT_EQ(StatusCode::OK_200, res->status);
  14494. }
  14495. }
  14496. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14497. std::string data(1024 * 1024 * 2, '&');
  14498. std::stringstream buffer;
  14499. buffer << data;
  14500. Client cli("https://localhost:8080");
  14501. cli.enable_server_certificate_verification(false);
  14502. UploadFormDataItems items{
  14503. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14504. {"hello", "world", "", ""},
  14505. };
  14506. for (const char &c : " \t\r\n") {
  14507. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14508. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14509. ASSERT_FALSE(res);
  14510. }
  14511. }
  14512. TEST(MultipartFormDataTest, AlternateFilename) {
  14513. auto handled = false;
  14514. Server svr;
  14515. svr.Post("/test", [&](const Request &req, Response &res) {
  14516. ASSERT_EQ(2u, req.form.files.size());
  14517. ASSERT_EQ(1u, req.form.fields.size());
  14518. // Test files
  14519. const auto &file1 = req.form.get_file("file1");
  14520. ASSERT_EQ("file1", file1.name);
  14521. ASSERT_EQ("A.txt", file1.filename);
  14522. ASSERT_EQ("text/plain", file1.content_type);
  14523. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14524. const auto &file2 = req.form.get_file("file2");
  14525. ASSERT_EQ("file2", file2.name);
  14526. ASSERT_EQ("a.html", file2.filename);
  14527. ASSERT_EQ("text/html", file2.content_type);
  14528. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14529. file2.content);
  14530. // Test text field
  14531. const auto &text = req.form.get_field("text");
  14532. ASSERT_EQ("text default", text);
  14533. res.set_content("ok", "text/plain");
  14534. handled = true;
  14535. });
  14536. thread t = thread([&] { svr.listen(HOST, PORT); });
  14537. auto se = detail::scope_exit([&] {
  14538. svr.stop();
  14539. t.join();
  14540. ASSERT_FALSE(svr.is_running());
  14541. ASSERT_TRUE(handled);
  14542. });
  14543. svr.wait_until_ready();
  14544. auto req = "POST /test HTTP/1.1\r\n"
  14545. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14546. "Content-Length: 399\r\n"
  14547. "\r\n"
  14548. "----------\r\n"
  14549. "Content-Disposition: form-data; name=\"text\"\r\n"
  14550. "\r\n"
  14551. "text default\r\n"
  14552. "----------\r\n"
  14553. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14554. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14555. "Content-Type: text/plain\r\n"
  14556. "\r\n"
  14557. "Content of a.txt.\r\n"
  14558. "\r\n"
  14559. "----------\r\n"
  14560. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14561. "\"a.html\"\r\n"
  14562. "Content-Type: text/html\r\n"
  14563. "\r\n"
  14564. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14565. "\r\n"
  14566. "------------\r\n";
  14567. ASSERT_TRUE(send_request(1, req));
  14568. }
  14569. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14570. auto handled = false;
  14571. Server svr;
  14572. svr.Post("/test", [&](const Request &req, Response &res) {
  14573. // Case-insensitive "utf-8''" prefix with a long value
  14574. const auto &file = req.form.get_file("file1");
  14575. ASSERT_EQ("file1", file.name);
  14576. // 8000 chars exercises both the Content-Disposition parser and the
  14577. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14578. // Prior to the fix, std::regex_match on this header would cause O(N)
  14579. // stack recursion in libstdc++, leading to SIGSEGV.
  14580. std::string expected_filename(8000, 'A');
  14581. ASSERT_EQ(expected_filename, file.filename);
  14582. res.set_content("ok", "text/plain");
  14583. handled = true;
  14584. });
  14585. thread t = thread([&] { svr.listen(HOST, PORT); });
  14586. auto se = detail::scope_exit([&] {
  14587. svr.stop();
  14588. t.join();
  14589. ASSERT_FALSE(svr.is_running());
  14590. ASSERT_TRUE(handled);
  14591. });
  14592. svr.wait_until_ready();
  14593. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14594. // Regression test for GHSA-qq6v-r583-3h69
  14595. std::string long_filename(8000, 'A');
  14596. std::string body = "----------\r\n"
  14597. "Content-Disposition: form-data; name=\"file1\"; "
  14598. "filename*=\"Utf-8''" +
  14599. long_filename +
  14600. "\"\r\n"
  14601. "\r\n"
  14602. "hello\r\n"
  14603. "------------\r\n";
  14604. auto req = "POST /test HTTP/1.1\r\n"
  14605. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14606. "Content-Length: " +
  14607. std::to_string(body.size()) + "\r\n\r\n" + body;
  14608. ASSERT_TRUE(send_request(1, req));
  14609. }
  14610. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14611. auto handled = false;
  14612. Server svr;
  14613. svr.Post("/test", [&](const Request &req, Response &) {
  14614. ASSERT_EQ(2u, req.form.fields.size());
  14615. const auto &text1 = req.form.get_field("text1");
  14616. ASSERT_EQ("text1", text1);
  14617. const auto &text2 = req.form.get_field("text2");
  14618. ASSERT_EQ("text2", text2);
  14619. handled = true;
  14620. });
  14621. thread t = thread([&] { svr.listen(HOST, PORT); });
  14622. auto se = detail::scope_exit([&] {
  14623. svr.stop();
  14624. t.join();
  14625. ASSERT_FALSE(svr.is_running());
  14626. ASSERT_TRUE(handled);
  14627. });
  14628. svr.wait_until_ready();
  14629. auto req = "POST /test HTTP/1.1\r\n"
  14630. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14631. "Content-Length: 146\r\n"
  14632. "\r\n----------\r\n"
  14633. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14634. "\r\n"
  14635. "text1"
  14636. "\r\n----------\r\n"
  14637. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14638. "\r\n"
  14639. "text2"
  14640. "\r\n------------";
  14641. std::string response;
  14642. ASSERT_TRUE(send_request(1, req, &response));
  14643. ASSERT_EQ("200", response.substr(9, 3));
  14644. }
  14645. TEST(MultipartFormDataTest, ContentLength) {
  14646. auto handled = false;
  14647. Server svr;
  14648. svr.Post("/test", [&](const Request &req, Response &) {
  14649. ASSERT_EQ(2u, req.form.fields.size());
  14650. const auto &text1 = req.form.get_field("text1");
  14651. ASSERT_EQ("text1", text1);
  14652. const auto &text2 = req.form.get_field("text2");
  14653. ASSERT_EQ("text2", text2);
  14654. handled = true;
  14655. });
  14656. thread t = thread([&] { svr.listen(HOST, PORT); });
  14657. auto se = detail::scope_exit([&] {
  14658. svr.stop();
  14659. t.join();
  14660. ASSERT_FALSE(svr.is_running());
  14661. ASSERT_TRUE(handled);
  14662. });
  14663. svr.wait_until_ready();
  14664. auto req = "POST /test HTTP/1.1\r\n"
  14665. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14666. "Content-Length: 167\r\n"
  14667. "\r\n----------\r\n"
  14668. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14669. "Content-Length: 5\r\n"
  14670. "\r\n"
  14671. "text1"
  14672. "\r\n----------\r\n"
  14673. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14674. "\r\n"
  14675. "text2"
  14676. "\r\n------------\r\n";
  14677. std::string response;
  14678. ASSERT_TRUE(send_request(1, req, &response));
  14679. ASSERT_EQ("200", response.substr(9, 3));
  14680. }
  14681. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14682. auto handled = false;
  14683. Server svr;
  14684. svr.Post("/test", [&](const Request &req, Response &) {
  14685. ASSERT_EQ(2u, req.form.fields.size());
  14686. const auto &text1 = req.form.get_field("text1");
  14687. ASSERT_EQ("text1", text1);
  14688. // TODO: Add header access for text fields if needed
  14689. const auto &text2 = req.form.get_field("text2");
  14690. ASSERT_EQ("text2", text2);
  14691. // TODO: Header access for text fields needs to be implemented
  14692. // auto &headers = it->second.headers;
  14693. // ASSERT_EQ(3U, headers.size());
  14694. // auto custom_header = headers.find("x-whatever");
  14695. // ASSERT_TRUE(custom_header != headers.end());
  14696. // ASSERT_NE("customvalue", custom_header->second);
  14697. // ASSERT_EQ("CustomValue", custom_header->second);
  14698. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14699. handled = true;
  14700. });
  14701. thread t = thread([&] { svr.listen(HOST, PORT); });
  14702. auto se = detail::scope_exit([&] {
  14703. svr.stop();
  14704. t.join();
  14705. ASSERT_FALSE(svr.is_running());
  14706. ASSERT_TRUE(handled);
  14707. });
  14708. svr.wait_until_ready();
  14709. auto req = "POST /test HTTP/1.1\r\n"
  14710. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14711. "Content-Length: 232\r\n"
  14712. "\r\n----------\r\n"
  14713. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14714. "Content-Length: 5\r\n"
  14715. "X-Test: 1\r\n"
  14716. "\r\n"
  14717. "text1"
  14718. "\r\n----------\r\n"
  14719. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14720. "Content-Type: text/plain\r\n"
  14721. "X-Whatever: CustomValue\r\n"
  14722. "\r\n"
  14723. "text2"
  14724. "\r\n------------\r\n"
  14725. "That should be disregarded. Not even read";
  14726. std::string response;
  14727. ASSERT_TRUE(send_request(1, req, &response));
  14728. ASSERT_EQ("200", response.substr(9, 3));
  14729. }
  14730. TEST(MultipartFormDataTest, LargeHeader) {
  14731. auto handled = false;
  14732. Server svr;
  14733. svr.Post("/test", [&](const Request &req, Response &) {
  14734. ASSERT_EQ(1u, req.form.fields.size());
  14735. const auto &text = req.form.get_field("name1");
  14736. ASSERT_EQ("text1", text);
  14737. handled = true;
  14738. });
  14739. thread t = thread([&] { svr.listen(HOST, PORT); });
  14740. auto se = detail::scope_exit([&] {
  14741. svr.stop();
  14742. t.join();
  14743. ASSERT_FALSE(svr.is_running());
  14744. ASSERT_TRUE(handled);
  14745. });
  14746. svr.wait_until_ready();
  14747. auto boundary = std::string("cpp-httplib-multipart-data");
  14748. std::string content = "--" + boundary +
  14749. "\r\n"
  14750. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14751. "\r\n"
  14752. "text1\r\n"
  14753. "--" +
  14754. boundary + "--\r\n";
  14755. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14756. "Content-Type: multipart/form-data;boundary=" +
  14757. boundary +
  14758. "\r\n"
  14759. "Content-Length: " +
  14760. std::to_string(content.size()) +
  14761. "\r\n"
  14762. "Dummy-Header: ";
  14763. std::string header_suffix = "\r\n"
  14764. "\r\n";
  14765. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14766. size_t header_dummy_size =
  14767. read_buff_size -
  14768. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14769. auto header_dummy = std::string(header_dummy_size, '@');
  14770. auto req = header_prefix + header_dummy + header_suffix + content;
  14771. std::string response;
  14772. ASSERT_TRUE(send_request(1, req, &response));
  14773. ASSERT_EQ("200", response.substr(9, 3));
  14774. }
  14775. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14776. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14777. // (not chunked Transfer-Encoding) after the streaming refactor.
  14778. auto handled = false;
  14779. Server svr;
  14780. svr.Post("/upload", [&](const Request &req, Response &res) {
  14781. auto cl_it = req.headers.find("Content-Length");
  14782. EXPECT_TRUE(cl_it != req.headers.end());
  14783. auto te_it = req.headers.find("Transfer-Encoding");
  14784. EXPECT_TRUE(te_it == req.headers.end());
  14785. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14786. res.set_content("ok", "text/plain");
  14787. handled = true;
  14788. });
  14789. auto port = svr.bind_to_any_port(HOST);
  14790. auto t = thread([&] { svr.listen_after_bind(); });
  14791. auto se = detail::scope_exit([&] {
  14792. svr.stop();
  14793. t.join();
  14794. ASSERT_FALSE(svr.is_running());
  14795. ASSERT_TRUE(handled);
  14796. });
  14797. svr.wait_until_ready();
  14798. UploadFormDataItems items = {
  14799. {"field1", "hello", "", "text/plain"},
  14800. {"file1", "world", "test.txt", "application/octet-stream"},
  14801. };
  14802. Client cli(HOST, port);
  14803. auto res = cli.Post("/upload", {}, items);
  14804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14805. EXPECT_EQ(StatusCode::OK_200, res->status);
  14806. }
  14807. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14808. // Verify that make_multipart_content_provider coalesces many small segments
  14809. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14810. constexpr size_t kItemCount = 1000;
  14811. UploadFormDataItems items;
  14812. items.reserve(kItemCount);
  14813. for (size_t i = 0; i < kItemCount; i++) {
  14814. items.push_back(
  14815. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14816. }
  14817. const std::string boundary = "----test-boundary";
  14818. auto content_length = detail::get_multipart_content_length(items, boundary);
  14819. auto provider = detail::make_multipart_content_provider(items, boundary);
  14820. // Drive the provider the same way write_content_with_progress does
  14821. size_t write_count = 0;
  14822. size_t total_bytes = 0;
  14823. DataSink sink;
  14824. size_t offset = 0;
  14825. sink.write = [&](const char *d, size_t l) -> bool {
  14826. (void)d;
  14827. write_count++;
  14828. total_bytes += l;
  14829. offset += l;
  14830. return true;
  14831. };
  14832. sink.is_writable = []() -> bool { return true; };
  14833. while (offset < content_length) {
  14834. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14835. }
  14836. EXPECT_EQ(content_length, total_bytes);
  14837. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14838. // With buffering into 64KB blocks, write_count should be much smaller.
  14839. auto segment_count = 3 * kItemCount + 1;
  14840. EXPECT_LT(write_count, segment_count / 10);
  14841. }
  14842. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14843. // Integration test: send many UploadFormDataItems and verify the server
  14844. // receives all of them correctly (#2410).
  14845. constexpr size_t kItemCount = 500;
  14846. auto handled = false;
  14847. Server svr;
  14848. svr.Post("/upload", [&](const Request &req, Response &res) {
  14849. EXPECT_EQ(kItemCount, req.form.fields.size());
  14850. for (size_t i = 0; i < kItemCount; i++) {
  14851. auto key = "field" + std::to_string(i);
  14852. auto val = "value" + std::to_string(i);
  14853. auto it = req.form.fields.find(key);
  14854. if (it != req.form.fields.end()) {
  14855. EXPECT_EQ(val, it->second.content);
  14856. } else {
  14857. ADD_FAILURE() << "Missing field: " << key;
  14858. }
  14859. }
  14860. res.set_content("ok", "text/plain");
  14861. handled = true;
  14862. });
  14863. auto port = svr.bind_to_any_port(HOST);
  14864. auto t = thread([&] { svr.listen_after_bind(); });
  14865. auto se = detail::scope_exit([&] {
  14866. svr.stop();
  14867. t.join();
  14868. ASSERT_FALSE(svr.is_running());
  14869. ASSERT_TRUE(handled);
  14870. });
  14871. svr.wait_until_ready();
  14872. UploadFormDataItems items;
  14873. items.reserve(kItemCount);
  14874. for (size_t i = 0; i < kItemCount; i++) {
  14875. items.push_back(
  14876. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14877. }
  14878. Client cli(HOST, port);
  14879. auto res = cli.Post("/upload", items);
  14880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14881. EXPECT_EQ(StatusCode::OK_200, res->status);
  14882. }
  14883. TEST(MultipartFormDataTest, MakeFileProvider) {
  14884. // Verify make_file_provider sends a file's contents correctly.
  14885. const std::string file_content(4096, 'Z');
  14886. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14887. {
  14888. std::ofstream ofs(tmp_path, std::ios::binary);
  14889. ofs.write(file_content.data(),
  14890. static_cast<std::streamsize>(file_content.size()));
  14891. }
  14892. auto handled = false;
  14893. Server svr;
  14894. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14895. const ContentReader &content_reader) {
  14896. ASSERT_TRUE(req.is_multipart_form_data());
  14897. std::vector<FormData> items;
  14898. content_reader(
  14899. [&](const FormData &file) {
  14900. items.push_back(file);
  14901. return true;
  14902. },
  14903. [&](const char *data, size_t data_length) {
  14904. items.back().content.append(data, data_length);
  14905. return true;
  14906. });
  14907. ASSERT_EQ(1u, items.size());
  14908. EXPECT_EQ("myfile", items[0].name);
  14909. EXPECT_EQ("data.bin", items[0].filename);
  14910. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14911. EXPECT_EQ(file_content, items[0].content);
  14912. handled = true;
  14913. });
  14914. auto port = svr.bind_to_any_port(HOST);
  14915. auto t = thread([&] { svr.listen_after_bind(); });
  14916. auto se = detail::scope_exit([&] {
  14917. svr.stop();
  14918. t.join();
  14919. ASSERT_FALSE(svr.is_running());
  14920. ASSERT_TRUE(handled);
  14921. std::remove(tmp_path.c_str());
  14922. });
  14923. svr.wait_until_ready();
  14924. FormDataProviderItems providers;
  14925. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14926. "application/octet-stream"));
  14927. Client cli(HOST, port);
  14928. auto res = cli.Post("/upload", {}, {}, providers);
  14929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14930. EXPECT_EQ(StatusCode::OK_200, res->status);
  14931. }
  14932. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14933. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14934. // (100) headers is rejected with a 400 Bad Request response.
  14935. Server svr;
  14936. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14937. res.set_content("ok", "text/plain");
  14938. });
  14939. thread t = thread([&] { svr.listen(HOST, PORT); });
  14940. auto se = detail::scope_exit([&] {
  14941. svr.stop();
  14942. t.join();
  14943. ASSERT_FALSE(svr.is_running());
  14944. });
  14945. svr.wait_until_ready();
  14946. // Build a multipart part with 101 custom headers (exceeding
  14947. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14948. std::stringstream body;
  14949. body << "--simpleboundary\r\n"
  14950. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14951. for (int i = 0; i < 101; i++) {
  14952. body << "X-Custom-Header-" << i << ": value\r\n";
  14953. }
  14954. body << "\r\n"
  14955. << "value1\r\n"
  14956. << "--simpleboundary--\r\n";
  14957. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14958. Client cli(HOST, PORT);
  14959. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14961. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14962. }
  14963. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14964. // A body that never contains the declared boundary must not be accumulated
  14965. // while the parser waits for it. Buffering it would also make every read
  14966. // rescan everything seen so far, which is quadratic in the body size.
  14967. Server svr;
  14968. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14969. res.set_content("ok", "text/plain");
  14970. });
  14971. auto port = svr.bind_to_any_port(HOST);
  14972. thread t = thread([&] { svr.listen_after_bind(); });
  14973. auto se = detail::scope_exit([&] {
  14974. svr.stop();
  14975. t.join();
  14976. ASSERT_FALSE(svr.is_running());
  14977. });
  14978. svr.wait_until_ready();
  14979. Client cli(HOST, port);
  14980. cli.set_read_timeout(60, 0);
  14981. cli.set_write_timeout(60, 0);
  14982. // '-' is the worst case: it matches the first character of the boundary, so
  14983. // every position has to be checked against it.
  14984. auto post_dashes = [&](size_t size) {
  14985. const std::string body(size, '-');
  14986. auto start = std::chrono::steady_clock::now();
  14987. auto res =
  14988. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14989. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14990. std::chrono::steady_clock::now() - start)
  14991. .count();
  14992. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14993. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14994. return ms;
  14995. };
  14996. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14997. // Windows.
  14998. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14999. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15000. // Comparing the two sizes rather than checking an absolute duration keeps
  15001. // this meaningful across build types and CI load, both of which move the
  15002. // absolute numbers by more than an order of magnitude. Four times the bytes
  15003. // costs about four times the time when parsing is linear, and about sixteen
  15004. // times when the body is buffered and rescanned.
  15005. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15006. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15007. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15008. << "ms, which suggests the body is being buffered and rescanned";
  15009. }
  15010. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15011. // A boundary can only be followed by CRLF or by "--", so anything else is
  15012. // malformed no matter what comes next. The parser must say so right away
  15013. // instead of buffering the rest of the declared body.
  15014. Server svr;
  15015. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15016. res.set_content("ok", "text/plain");
  15017. });
  15018. auto port = svr.bind_to_any_port(HOST);
  15019. thread t = thread([&] { svr.listen_after_bind(); });
  15020. auto se = detail::scope_exit([&] {
  15021. svr.stop();
  15022. t.join();
  15023. ASSERT_FALSE(svr.is_running());
  15024. });
  15025. svr.wait_until_ready();
  15026. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15027. // buffers instead of failing would still be waiting for the remaining bytes.
  15028. const std::string body = "--zzzz\r\n"
  15029. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15030. "\r\n"
  15031. "text1"
  15032. "\r\n--zzzzXX";
  15033. const std::string req = "POST /post HTTP/1.1\r\n"
  15034. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15035. "Content-Length: 1048576\r\n"
  15036. "\r\n" +
  15037. body;
  15038. std::string response;
  15039. ASSERT_TRUE(send_request(3, req, &response, port));
  15040. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15041. EXPECT_EQ("400", response.substr(9, 3));
  15042. }
  15043. // Posts a multipart body split into two writes, so that the server sees the
  15044. // split at whatever offset the caller chose, and expects the single "text1"
  15045. // field to come through.
  15046. static void expect_split_multipart_ok(const std::string &body1,
  15047. const std::string &body2) {
  15048. auto handled = false;
  15049. Server svr;
  15050. svr.Post("/post", [&](const Request &req, Response &) {
  15051. EXPECT_EQ(1u, req.form.fields.size());
  15052. EXPECT_EQ("text1", req.form.get_field("text1"));
  15053. handled = true;
  15054. });
  15055. auto port = svr.bind_to_any_port(HOST);
  15056. thread t = thread([&] { svr.listen_after_bind(); });
  15057. auto se = detail::scope_exit([&] {
  15058. svr.stop();
  15059. t.join();
  15060. ASSERT_FALSE(svr.is_running());
  15061. ASSERT_TRUE(handled);
  15062. });
  15063. svr.wait_until_ready();
  15064. // "Connection: close" makes the server close once it has answered, so the
  15065. // response drain ends immediately instead of idling until the read timeout.
  15066. const std::string head =
  15067. "POST /post HTTP/1.1\r\n"
  15068. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15069. "Connection: close\r\n"
  15070. "Content-Length: " +
  15071. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15072. std::string response;
  15073. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15074. ASSERT_GE(response.size(), 12u) << "no response";
  15075. EXPECT_EQ("200", response.substr(9, 3));
  15076. }
  15077. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15078. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15079. // ignored, including when it does not arrive in the same read as the
  15080. // close-delimiter itself.
  15081. expect_split_multipart_ok("--zzzz\r\n"
  15082. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15083. "\r\n"
  15084. "text1"
  15085. "\r\n--zzzz--",
  15086. "\r\nthis epilogue must be ignored\r\n");
  15087. }
  15088. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15089. // The initial boundary may be preceded by a preamble of any length and may
  15090. // straddle a read boundary. Discarding data while waiting for it must not
  15091. // throw away a partial boundary sitting at the end of the buffer.
  15092. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15093. "zz\r\n"
  15094. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15095. "\r\n"
  15096. "text1"
  15097. "\r\n--zzzz--\r\n");
  15098. }
  15099. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15100. // The received boundary was only checked for being non-empty, so it could be
  15101. // as long as a header is allowed to be. The parser scans the body for
  15102. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15103. // costs a nearly full comparison at nearly every position, making the
  15104. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15105. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15106. Server svr;
  15107. svr.Post("/post", [](const Request &req, Response &res) {
  15108. EXPECT_EQ(1u, req.form.fields.size());
  15109. EXPECT_EQ("text1", req.form.get_field("text1"));
  15110. res.set_content("ok", "text/plain");
  15111. });
  15112. auto port = svr.bind_to_any_port(HOST);
  15113. thread t = thread([&] { svr.listen_after_bind(); });
  15114. auto se = detail::scope_exit([&] {
  15115. svr.stop();
  15116. t.join();
  15117. ASSERT_FALSE(svr.is_running());
  15118. });
  15119. svr.wait_until_ready();
  15120. Client cli(HOST, port);
  15121. auto post_with_boundary_of_length = [&](size_t len) {
  15122. const std::string boundary(len, 'a');
  15123. const std::string body =
  15124. "--" + boundary +
  15125. "\r\n"
  15126. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15127. "\r\n"
  15128. "text1"
  15129. "\r\n--" +
  15130. boundary + "--\r\n";
  15131. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15132. };
  15133. auto res = post_with_boundary_of_length(70);
  15134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15135. EXPECT_EQ(StatusCode::OK_200, res->status);
  15136. res = post_with_boundary_of_length(71);
  15137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15138. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15139. }
  15140. TEST(MakeFileBodyTest, Basic) {
  15141. const std::string file_content(4096, 'Z');
  15142. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15143. {
  15144. std::ofstream ofs(tmp_path, std::ios::binary);
  15145. ofs.write(file_content.data(),
  15146. static_cast<std::streamsize>(file_content.size()));
  15147. }
  15148. auto handled = false;
  15149. Server svr;
  15150. svr.Post("/upload", [&](const Request &req, Response &res) {
  15151. EXPECT_EQ(file_content, req.body);
  15152. handled = true;
  15153. res.status = StatusCode::OK_200;
  15154. });
  15155. auto port = svr.bind_to_any_port(HOST);
  15156. auto t = thread([&] { svr.listen_after_bind(); });
  15157. auto se = detail::scope_exit([&] {
  15158. svr.stop();
  15159. t.join();
  15160. ASSERT_FALSE(svr.is_running());
  15161. ASSERT_TRUE(handled);
  15162. std::remove(tmp_path.c_str());
  15163. });
  15164. svr.wait_until_ready();
  15165. auto fb = make_file_body(tmp_path);
  15166. ASSERT_GT(fb.first, 0u);
  15167. Client cli(HOST, port);
  15168. auto res =
  15169. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15171. EXPECT_EQ(StatusCode::OK_200, res->status);
  15172. }
  15173. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15174. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15175. {
  15176. std::ofstream ofs(path, std::ios::binary);
  15177. const std::string content(100, 'A');
  15178. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15179. }
  15180. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15181. auto body = make_file_body(path);
  15182. ASSERT_EQ(100u, body.first);
  15183. ASSERT_TRUE(static_cast<bool>(body.second));
  15184. // Rewritten shorter after its length was measured - and, on a server, after
  15185. // that length has already gone out as Content-Length.
  15186. {
  15187. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15188. const std::string content(10, 'A');
  15189. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15190. }
  15191. std::string written;
  15192. DataSink sink;
  15193. sink.write = [&](const char *d, size_t l) {
  15194. written.append(d, l);
  15195. return true;
  15196. };
  15197. // The provider has to report failure. write_content_with_progress() advances
  15198. // its offset only by what was written, so a provider that returns true
  15199. // without completing the length it promised is called again straight away,
  15200. // and again.
  15201. EXPECT_FALSE(body.second(0, body.first, sink));
  15202. EXPECT_EQ(std::string(10, 'A'), written);
  15203. }
  15204. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15205. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15206. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15207. {
  15208. std::ofstream ofs(path, std::ios::binary);
  15209. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15210. }
  15211. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15212. auto body = make_file_body(path);
  15213. ASSERT_EQ(content.size(), body.first);
  15214. ASSERT_TRUE(static_cast<bool>(body.second));
  15215. std::string written;
  15216. DataSink sink;
  15217. sink.write = [&](const char *d, size_t l) {
  15218. written.append(d, l);
  15219. return true;
  15220. };
  15221. EXPECT_TRUE(body.second(0, body.first, sink));
  15222. EXPECT_EQ(content, written);
  15223. }
  15224. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15225. static constexpr unsigned int number_of_tasks{1000000};
  15226. std::atomic_uint count{0};
  15227. std::unique_ptr<TaskQueue> task_queue{
  15228. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15229. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15230. auto queued = task_queue->enqueue(
  15231. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15232. EXPECT_TRUE(queued);
  15233. }
  15234. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15235. task_queue->shutdown();
  15236. #else
  15237. EXPECT_NO_THROW(task_queue->shutdown());
  15238. #endif
  15239. EXPECT_EQ(number_of_tasks, count.load());
  15240. }
  15241. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15242. static constexpr unsigned int number_of_tasks{1000000};
  15243. static constexpr unsigned int qlimit{2};
  15244. unsigned int queued_count{0};
  15245. std::atomic_uint count{0};
  15246. std::unique_ptr<TaskQueue> task_queue{
  15247. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15248. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15249. if (task_queue->enqueue(
  15250. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15251. queued_count++;
  15252. }
  15253. }
  15254. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15255. task_queue->shutdown();
  15256. #else
  15257. EXPECT_NO_THROW(task_queue->shutdown());
  15258. #endif
  15259. EXPECT_EQ(queued_count, count.load());
  15260. EXPECT_TRUE(queued_count <= number_of_tasks);
  15261. EXPECT_TRUE(queued_count >= qlimit);
  15262. }
  15263. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15264. // Use a short idle timeout so a dynamic thread spawns, times out and
  15265. // exits during the test, and the pool keeps working afterwards.
  15266. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15267. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15268. /*idle_timeout_sec=*/1}};
  15269. std::atomic_uint count{0};
  15270. std::condition_variable cv;
  15271. std::mutex mtx;
  15272. bool release = false;
  15273. // Block the base thread so the second task spawns a dynamic thread.
  15274. EXPECT_TRUE(task_queue->enqueue([&] {
  15275. std::unique_lock<std::mutex> lock(mtx);
  15276. while (!release) {
  15277. cv.wait(lock);
  15278. }
  15279. count++;
  15280. }));
  15281. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15282. // Let the dynamic thread finish its task and exceed the idle timeout.
  15283. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15284. {
  15285. std::unique_lock<std::mutex> lock(mtx);
  15286. release = true;
  15287. }
  15288. cv.notify_all();
  15289. // The pool must still accept and run tasks after the dynamic thread exited.
  15290. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15291. task_queue->shutdown();
  15292. EXPECT_EQ(3u, count.load());
  15293. }
  15294. TEST(TaskQueueTest, MaxQueuedRequests) {
  15295. static constexpr unsigned int qlimit{3};
  15296. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15297. std::condition_variable sem_cv;
  15298. std::mutex sem_mtx;
  15299. int credits = 0;
  15300. bool queued;
  15301. /* Fill up the queue with tasks that will block until we give them credits to
  15302. * complete. */
  15303. for (unsigned int n = 0; n <= qlimit;) {
  15304. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15305. std::unique_lock<std::mutex> lock(sem_mtx);
  15306. while (credits <= 0) {
  15307. sem_cv.wait(lock);
  15308. }
  15309. /* Consume the credit and signal the test code if they are all gone. */
  15310. if (--credits == 0) { sem_cv.notify_one(); }
  15311. });
  15312. if (n < qlimit) {
  15313. /* The first qlimit enqueues must succeed. */
  15314. EXPECT_TRUE(queued);
  15315. } else {
  15316. /* The last one will succeed only when the worker thread
  15317. * starts and dequeues the first blocking task. Although
  15318. * not necessary for the correctness of this test, we sleep for
  15319. * a short while to avoid busy waiting. */
  15320. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15321. }
  15322. if (queued) { n++; }
  15323. }
  15324. /* Further enqueues must fail since the queue is full. */
  15325. for (auto i = 0; i < 4; i++) {
  15326. queued = task_queue->enqueue([] {});
  15327. EXPECT_FALSE(queued);
  15328. }
  15329. /* Give the credits to allow the previous tasks to complete. */
  15330. {
  15331. std::unique_lock<std::mutex> lock(sem_mtx);
  15332. credits += qlimit + 1;
  15333. }
  15334. sem_cv.notify_all();
  15335. /* Wait for all the credits to be consumed. */
  15336. {
  15337. std::unique_lock<std::mutex> lock(sem_mtx);
  15338. while (credits > 0) {
  15339. sem_cv.wait(lock);
  15340. }
  15341. }
  15342. /* Check that we are able again to enqueue at least qlimit tasks. */
  15343. for (unsigned int i = 0; i < qlimit; i++) {
  15344. queued = task_queue->enqueue([] {});
  15345. EXPECT_TRUE(queued);
  15346. }
  15347. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15348. task_queue->shutdown();
  15349. #else
  15350. EXPECT_NO_THROW(task_queue->shutdown());
  15351. #endif
  15352. }
  15353. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15354. Server svr;
  15355. std::string method;
  15356. std::string body;
  15357. auto has_content_length = false;
  15358. auto has_transfer_encoding = false;
  15359. std::atomic<int> bad_requests{0};
  15360. // Leftover body bytes get parsed as a malformed request and answered with
  15361. // 400
  15362. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15363. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15364. });
  15365. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15366. res.set_redirect("/down", StatusCode::SeeOther_303);
  15367. });
  15368. svr.Get("/down", [&](const Request &req, Response &res) {
  15369. method = req.method;
  15370. body = req.body;
  15371. has_content_length = req.has_header("Content-Length");
  15372. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15373. res.set_content("ok", "text/plain");
  15374. });
  15375. auto port = svr.bind_to_any_port(HOST);
  15376. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15377. auto se = detail::scope_exit([&] {
  15378. svr.stop();
  15379. thread.join();
  15380. ASSERT_FALSE(svr.is_running());
  15381. });
  15382. svr.wait_until_ready();
  15383. const std::string payload = "SECRET-BODY";
  15384. auto check = [&](Client &cli, const Result &res) {
  15385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15386. EXPECT_EQ(StatusCode::OK_200, res->status);
  15387. EXPECT_EQ("ok", res->body);
  15388. EXPECT_EQ("GET", method);
  15389. EXPECT_TRUE(body.empty());
  15390. EXPECT_FALSE(has_content_length);
  15391. EXPECT_FALSE(has_transfer_encoding);
  15392. // Nothing of the original body may be left on the connection
  15393. auto res2 = cli.Get("/down");
  15394. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15395. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15396. EXPECT_EQ("ok", res2->body);
  15397. EXPECT_EQ(0, bad_requests);
  15398. };
  15399. // With content length
  15400. {
  15401. Client cli(HOST, port);
  15402. cli.set_keep_alive(true);
  15403. cli.set_follow_location(true);
  15404. auto res = cli.Post(
  15405. "/up", payload.size(),
  15406. [&](size_t offset, size_t length, DataSink &sink) {
  15407. return sink.write(payload.data() + offset, length);
  15408. },
  15409. "text/plain");
  15410. check(cli, res);
  15411. }
  15412. // Without content length (chunked)
  15413. {
  15414. Client cli(HOST, port);
  15415. cli.set_keep_alive(true);
  15416. cli.set_follow_location(true);
  15417. auto res = cli.Post(
  15418. "/up",
  15419. [&](size_t /*offset*/, DataSink &sink) {
  15420. sink.write(payload.data(), payload.size());
  15421. sink.done();
  15422. return true;
  15423. },
  15424. "text/plain");
  15425. check(cli, res);
  15426. }
  15427. }
  15428. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15429. Server svr;
  15430. std::string target;
  15431. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15432. // Echo the still-encoded name back in the Location
  15433. const std::string prefix = "/start/";
  15434. res.status = StatusCode::Found_302;
  15435. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15436. });
  15437. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15438. target = req.target;
  15439. res.set_content("ok", "text/plain");
  15440. });
  15441. auto port = svr.bind_to_any_port(HOST);
  15442. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15443. auto se = detail::scope_exit([&] {
  15444. svr.stop();
  15445. thread.join();
  15446. ASSERT_FALSE(svr.is_running());
  15447. });
  15448. svr.wait_until_ready();
  15449. // Decoding the Location path would turn the first four into a path
  15450. // separator, a query delimiter, a fragment delimiter and a different
  15451. // percent-encoded octet. The rest must keep reaching the server as they are.
  15452. const std::vector<std::string> names = {
  15453. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15454. };
  15455. for (auto path_encode : {true, false}) {
  15456. Client cli(HOST, port);
  15457. cli.set_follow_location(true);
  15458. cli.set_path_encode(path_encode);
  15459. for (const auto &name : names) {
  15460. target.clear();
  15461. auto res = cli.Get("/start/" + name);
  15462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15463. EXPECT_EQ(StatusCode::OK_200, res->status);
  15464. EXPECT_EQ("/dest/" + name, target);
  15465. }
  15466. }
  15467. }
  15468. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15469. Server svr;
  15470. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15471. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15472. });
  15473. svr.Get("/hello", [](const Request &req, Response &res) {
  15474. res.set_content(req.get_param_value("key"), "text/plain");
  15475. });
  15476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15477. auto se = detail::scope_exit([&] {
  15478. svr.stop();
  15479. thread.join();
  15480. ASSERT_FALSE(svr.is_running());
  15481. });
  15482. svr.wait_until_ready();
  15483. {
  15484. Client cli(HOST, PORT);
  15485. cli.set_follow_location(true);
  15486. auto res = cli.Get("/");
  15487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15488. EXPECT_EQ(StatusCode::OK_200, res->status);
  15489. EXPECT_EQ("val&key2=val2", res->body);
  15490. }
  15491. }
  15492. #endif
  15493. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15494. Server svr;
  15495. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15496. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15497. });
  15498. svr.Get("/hello", [](const Request &req, Response &res) {
  15499. res.set_content(req.get_param_value("key"), "text/plain");
  15500. });
  15501. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15502. auto se = detail::scope_exit([&] {
  15503. svr.stop();
  15504. thread.join();
  15505. ASSERT_FALSE(svr.is_running());
  15506. });
  15507. svr.wait_until_ready();
  15508. {
  15509. Client cli(HOST, PORT);
  15510. cli.set_follow_location(true);
  15511. auto res = cli.Get("/");
  15512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15513. EXPECT_EQ(StatusCode::OK_200, res->status);
  15514. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15515. }
  15516. }
  15517. TEST(RedirectTest, RedirectWithPlusInPath) {
  15518. Server svr;
  15519. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15520. res.set_redirect("/a+b");
  15521. });
  15522. // Route pattern uses regex; escape + as \\+
  15523. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15524. res.set_content(req.path, "text/plain");
  15525. });
  15526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15527. auto se = detail::scope_exit([&] {
  15528. svr.stop();
  15529. thread.join();
  15530. ASSERT_FALSE(svr.is_running());
  15531. });
  15532. svr.wait_until_ready();
  15533. {
  15534. Client cli(HOST, PORT);
  15535. cli.set_follow_location(true);
  15536. auto res = cli.Get("/");
  15537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15538. EXPECT_EQ(StatusCode::OK_200, res->status);
  15539. EXPECT_EQ("/a+b", res->body);
  15540. }
  15541. }
  15542. TEST(RedirectTest, ResolveRelativeLocation) {
  15543. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15544. const std::vector<std::pair<std::string, std::string>> cases = {
  15545. {"g", "/b/c/g"},
  15546. {"./g", "/b/c/g"},
  15547. {"g/", "/b/c/g/"},
  15548. {"?y", "/b/c/d;p?y"},
  15549. {"g?y", "/b/c/g?y"},
  15550. {"#s", "/b/c/d;p?q#s"},
  15551. {"g#s", "/b/c/g#s"},
  15552. {"g?y#s", "/b/c/g?y#s"},
  15553. {";x", "/b/c/;x"},
  15554. {"g;x", "/b/c/g;x"},
  15555. {".", "/b/c/"},
  15556. {"./", "/b/c/"},
  15557. {"..", "/b/"},
  15558. {"../", "/b/"},
  15559. {"../g", "/b/g"},
  15560. {"../..", "/"},
  15561. {"../../", "/"},
  15562. {"../../g", "/g"},
  15563. {"../../../g", "/g"},
  15564. {"g.", "/b/c/g."},
  15565. {".g", "/b/c/.g"},
  15566. {"g..", "/b/c/g.."},
  15567. {"..g", "/b/c/..g"},
  15568. {"./../g", "/b/g"},
  15569. {"./g/.", "/b/c/g/"},
  15570. {"g/./h", "/b/c/g/h"},
  15571. {"g/../h", "/b/c/h"},
  15572. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15573. {"g;x=1/../y", "/b/c/y"},
  15574. {"g?y/./x", "/b/c/g?y/./x"},
  15575. {"g#s/../x", "/b/c/g#s/../x"},
  15576. // Not relative-path references, so left for parse_url.
  15577. {"/g", "/g"},
  15578. {"//g", "//g"},
  15579. {"http://g/x", "http://g/x"},
  15580. {"g:h", "g:h"},
  15581. };
  15582. for (const auto &c : cases) {
  15583. EXPECT_EQ(c.second,
  15584. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15585. << c.first;
  15586. }
  15587. }
  15588. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15589. Server svr;
  15590. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15591. res.set_redirect(req.get_param_value("to"));
  15592. });
  15593. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15594. res.set_content(req.target, "text/plain");
  15595. });
  15596. svr.Get("/other", [](const Request &req, Response &res) {
  15597. res.set_content(req.target, "text/plain");
  15598. });
  15599. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15600. auto se = detail::scope_exit([&] {
  15601. svr.stop();
  15602. thread.join();
  15603. ASSERT_FALSE(svr.is_running());
  15604. });
  15605. svr.wait_until_ready();
  15606. const std::vector<std::pair<std::string, std::string>> cases = {
  15607. {"next", "/dir/next"},
  15608. {"./next?x=1", "/dir/next?x=1"},
  15609. {"../other", "/other"},
  15610. };
  15611. for (const auto &c : cases) {
  15612. Client cli(HOST, PORT);
  15613. cli.set_follow_location(true);
  15614. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15615. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15616. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15617. EXPECT_EQ(c.second, res->body) << c.first;
  15618. }
  15619. }
  15620. #ifdef CPPHTTPLIB_SSL_ENABLED
  15621. TEST(RedirectTest, Issue2185_Online) {
  15622. SSLClient client("github.com");
  15623. client.set_follow_location(true);
  15624. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15625. "Coollab-Windows.zip");
  15626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15627. EXPECT_EQ(StatusCode::OK_200, res->status);
  15628. EXPECT_EQ(9920427U, res->body.size());
  15629. }
  15630. #endif
  15631. TEST(VulnerabilityTest, CRLFInjection) {
  15632. Server svr;
  15633. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15634. res.set_content("Hello 1", "text/plain");
  15635. });
  15636. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15637. res.set_content("Hello 2", "text/plain");
  15638. });
  15639. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15640. res.set_content("Hello 3", "text/plain");
  15641. });
  15642. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15643. res.set_content("Hello 4", "text/plain");
  15644. });
  15645. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15646. for (const auto &x : req.headers) {
  15647. auto key = x.first;
  15648. EXPECT_STRNE("evil", key.c_str());
  15649. }
  15650. });
  15651. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15652. auto se = detail::scope_exit([&] {
  15653. svr.stop();
  15654. thread.join();
  15655. ASSERT_FALSE(svr.is_running());
  15656. });
  15657. svr.wait_until_ready();
  15658. {
  15659. Client cli(HOST, PORT);
  15660. cli.Post("/test1", "A=B",
  15661. "application/x-www-form-urlencoded\r\nevil: hello1");
  15662. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15663. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15664. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15665. }
  15666. }
  15667. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15668. auto server_thread = std::thread([] {
  15669. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15670. default_socket_options(srv);
  15671. sockaddr_in addr{};
  15672. addr.sin_family = AF_INET;
  15673. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15674. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15675. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15676. ::listen(srv, 1);
  15677. sockaddr_in cli_addr{};
  15678. socklen_t cli_len = sizeof(cli_addr);
  15679. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15680. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15681. std::string buf_all;
  15682. char buf[2048];
  15683. ssize_t n;
  15684. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15685. buf_all.append(buf, static_cast<size_t>(n));
  15686. size_t pos;
  15687. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15688. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15689. auto e = request_block.find("\r\n");
  15690. if (e != std::string::npos) {
  15691. auto request_line = request_block.substr(0, e);
  15692. std::string msg =
  15693. "CRLF injection detected in request line: '" + request_line + "'";
  15694. EXPECT_FALSE(true) << msg;
  15695. }
  15696. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15697. ::send(cli,
  15698. #ifdef _WIN32
  15699. static_cast<const char *>(resp.c_str()),
  15700. static_cast<int>(resp.size()),
  15701. #else
  15702. resp.c_str(), resp.size(),
  15703. #endif
  15704. 0);
  15705. buf_all.erase(0, pos + 4);
  15706. }
  15707. }
  15708. detail::close_socket(cli);
  15709. detail::close_socket(srv);
  15710. });
  15711. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15712. auto cli = Client("127.0.0.1", PORT + 1);
  15713. auto headers = Headers{
  15714. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15715. {"Connection", "keep-alive"}};
  15716. auto res = cli.Get("/hi", headers);
  15717. EXPECT_FALSE(res);
  15718. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15719. server_thread.join();
  15720. }
  15721. // A request rejected before any byte reaches the socket must fail right away
  15722. // instead of waiting for a response the server will never send.
  15723. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15724. // The kernel completes the TCP handshake from the listen backlog, so the
  15725. // client connects, but nothing ever reads, responds or closes.
  15726. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15727. default_socket_options(srv);
  15728. sockaddr_in addr{};
  15729. addr.sin_family = AF_INET;
  15730. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15731. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15732. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15733. ASSERT_EQ(0, ::listen(srv, 8));
  15734. auto cli = Client("127.0.0.1", PORT + 1);
  15735. cli.set_read_timeout(10, 0);
  15736. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15737. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15738. std::chrono::steady_clock::now() - start)
  15739. .count();
  15740. };
  15741. {
  15742. Request req;
  15743. req.method = "GE T";
  15744. req.path = "/";
  15745. auto start = std::chrono::steady_clock::now();
  15746. auto res = cli.send(req);
  15747. EXPECT_FALSE(res);
  15748. EXPECT_EQ(Error::Write, res.error());
  15749. EXPECT_LT(elapsed_ms(start), 1000);
  15750. }
  15751. {
  15752. auto start = std::chrono::steady_clock::now();
  15753. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15754. EXPECT_FALSE(res);
  15755. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15756. EXPECT_LT(elapsed_ms(start), 1000);
  15757. }
  15758. EXPECT_FALSE(cli.is_socket_open());
  15759. detail::close_socket(srv);
  15760. }
  15761. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15762. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15763. default_socket_options(srv);
  15764. sockaddr_in addr{};
  15765. addr.sin_family = AF_INET;
  15766. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15767. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15768. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15769. ASSERT_EQ(0, ::listen(srv, 1));
  15770. std::string received;
  15771. auto server_thread = std::thread([&] {
  15772. auto sock = ::accept(srv, nullptr, nullptr);
  15773. if (sock == INVALID_SOCKET) { return; }
  15774. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15775. char buf[2048];
  15776. ssize_t n;
  15777. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15778. received.append(buf, static_cast<size_t>(n));
  15779. }
  15780. detail::close_socket(sock);
  15781. });
  15782. {
  15783. auto cli = Client("127.0.0.1", PORT + 1);
  15784. // "Z" sorts after the default headers, so writing straight to the socket
  15785. // would have sent the request line and those headers before the rejection.
  15786. auto handle =
  15787. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15788. EXPECT_FALSE(handle.is_valid());
  15789. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15790. }
  15791. server_thread.join();
  15792. detail::close_socket(srv);
  15793. EXPECT_TRUE(received.empty()) << received;
  15794. }
  15795. TEST(PathParamsTest, StaticMatch) {
  15796. const auto pattern = "/users/all";
  15797. detail::PathParamsMatcher matcher(pattern);
  15798. Request request;
  15799. request.path = "/users/all";
  15800. ASSERT_TRUE(matcher.match(request));
  15801. std::unordered_map<std::string, std::string> expected_params = {};
  15802. EXPECT_EQ(request.path_params, expected_params);
  15803. }
  15804. TEST(PathParamsTest, StaticMismatch) {
  15805. const auto pattern = "/users/all";
  15806. detail::PathParamsMatcher matcher(pattern);
  15807. Request request;
  15808. request.path = "/users/1";
  15809. ASSERT_FALSE(matcher.match(request));
  15810. }
  15811. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15812. const auto pattern = "/users/:id/subscriptions";
  15813. detail::PathParamsMatcher matcher(pattern);
  15814. Request request;
  15815. request.path = "/users/42/subscriptions";
  15816. ASSERT_TRUE(matcher.match(request));
  15817. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15818. EXPECT_EQ(request.path_params, expected_params);
  15819. }
  15820. TEST(PathParamsTest, SingleParamInTheEnd) {
  15821. const auto pattern = "/users/:id";
  15822. detail::PathParamsMatcher matcher(pattern);
  15823. Request request;
  15824. request.path = "/users/24";
  15825. ASSERT_TRUE(matcher.match(request));
  15826. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15827. EXPECT_EQ(request.path_params, expected_params);
  15828. }
  15829. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15830. const auto pattern = "/users/:id/";
  15831. detail::PathParamsMatcher matcher(pattern);
  15832. Request request;
  15833. request.path = "/users/42/";
  15834. ASSERT_TRUE(matcher.match(request));
  15835. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15836. EXPECT_EQ(request.path_params, expected_params);
  15837. }
  15838. TEST(PathParamsTest, EmptyParam) {
  15839. const auto pattern = "/users/:id/";
  15840. detail::PathParamsMatcher matcher(pattern);
  15841. Request request;
  15842. request.path = "/users//";
  15843. ASSERT_TRUE(matcher.match(request));
  15844. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15845. EXPECT_EQ(request.path_params, expected_params);
  15846. }
  15847. TEST(PathParamsTest, FragmentMismatch) {
  15848. const auto pattern = "/users/:id/";
  15849. detail::PathParamsMatcher matcher(pattern);
  15850. Request request;
  15851. request.path = "/admins/24/";
  15852. ASSERT_FALSE(matcher.match(request));
  15853. }
  15854. TEST(PathParamsTest, ExtraFragments) {
  15855. const auto pattern = "/users/:id";
  15856. detail::PathParamsMatcher matcher(pattern);
  15857. Request request;
  15858. request.path = "/users/42/subscriptions";
  15859. ASSERT_FALSE(matcher.match(request));
  15860. }
  15861. TEST(PathParamsTest, MissingTrailingParam) {
  15862. const auto pattern = "/users/:id";
  15863. detail::PathParamsMatcher matcher(pattern);
  15864. Request request;
  15865. request.path = "/users";
  15866. ASSERT_FALSE(matcher.match(request));
  15867. }
  15868. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15869. const auto pattern = "/users/:id/subscriptions";
  15870. detail::PathParamsMatcher matcher(pattern);
  15871. Request request;
  15872. request.path = "/users/subscriptions";
  15873. ASSERT_FALSE(matcher.match(request));
  15874. }
  15875. TEST(PathParamsTest, MultipleParams) {
  15876. const auto pattern = "/users/:userid/subscriptions/:subid";
  15877. detail::PathParamsMatcher matcher(pattern);
  15878. Request request;
  15879. request.path = "/users/42/subscriptions/2";
  15880. ASSERT_TRUE(matcher.match(request));
  15881. std::unordered_map<std::string, std::string> expected_params = {
  15882. {"userid", "42"}, {"subid", "2"}};
  15883. EXPECT_EQ(request.path_params, expected_params);
  15884. }
  15885. TEST(PathParamsTest, SequenceOfParams) {
  15886. const auto pattern = "/values/:x/:y/:z";
  15887. detail::PathParamsMatcher matcher(pattern);
  15888. Request request;
  15889. request.path = "/values/1/2/3";
  15890. ASSERT_TRUE(matcher.match(request));
  15891. std::unordered_map<std::string, std::string> expected_params = {
  15892. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15893. EXPECT_EQ(request.path_params, expected_params);
  15894. }
  15895. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15896. const auto pattern = "/prefix:suffix";
  15897. detail::PathParamsMatcher matcher(pattern);
  15898. Request request;
  15899. request.path = "/prefix:suffix";
  15900. ASSERT_TRUE(matcher.match(request));
  15901. const std::unordered_map<std::string, std::string> expected_params = {};
  15902. EXPECT_EQ(request.path_params, expected_params);
  15903. }
  15904. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15905. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15906. // calling thread's stack on a long enough path for a quantified pattern;
  15907. // RegexMatcher must refuse to run regex matching on paths beyond
  15908. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15909. detail::RegexMatcher matcher("/files/(.*)");
  15910. Request within_limit;
  15911. within_limit.path = "/files/" + std::string(10, 'A');
  15912. EXPECT_TRUE(matcher.match(within_limit));
  15913. Request over_limit;
  15914. over_limit.path =
  15915. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15916. EXPECT_FALSE(matcher.match(over_limit));
  15917. }
  15918. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15919. Server svr;
  15920. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15921. res.set_content("ok", "text/plain");
  15922. });
  15923. auto port = svr.bind_to_any_port(HOST);
  15924. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15925. auto se = detail::scope_exit([&] {
  15926. svr.stop();
  15927. thread.join();
  15928. ASSERT_FALSE(svr.is_running());
  15929. });
  15930. svr.wait_until_ready();
  15931. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15932. // request URI limit; this used to be able to crash the process.
  15933. std::string path =
  15934. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15935. std::string req = "GET " + path +
  15936. " HTTP/1.1\r\n"
  15937. "Host: " +
  15938. std::string(HOST) + ":" + std::to_string(port) +
  15939. "\r\n"
  15940. "Connection: close\r\n"
  15941. "\r\n";
  15942. std::string response;
  15943. ASSERT_TRUE(send_request(5, req, &response, port));
  15944. EXPECT_NE(std::string::npos, response.find("404"));
  15945. }
  15946. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15947. Server svr;
  15948. auto handler = [](const Request & /*req*/, Response &res) {
  15949. res.set_content("hit", "text/plain");
  15950. };
  15951. // No regex metacharacter, so this one is compared literally
  15952. svr.Get("/literal/route", handler);
  15953. // '.' is a regex metacharacter, so this one must keep regex semantics
  15954. svr.Get("/a.c", handler);
  15955. auto port = svr.bind_to_any_port(HOST);
  15956. std::thread t([&]() { svr.listen_after_bind(); });
  15957. auto se = detail::scope_exit([&] {
  15958. svr.stop();
  15959. t.join();
  15960. ASSERT_FALSE(svr.is_running());
  15961. });
  15962. svr.wait_until_ready();
  15963. Client cli(HOST, port);
  15964. struct {
  15965. const char *path;
  15966. int status;
  15967. } cases[] = {
  15968. {"/literal/route", StatusCode::OK_200},
  15969. {"/literal/routes", StatusCode::NotFound_404},
  15970. {"/literal/rout", StatusCode::NotFound_404},
  15971. {"/abc", StatusCode::OK_200},
  15972. {"/a.c", StatusCode::OK_200},
  15973. };
  15974. for (const auto &x : cases) {
  15975. auto res = cli.Get(x.path);
  15976. ASSERT_TRUE(res) << x.path;
  15977. EXPECT_EQ(x.status, res->status) << x.path;
  15978. }
  15979. }
  15980. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15981. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15982. // from exhausting the stack, so it must only constrain routes that actually
  15983. // run a regular expression. A literal route is matched by comparison and
  15984. // stays usable at any length.
  15985. Server svr;
  15986. const std::string pattern =
  15987. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15988. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15989. res.set_content("hit", "text/plain");
  15990. });
  15991. auto port = svr.bind_to_any_port(HOST);
  15992. std::thread t([&]() { svr.listen_after_bind(); });
  15993. auto se = detail::scope_exit([&] {
  15994. svr.stop();
  15995. t.join();
  15996. ASSERT_FALSE(svr.is_running());
  15997. });
  15998. svr.wait_until_ready();
  15999. Client cli(HOST, port);
  16000. auto res = cli.Get(pattern);
  16001. ASSERT_TRUE(res);
  16002. EXPECT_EQ(StatusCode::OK_200, res->status);
  16003. }
  16004. TEST(ParseUrlTest, VariousPatterns) {
  16005. {
  16006. detail::UrlComponents uc;
  16007. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16008. EXPECT_EQ("http", uc.scheme);
  16009. EXPECT_EQ("example.com", uc.host);
  16010. EXPECT_EQ("8080", uc.port);
  16011. EXPECT_EQ("/path", uc.path);
  16012. EXPECT_EQ("?q=1", uc.query);
  16013. }
  16014. {
  16015. detail::UrlComponents uc;
  16016. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16017. EXPECT_EQ("https", uc.scheme);
  16018. EXPECT_EQ("example.com", uc.host);
  16019. EXPECT_TRUE(uc.port.empty());
  16020. EXPECT_EQ("/path", uc.path);
  16021. }
  16022. {
  16023. detail::UrlComponents uc;
  16024. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16025. EXPECT_EQ("::1", uc.host);
  16026. EXPECT_EQ("8080", uc.port);
  16027. EXPECT_EQ("/path", uc.path);
  16028. }
  16029. {
  16030. detail::UrlComponents uc;
  16031. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16032. }
  16033. {
  16034. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16035. // the path while the connection still targets the bracketed host.
  16036. detail::UrlComponents uc;
  16037. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16038. }
  16039. {
  16040. detail::UrlComponents uc;
  16041. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16042. }
  16043. {
  16044. detail::UrlComponents uc;
  16045. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16046. EXPECT_EQ("::1", uc.host);
  16047. EXPECT_TRUE(uc.port.empty());
  16048. EXPECT_EQ("/path", uc.path);
  16049. }
  16050. {
  16051. detail::UrlComponents uc;
  16052. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16053. EXPECT_TRUE(uc.scheme.empty());
  16054. EXPECT_EQ("example.com", uc.host);
  16055. EXPECT_EQ("/path", uc.path);
  16056. EXPECT_EQ("?q=1", uc.query);
  16057. }
  16058. {
  16059. detail::UrlComponents uc;
  16060. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16061. EXPECT_TRUE(uc.host.empty());
  16062. EXPECT_EQ("/path", uc.path);
  16063. EXPECT_EQ("?q=1", uc.query);
  16064. }
  16065. {
  16066. detail::UrlComponents uc;
  16067. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16068. EXPECT_EQ("example.com", uc.host);
  16069. EXPECT_EQ("8080", uc.port);
  16070. }
  16071. {
  16072. // Unix socket path — must not be parsed as host
  16073. detail::UrlComponents uc;
  16074. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16075. EXPECT_TRUE(uc.host.empty());
  16076. }
  16077. {
  16078. detail::UrlComponents uc;
  16079. ASSERT_TRUE(detail::parse_url("", uc));
  16080. EXPECT_TRUE(uc.host.empty());
  16081. EXPECT_TRUE(uc.path.empty());
  16082. }
  16083. {
  16084. detail::UrlComponents uc;
  16085. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16086. }
  16087. {
  16088. detail::UrlComponents uc;
  16089. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16090. }
  16091. {
  16092. // Accepted by parse_url; callers restrict to http/https
  16093. detail::UrlComponents uc;
  16094. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16095. EXPECT_EQ("ftp", uc.scheme);
  16096. }
  16097. {
  16098. detail::UrlComponents uc;
  16099. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16100. }
  16101. {
  16102. detail::UrlComponents uc;
  16103. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16104. }
  16105. }
  16106. TEST(ParseUrlTest, FragmentHandling) {
  16107. {
  16108. detail::UrlComponents uc;
  16109. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16110. EXPECT_EQ("/path", uc.path);
  16111. EXPECT_TRUE(uc.query.empty());
  16112. }
  16113. {
  16114. detail::UrlComponents uc;
  16115. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16116. EXPECT_TRUE(uc.path.empty());
  16117. EXPECT_TRUE(uc.query.empty());
  16118. }
  16119. }
  16120. TEST(ParseUrlTest, UserinfoHandling) {
  16121. // Userinfo with @ but no colon — host includes @
  16122. detail::UrlComponents uc;
  16123. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  16124. EXPECT_EQ("user@host.com", uc.host);
  16125. EXPECT_EQ("/path", uc.path);
  16126. }
  16127. TEST(ParseUrlTest, IPv6EdgeCases) {
  16128. {
  16129. detail::UrlComponents uc;
  16130. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16131. EXPECT_TRUE(uc.scheme.empty());
  16132. EXPECT_EQ("::1", uc.host);
  16133. EXPECT_EQ("8080", uc.port);
  16134. }
  16135. {
  16136. // Zone ID '%25' is not in [a-fA-F0-9:]
  16137. detail::UrlComponents uc;
  16138. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16139. }
  16140. }
  16141. TEST(ParseUrlTest, SchemeEdgeCases) {
  16142. {
  16143. detail::UrlComponents uc;
  16144. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16145. }
  16146. {
  16147. detail::UrlComponents uc;
  16148. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16149. }
  16150. {
  16151. detail::UrlComponents uc;
  16152. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16153. }
  16154. }
  16155. TEST(ParseUrlTest, PortEdgeCases) {
  16156. {
  16157. detail::UrlComponents uc;
  16158. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16159. EXPECT_TRUE(uc.port.empty());
  16160. EXPECT_EQ("/path", uc.path);
  16161. }
  16162. {
  16163. // parse_url accepts any port string; validation is done by parse_port
  16164. detail::UrlComponents uc;
  16165. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16166. EXPECT_EQ("abc", uc.port);
  16167. }
  16168. }
  16169. TEST(ParseUrlTest, WebSocketPatterns) {
  16170. {
  16171. detail::UrlComponents uc;
  16172. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16173. EXPECT_EQ("ws", uc.scheme);
  16174. EXPECT_EQ("echo.example.com", uc.host);
  16175. EXPECT_EQ("8080", uc.port);
  16176. EXPECT_EQ("/ws", uc.path);
  16177. }
  16178. {
  16179. detail::UrlComponents uc;
  16180. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16181. EXPECT_EQ("wss", uc.scheme);
  16182. EXPECT_EQ("echo.example.com", uc.host);
  16183. EXPECT_TRUE(uc.port.empty());
  16184. EXPECT_EQ("/ws", uc.path);
  16185. }
  16186. }
  16187. TEST(ParseUrlTest, QueryOnly) {
  16188. detail::UrlComponents uc;
  16189. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16190. EXPECT_TRUE(uc.host.empty());
  16191. EXPECT_TRUE(uc.path.empty());
  16192. EXPECT_EQ("?q=1&r=2", uc.query);
  16193. }
  16194. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16195. detail::UrlComponents uc;
  16196. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16197. EXPECT_TRUE(uc.scheme.empty());
  16198. EXPECT_EQ("example.com", uc.host);
  16199. EXPECT_EQ("443", uc.port);
  16200. EXPECT_EQ("/path", uc.path);
  16201. }
  16202. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16203. // If ipv6 regex working, regex match codepath is taken.
  16204. // else port will default to 80 in Client impl
  16205. int clientImplMagicPort = 80;
  16206. int port = 4321;
  16207. // above ports must be different to avoid false negative
  16208. EXPECT_NE(clientImplMagicPort, port);
  16209. std::string ipV6TestURL = "http://[ff06::c3]";
  16210. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16211. CLIENT_PRIVATE_KEY_FILE);
  16212. EXPECT_EQ(cli.port(), port);
  16213. }
  16214. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16215. auto file_path = "./www/dir/index.html";
  16216. auto dir_path = "./www/dir";
  16217. detail::FileStat stat_file(file_path);
  16218. EXPECT_TRUE(stat_file.is_file());
  16219. EXPECT_FALSE(stat_file.is_dir());
  16220. detail::FileStat stat_dir(dir_path);
  16221. EXPECT_FALSE(stat_dir.is_file());
  16222. EXPECT_TRUE(stat_dir.is_dir());
  16223. }
  16224. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16225. // IPv4 with default HTTP port (80)
  16226. EXPECT_EQ("example.com",
  16227. detail::make_host_and_port_string("example.com", 80, false));
  16228. // IPv4 with default HTTPS port (443)
  16229. EXPECT_EQ("example.com",
  16230. detail::make_host_and_port_string("example.com", 443, true));
  16231. // IPv4 with non-default HTTP port
  16232. EXPECT_EQ("example.com:8080",
  16233. detail::make_host_and_port_string("example.com", 8080, false));
  16234. // IPv4 with non-default HTTPS port
  16235. EXPECT_EQ("example.com:8443",
  16236. detail::make_host_and_port_string("example.com", 8443, true));
  16237. // IPv6 with default HTTP port (80)
  16238. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16239. // IPv6 with default HTTPS port (443)
  16240. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16241. // IPv6 with non-default HTTP port
  16242. EXPECT_EQ("[::1]:8080",
  16243. detail::make_host_and_port_string("::1", 8080, false));
  16244. // IPv6 with non-default HTTPS port
  16245. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16246. // IPv6 full address with default port
  16247. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16248. detail::make_host_and_port_string(
  16249. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16250. // IPv6 full address with non-default port
  16251. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16252. detail::make_host_and_port_string(
  16253. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16254. // IPv6 localhost with non-default port
  16255. EXPECT_EQ("[::1]:3000",
  16256. detail::make_host_and_port_string("::1", 3000, false));
  16257. // IPv6 with zone ID (link-local address) with default port
  16258. EXPECT_EQ("[fe80::1%eth0]",
  16259. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16260. // IPv6 with zone ID (link-local address) with non-default port
  16261. EXPECT_EQ("[fe80::1%eth0]:8080",
  16262. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16263. // Edge case: Port 443 with is_ssl=false (should add port)
  16264. EXPECT_EQ("example.com:443",
  16265. detail::make_host_and_port_string("example.com", 443, false));
  16266. // Edge case: Port 80 with is_ssl=true (should add port)
  16267. EXPECT_EQ("example.com:80",
  16268. detail::make_host_and_port_string("example.com", 80, true));
  16269. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16270. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16271. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16272. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16273. // Security fix: Already bracketed IPv6 should not get double brackets
  16274. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16275. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16276. EXPECT_EQ("[::1]:8080",
  16277. detail::make_host_and_port_string("[::1]", 8080, false));
  16278. EXPECT_EQ("[2001:db8::1]:8080",
  16279. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16280. EXPECT_EQ("[fe80::1%eth0]",
  16281. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16282. EXPECT_EQ("[fe80::1%eth0]:8080",
  16283. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16284. // Edge case: Empty host (should return as-is)
  16285. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16286. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16287. // This is a known limitation but shouldn't crash
  16288. EXPECT_EQ("[host:name]",
  16289. detail::make_host_and_port_string("host:name", 80, false));
  16290. // Port number edge cases (no validation, but should not crash)
  16291. EXPECT_EQ("example.com:0",
  16292. detail::make_host_and_port_string("example.com", 0, false));
  16293. EXPECT_EQ("example.com:-1",
  16294. detail::make_host_and_port_string("example.com", -1, false));
  16295. EXPECT_EQ("example.com:65535",
  16296. detail::make_host_and_port_string("example.com", 65535, false));
  16297. EXPECT_EQ("example.com:65536",
  16298. detail::make_host_and_port_string("example.com", 65536, false));
  16299. }
  16300. #ifdef CPPHTTPLIB_SSL_ENABLED
  16301. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16302. httplib::SSLClient cli("roblox.com", 443);
  16303. cli.set_follow_location(true);
  16304. auto res = cli.Get("/");
  16305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16306. EXPECT_EQ(StatusCode::OK_200, res->status);
  16307. }
  16308. #endif
  16309. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16310. Server svr;
  16311. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16312. EXPECT_EQ(res.status, 400);
  16313. });
  16314. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16315. auto se = detail::scope_exit([&] {
  16316. svr.stop();
  16317. thread.join();
  16318. ASSERT_FALSE(svr.is_running());
  16319. });
  16320. svr.wait_until_ready();
  16321. Client cli(HOST, PORT);
  16322. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16323. }
  16324. TEST(InvalidHeaderCharsTest, is_field_name) {
  16325. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16326. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16327. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16328. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16329. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16330. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16331. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16332. EXPECT_FALSE(detail::fields::is_field_name(""));
  16333. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16334. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16335. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16336. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16337. }
  16338. TEST(InvalidHeaderCharsTest, is_field_value) {
  16339. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16340. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16341. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16342. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16343. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16344. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16345. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16346. EXPECT_TRUE(detail::fields::is_field_value(""));
  16347. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16348. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16349. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16350. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16351. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16352. }
  16353. TEST(InvalidHeaderCharsTest, OnServer) {
  16354. Server svr;
  16355. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16356. std::string header = "Not Set";
  16357. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16358. res.set_header(header, "value");
  16359. res.set_content("Page Content Page Content", "text/plain");
  16360. });
  16361. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16362. std::string header = "Not Set";
  16363. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16364. res.set_header("X-Test", header);
  16365. res.set_content("Page Content Page Content", "text/plain");
  16366. });
  16367. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16368. auto se = detail::scope_exit([&] {
  16369. svr.stop();
  16370. thread.join();
  16371. ASSERT_FALSE(svr.is_running());
  16372. });
  16373. svr.wait_until_ready();
  16374. Client cli(HOST, PORT);
  16375. {
  16376. auto res = cli.Get(
  16377. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16379. EXPECT_EQ("Page Content Page Content", res->body);
  16380. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16381. }
  16382. {
  16383. auto res = cli.Get(
  16384. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16386. EXPECT_EQ("Page Content Page Content", res->body);
  16387. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16388. }
  16389. }
  16390. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16391. auto handled = false;
  16392. Server svr;
  16393. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16394. thread t = thread([&] { svr.listen(HOST, PORT); });
  16395. auto se = detail::scope_exit([&] {
  16396. svr.stop();
  16397. t.join();
  16398. ASSERT_FALSE(svr.is_running());
  16399. ASSERT_FALSE(handled);
  16400. });
  16401. svr.wait_until_ready();
  16402. auto req = "POST /test HTTP/1.1\r\n"
  16403. "Content-Length: x\r\n"
  16404. "\r\n";
  16405. std::string response;
  16406. ASSERT_TRUE(send_request(1, req, &response));
  16407. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16408. response.substr(0, response.find("\r\n")));
  16409. }
  16410. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16411. // case-insensitive, and a server that receives a 100-continue expectation in
  16412. // an HTTP/1.0 request MUST ignore it.
  16413. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16414. std::string response;
  16415. ASSERT_TRUE(send_request(1, req, &response, port));
  16416. *got_100 = response.find("100 Continue") != std::string::npos;
  16417. }
  16418. class ExpectTokenTest : public ::testing::Test {
  16419. protected:
  16420. void SetUp() override {
  16421. svr_.Post("/p", [](const Request &, Response &res) {
  16422. res.set_content("ok", "text/plain");
  16423. });
  16424. port_ = svr_.bind_to_any_port(HOST);
  16425. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16426. svr_.wait_until_ready();
  16427. }
  16428. void TearDown() override {
  16429. svr_.stop();
  16430. if (thread_.joinable()) { thread_.join(); }
  16431. }
  16432. std::string request(const char *version, const char *expect_value) const {
  16433. return std::string("POST /p ") + version +
  16434. "\r\n"
  16435. "Host: localhost\r\n"
  16436. "Content-Length: 2\r\n"
  16437. "Connection: close\r\n"
  16438. "Expect: " +
  16439. expect_value +
  16440. "\r\n"
  16441. "\r\n"
  16442. "hi";
  16443. }
  16444. Server svr_;
  16445. int port_ = 0;
  16446. thread thread_;
  16447. };
  16448. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16449. bool got_100 = false;
  16450. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16451. EXPECT_TRUE(got_100);
  16452. }
  16453. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16454. bool got_100 = true;
  16455. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16456. EXPECT_FALSE(got_100);
  16457. }
  16458. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16459. bool got_100 = false;
  16460. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16461. EXPECT_TRUE(got_100);
  16462. }
  16463. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16464. bool got_100 = false;
  16465. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16466. EXPECT_TRUE(got_100);
  16467. }
  16468. // `100 Continue` is sent only when the server starts reading the body, so a
  16469. // request rejected before that never invites the client to send it. The
  16470. // requests below carry the expectation but withhold the body, as a client
  16471. // waiting for `100 Continue` would.
  16472. // A POST that expects `100 Continue` and withholds its two-byte body.
  16473. static std::string expect_headers_only(const std::string &path) {
  16474. return "POST " + path +
  16475. " HTTP/1.1\r\n"
  16476. "Host: localhost\r\n"
  16477. "Content-Length: 2\r\n"
  16478. "Expect: 100-continue\r\n"
  16479. "\r\n";
  16480. }
  16481. class ExpectLazyContinueTest : public ::testing::Test {
  16482. protected:
  16483. void SetUp() override {
  16484. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16485. if (req.path == "/pre-routing") {
  16486. res.status = StatusCode::Unauthorized_401;
  16487. return Server::HandlerResponse::Handled;
  16488. }
  16489. return Server::HandlerResponse::Unhandled;
  16490. });
  16491. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16492. if (req.matched_route == "/pre-request") {
  16493. res.status = StatusCode::Forbidden_403;
  16494. return Server::HandlerResponse::Handled;
  16495. }
  16496. return Server::HandlerResponse::Unhandled;
  16497. });
  16498. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16499. res.set_content("ok", "text/plain");
  16500. });
  16501. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16502. res.set_content("ok", "text/plain");
  16503. });
  16504. svr_.Post("/reader-used", [](const Request &, Response &res,
  16505. const ContentReader &content_reader) {
  16506. std::string body;
  16507. content_reader([&](const char *data, size_t len) {
  16508. body.append(data, len);
  16509. return true;
  16510. });
  16511. res.set_content(body, "text/plain");
  16512. });
  16513. svr_.Post("/reader-unused",
  16514. [](const Request &, Response &res, const ContentReader &) {
  16515. res.set_content("ignored", "text/plain");
  16516. });
  16517. port_ = svr_.bind_to_any_port(HOST);
  16518. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16519. svr_.wait_until_ready();
  16520. }
  16521. void TearDown() override {
  16522. svr_.stop();
  16523. if (thread_.joinable()) { thread_.join(); }
  16524. }
  16525. // Sends `req` and reads until the server closes the connection. Returns
  16526. // false if the read had to wait for the client-side timeout instead.
  16527. bool send_until_closed(const std::string &req, std::string *resp) const {
  16528. auto start = std::chrono::steady_clock::now();
  16529. if (!send_request(3, req, resp, port_)) { return false; }
  16530. auto elapsed = std::chrono::steady_clock::now() - start;
  16531. return elapsed < std::chrono::seconds(2);
  16532. }
  16533. // The final response comes without `100 Continue`, and the server closes
  16534. // the connection since the body may or may not follow.
  16535. void expect_final_without_interim(const std::string &path,
  16536. const char *status_line) const {
  16537. std::string resp;
  16538. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16539. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16540. EXPECT_EQ(0u, resp.find(status_line));
  16541. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16542. }
  16543. Server svr_;
  16544. int port_ = 0;
  16545. thread thread_;
  16546. };
  16547. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16548. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16549. }
  16550. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16551. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16552. }
  16553. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16554. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16555. }
  16556. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16557. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16558. }
  16559. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16560. // The body follows once `100 Continue` has had time to arrive.
  16561. auto req = expect_headers_only("/reader-used");
  16562. req.insert(req.size() - 2, "Connection: close\r\n");
  16563. std::string resp;
  16564. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16565. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16566. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16567. EXPECT_NE(std::string::npos, resp.find("hi"));
  16568. }
  16569. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16570. // Large enough for the client to add `Expect: 100-continue` itself.
  16571. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16572. std::atomic<bool> body_sent{false};
  16573. Client cli(HOST, port_);
  16574. auto res = cli.Post(
  16575. "/pre-request", length,
  16576. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16577. body_sent = true;
  16578. std::string chunk(len, 'x');
  16579. sink.write(chunk.data(), chunk.size());
  16580. return true;
  16581. },
  16582. "application/octet-stream");
  16583. ASSERT_TRUE(res);
  16584. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16585. EXPECT_FALSE(body_sent);
  16586. }
  16587. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16588. Server svr;
  16589. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16590. return StatusCode::ExpectationFailed_417;
  16591. });
  16592. svr.Post("/p", [](const Request &, Response &res) {
  16593. res.set_content("ok", "text/plain");
  16594. });
  16595. auto port = svr.bind_to_any_port(HOST);
  16596. thread t = thread([&] { svr.listen_after_bind(); });
  16597. auto se = detail::scope_exit([&] {
  16598. svr.stop();
  16599. t.join();
  16600. });
  16601. svr.wait_until_ready();
  16602. std::string resp;
  16603. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16604. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16605. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16606. // Exactly one response: the route handler must not run after the 417.
  16607. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16608. }
  16609. #ifndef _WIN32
  16610. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16611. static constexpr char reject[] = "Unauthorized";
  16612. static constexpr char accept[] = "Upload accepted";
  16613. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16614. Server svr;
  16615. svr.set_expect_100_continue_handler(
  16616. [](const Request & /*req*/, Response &res) {
  16617. res.status = StatusCode::Unauthorized_401;
  16618. res.set_content(reject, "text/plain");
  16619. return res.status;
  16620. });
  16621. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16622. res.set_content(accept, "text/plain");
  16623. });
  16624. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16625. auto se = detail::scope_exit([&] {
  16626. svr.stop();
  16627. thread.join();
  16628. ASSERT_FALSE(svr.is_running());
  16629. });
  16630. svr.wait_until_ready();
  16631. {
  16632. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16633. curl_easy_init(), &curl_easy_cleanup};
  16634. ASSERT_NE(curl, nullptr);
  16635. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16636. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16637. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16638. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16639. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16640. &curl_slist_free_all};
  16641. ASSERT_NE(list, nullptr);
  16642. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16643. struct read_data {
  16644. size_t read_size;
  16645. size_t total_size;
  16646. } data = {0, total_size};
  16647. using read_callback_t =
  16648. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16649. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16650. void *userdata) -> size_t {
  16651. read_data *d = (read_data *)userdata;
  16652. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16653. std::fill_n(ptr, size * nmemb, 'A');
  16654. d->read_size += size * nmemb;
  16655. return size * nmemb;
  16656. };
  16657. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16658. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16659. std::vector<char> buffer;
  16660. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16661. using write_callback_t =
  16662. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16663. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16664. void *userdata) -> size_t {
  16665. std::vector<char> *buf = (std::vector<char> *)userdata;
  16666. buf->reserve(buf->size() + size * nmemb + 1);
  16667. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16668. return size * nmemb;
  16669. };
  16670. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16671. {
  16672. const auto res = curl_easy_perform(curl.get());
  16673. ASSERT_EQ(res, CURLE_OK);
  16674. }
  16675. {
  16676. auto response_code = long{};
  16677. const auto res =
  16678. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16679. ASSERT_EQ(res, CURLE_OK);
  16680. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16681. }
  16682. {
  16683. auto dl = curl_off_t{};
  16684. const auto res =
  16685. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16686. ASSERT_EQ(res, CURLE_OK);
  16687. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16688. }
  16689. {
  16690. buffer.push_back('\0');
  16691. ASSERT_STRCASEEQ(buffer.data(), reject);
  16692. }
  16693. }
  16694. }
  16695. #endif
  16696. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16697. // Regression test for #2458.
  16698. //
  16699. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16700. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16701. // ticket can make the client socket spuriously readable during the
  16702. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16703. // the client withholds the body and then blocks reading a response that never
  16704. // comes, failing with `Failed to read connection`.
  16705. //
  16706. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16707. // within the timeout. This raw OpenSSL server deliberately never sends
  16708. // `100 Continue`; the client must still deliver the body and receive 200.
  16709. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16710. signal(SIGPIPE, SIG_IGN);
  16711. const auto port = PORT + 4;
  16712. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16713. ASSERT_NE(srv, INVALID_SOCKET);
  16714. int opt = 1;
  16715. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16716. sockaddr_in addr{};
  16717. addr.sin_family = AF_INET;
  16718. addr.sin_port = htons(static_cast<uint16_t>(port));
  16719. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16720. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16721. ASSERT_EQ(0, ::listen(srv, 1));
  16722. std::atomic<size_t> server_body_bytes{0};
  16723. auto server_thread = std::thread([&] {
  16724. sockaddr_in cli_addr{};
  16725. socklen_t cli_len = sizeof(cli_addr);
  16726. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16727. if (cli == INVALID_SOCKET) { return; }
  16728. // Bound the lifetime of the server side so a buggy client (which never
  16729. // sends the body) cannot make this thread block forever on join.
  16730. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16731. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16732. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16733. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16734. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16735. SSL *ssl = SSL_new(ctx);
  16736. SSL_set_fd(ssl, static_cast<int>(cli));
  16737. if (SSL_accept(ssl) > 0) {
  16738. // Read the request headers. Reading here also flushes the TLS 1.3
  16739. // session tickets to the client. Deliberately do NOT send
  16740. // `100 Continue`.
  16741. std::string buf;
  16742. char tmp[1024];
  16743. while (buf.find("\r\n\r\n") == std::string::npos) {
  16744. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16745. if (n <= 0) { break; }
  16746. buf.append(tmp, static_cast<size_t>(n));
  16747. }
  16748. // A correct client sends the body now; count what arrives.
  16749. auto pos = buf.find("\r\n\r\n");
  16750. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16751. while (body < 4096) {
  16752. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16753. if (n <= 0) { break; }
  16754. body += static_cast<size_t>(n);
  16755. }
  16756. server_body_bytes = body;
  16757. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16758. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16759. SSL_shutdown(ssl);
  16760. }
  16761. SSL_free(ssl);
  16762. detail::close_socket(cli);
  16763. SSL_CTX_free(ctx);
  16764. });
  16765. auto se = detail::scope_exit([&] {
  16766. server_thread.join();
  16767. detail::close_socket(srv);
  16768. });
  16769. SSLClient cli("127.0.0.1", port);
  16770. cli.enable_server_certificate_verification(false);
  16771. cli.set_connection_timeout(5, 0);
  16772. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16773. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16774. std::string body(4096, 'A');
  16775. auto res = cli.Put("/api/test", body, "application/json");
  16776. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16777. EXPECT_EQ(StatusCode::OK_200, res->status);
  16778. EXPECT_EQ(body.size(), server_body_bytes.load());
  16779. }
  16780. #endif
  16781. template <typename S, typename C>
  16782. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16783. svr.Get("/stream", [&](const Request &, Response &res) {
  16784. auto data = new std::string("01234567890123456789");
  16785. res.set_content_provider(
  16786. data->size(), "text/plain",
  16787. [&, data](size_t offset, size_t length, DataSink &sink) {
  16788. const size_t DATA_CHUNK_SIZE = 4;
  16789. const auto &d = *data;
  16790. std::this_thread::sleep_for(std::chrono::seconds(1));
  16791. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16792. return true;
  16793. },
  16794. [data](bool success) {
  16795. EXPECT_FALSE(success);
  16796. delete data;
  16797. });
  16798. });
  16799. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16800. auto i = new size_t(0);
  16801. res.set_content_provider(
  16802. "text/plain",
  16803. [i](size_t, DataSink &sink) {
  16804. if (*i < 5) {
  16805. std::this_thread::sleep_for(std::chrono::seconds(1));
  16806. sink.write("abcd", 4);
  16807. (*i)++;
  16808. } else {
  16809. sink.done();
  16810. }
  16811. return true;
  16812. },
  16813. [i](bool success) {
  16814. EXPECT_FALSE(success);
  16815. delete i;
  16816. });
  16817. });
  16818. svr.Get("/chunked", [&](const Request &, Response &res) {
  16819. auto i = new size_t(0);
  16820. res.set_chunked_content_provider(
  16821. "text/plain",
  16822. [i](size_t, DataSink &sink) {
  16823. if (*i < 5) {
  16824. std::this_thread::sleep_for(std::chrono::seconds(1));
  16825. sink.os << "abcd";
  16826. (*i)++;
  16827. } else {
  16828. sink.done();
  16829. }
  16830. return true;
  16831. },
  16832. [i](bool success) {
  16833. EXPECT_FALSE(success);
  16834. delete i;
  16835. });
  16836. });
  16837. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16838. auto se = detail::scope_exit([&] {
  16839. svr.stop();
  16840. listen_thread.join();
  16841. ASSERT_FALSE(svr.is_running());
  16842. });
  16843. svr.wait_until_ready();
  16844. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16845. {
  16846. auto start = std::chrono::steady_clock::now();
  16847. auto res = cli.Get("/stream");
  16848. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16849. std::chrono::steady_clock::now() - start)
  16850. .count();
  16851. ASSERT_FALSE(res);
  16852. EXPECT_EQ(Error::Read, res.error());
  16853. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16854. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16855. }
  16856. {
  16857. auto start = std::chrono::steady_clock::now();
  16858. auto res = cli.Get("/stream_without_length");
  16859. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16860. std::chrono::steady_clock::now() - start)
  16861. .count();
  16862. ASSERT_FALSE(res);
  16863. EXPECT_EQ(Error::Read, res.error());
  16864. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16865. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16866. }
  16867. {
  16868. auto start = std::chrono::steady_clock::now();
  16869. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16870. EXPECT_EQ("abcd", string(data, data_length));
  16871. return true;
  16872. });
  16873. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16874. std::chrono::steady_clock::now() - start)
  16875. .count();
  16876. ASSERT_FALSE(res);
  16877. EXPECT_EQ(Error::Read, res.error());
  16878. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16879. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16880. }
  16881. }
  16882. TEST(MaxTimeoutTest, ContentStream) {
  16883. time_t timeout = 2000;
  16884. time_t threshold = 200;
  16885. Server svr;
  16886. Client cli("localhost", PORT);
  16887. max_timeout_test(svr, cli, timeout, threshold);
  16888. }
  16889. #ifdef CPPHTTPLIB_SSL_ENABLED
  16890. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16891. time_t timeout = 2000;
  16892. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16894. SSLClient cli("localhost", PORT);
  16895. cli.enable_server_certificate_verification(false);
  16896. max_timeout_test(svr, cli, timeout, threshold);
  16897. }
  16898. #endif
  16899. class EventDispatcher {
  16900. public:
  16901. EventDispatcher() {}
  16902. bool wait_event(DataSink *sink) {
  16903. unique_lock<mutex> lk(m_);
  16904. int id = id_;
  16905. // Wait with timeout to prevent hanging if client disconnects
  16906. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16907. [&] { return cid_ == id; })) {
  16908. return false; // Timeout occurred
  16909. }
  16910. sink->write(message_.data(), message_.size());
  16911. return true;
  16912. }
  16913. void send_event(const string &message) {
  16914. lock_guard<mutex> lk(m_);
  16915. cid_ = id_++;
  16916. message_ = message;
  16917. cv_.notify_all();
  16918. }
  16919. private:
  16920. mutex m_;
  16921. condition_variable cv_;
  16922. atomic_int id_{0};
  16923. atomic_int cid_{-1};
  16924. string message_;
  16925. };
  16926. TEST(ClientInThreadTest, Issue2068) {
  16927. EventDispatcher ed;
  16928. Server svr;
  16929. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16930. res.set_chunked_content_provider("text/event-stream",
  16931. [&](size_t /*offset*/, DataSink &sink) {
  16932. return ed.wait_event(&sink);
  16933. });
  16934. });
  16935. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16936. svr.wait_until_ready();
  16937. thread event_thread([&] {
  16938. int id = 0;
  16939. while (svr.is_running()) {
  16940. this_thread::sleep_for(chrono::milliseconds(500));
  16941. std::stringstream ss;
  16942. ss << "data: " << id << "\n\n";
  16943. ed.send_event(ss.str());
  16944. id++;
  16945. }
  16946. });
  16947. auto se = detail::scope_exit([&] {
  16948. svr.stop();
  16949. listen_thread.join();
  16950. event_thread.join();
  16951. ASSERT_FALSE(svr.is_running());
  16952. });
  16953. {
  16954. auto client = detail::make_unique<Client>(HOST, PORT);
  16955. client->set_read_timeout(std::chrono::minutes(10));
  16956. std::atomic<bool> stop{false};
  16957. std::thread t([&] {
  16958. client->Get("/event1",
  16959. [&](const char *, size_t) -> bool { return !stop; });
  16960. });
  16961. std::this_thread::sleep_for(std::chrono::seconds(2));
  16962. stop = true;
  16963. client->stop();
  16964. t.join();
  16965. // Reset client after thread has finished
  16966. client.reset();
  16967. }
  16968. }
  16969. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16970. auto handled = false;
  16971. Server svr;
  16972. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16973. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16974. auto se = detail::scope_exit([&] {
  16975. svr.stop();
  16976. t.join();
  16977. ASSERT_FALSE(svr.is_running());
  16978. ASSERT_FALSE(handled);
  16979. });
  16980. svr.wait_until_ready();
  16981. // Two Content-Length headers with different values — must be rejected
  16982. auto req = "POST /test HTTP/1.1\r\n"
  16983. "Content-Length: 5\r\n"
  16984. "Content-Length: 10\r\n"
  16985. "\r\n"
  16986. "hello";
  16987. std::string response;
  16988. ASSERT_TRUE(send_request(1, req, &response));
  16989. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16990. response.substr(0, response.find("\r\n")));
  16991. }
  16992. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16993. auto handled = false;
  16994. Server svr;
  16995. svr.Post("/test", [&](const Request &, Response &res) {
  16996. handled = true;
  16997. res.set_content("ok", "text/plain");
  16998. });
  16999. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17000. auto se = detail::scope_exit([&] {
  17001. svr.stop();
  17002. t.join();
  17003. ASSERT_FALSE(svr.is_running());
  17004. ASSERT_TRUE(handled);
  17005. });
  17006. svr.wait_until_ready();
  17007. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17008. auto req = "POST /test HTTP/1.1\r\n"
  17009. "Content-Length: 5\r\n"
  17010. "Content-Length: 5\r\n"
  17011. "\r\n"
  17012. "hello";
  17013. std::string response;
  17014. ASSERT_TRUE(send_request(1, req, &response));
  17015. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17016. }
  17017. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17018. Server svr;
  17019. svr.Get("/test", [](const Request &, Response &res) {
  17020. res.set_content("ok", "text/plain");
  17021. });
  17022. auto port = svr.bind_to_any_port(HOST);
  17023. thread t = thread([&] { svr.listen_after_bind(); });
  17024. auto se = detail::scope_exit([&] {
  17025. svr.stop();
  17026. t.join();
  17027. ASSERT_FALSE(svr.is_running());
  17028. });
  17029. svr.wait_until_ready();
  17030. auto status_line = [&](const std::string &host_lines) {
  17031. std::string res;
  17032. send_request(
  17033. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17034. &res, port);
  17035. return res.substr(0, res.find("\r\n"));
  17036. };
  17037. const char *accepted[] = {
  17038. "Host: localhost\r\n",
  17039. "Host: a.example:8080\r\n",
  17040. "Host: my_service\r\n",
  17041. "Host: [::1]:8080\r\n",
  17042. "Host: [fe80::1%25eth0]\r\n",
  17043. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17044. };
  17045. for (auto host_lines : accepted) {
  17046. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17047. }
  17048. const char *rejected[] = {
  17049. "Host: a.example\r\nHost: b.example\r\n",
  17050. "Host: a.example\r\nHost: a.example\r\n",
  17051. "Host: a@b.example\r\n",
  17052. "Host: a.example/b\r\n",
  17053. "Host: a.example\\b\r\n",
  17054. "Host: a.example?b\r\n",
  17055. "Host: a.example#b\r\n",
  17056. "Host: a.example b.example\r\n",
  17057. };
  17058. for (auto host_lines : rejected) {
  17059. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17060. << host_lines;
  17061. }
  17062. }
  17063. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17064. Server svr;
  17065. svr.Get("/", [](const Request &req, Response &res) {
  17066. EXPECT_EQ(2U, req.trailers.size());
  17067. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17068. // Denied
  17069. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17070. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17071. // Accepted
  17072. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17073. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17074. EXPECT_TRUE(req.has_trailer("X-World"));
  17075. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17076. res.set_content("ok", "text/plain");
  17077. });
  17078. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17079. auto se = detail::scope_exit([&] {
  17080. svr.stop();
  17081. t.join();
  17082. ASSERT_FALSE(svr.is_running());
  17083. });
  17084. svr.wait_until_ready();
  17085. const std::string req = "GET / HTTP/1.1\r\n"
  17086. "Transfer-Encoding: chunked\r\n"
  17087. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17088. "\r\n"
  17089. "0\r\n"
  17090. "Content-Length: 10\r\n"
  17091. "Host: internal.local\r\n"
  17092. "Content-Type: malicious/content\r\n"
  17093. "Cookie: any\r\n"
  17094. "Set-Cookie: any\r\n"
  17095. "X-Forwarded-For: attacker.com\r\n"
  17096. "X-Real-Ip: 1.1.1.1\r\n"
  17097. "X-Hello: hello\r\n"
  17098. "X-World: world\r\n"
  17099. "\r\n";
  17100. std::string res;
  17101. ASSERT_TRUE(send_request(1, req, &res));
  17102. }
  17103. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17104. // several field lines, and the combined value is what has to be parsed. A
  17105. // Trailer field split across lines therefore declares every name it lists;
  17106. // reading only the first line silently drops the trailers the later lines
  17107. // declare. The prohibited-trailer filter still applies to every line.
  17108. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17109. Server svr;
  17110. size_t observed_trailer_count = 0;
  17111. std::string observed_hello;
  17112. std::string observed_world;
  17113. bool observed_content_length = true;
  17114. svr.Get("/", [&](const Request &req, Response &res) {
  17115. observed_trailer_count = req.trailers.size();
  17116. observed_hello = req.get_trailer_value("X-Hello");
  17117. observed_world = req.get_trailer_value("X-World");
  17118. observed_content_length = req.has_trailer("Content-Length");
  17119. res.set_content("ok", "text/plain");
  17120. });
  17121. auto port = svr.bind_to_any_port(HOST);
  17122. thread t = thread([&]() { svr.listen_after_bind(); });
  17123. auto se = detail::scope_exit([&] {
  17124. svr.stop();
  17125. t.join();
  17126. ASSERT_FALSE(svr.is_running());
  17127. });
  17128. svr.wait_until_ready();
  17129. const std::string req = "GET / HTTP/1.1\r\n"
  17130. "Transfer-Encoding: chunked\r\n"
  17131. "Trailer: X-Hello\r\n"
  17132. "Trailer: X-World, Content-Length\r\n"
  17133. "\r\n"
  17134. "0\r\n"
  17135. "X-Hello: hello\r\n"
  17136. "X-World: world\r\n"
  17137. "Content-Length: 10\r\n"
  17138. "\r\n";
  17139. std::string res;
  17140. ASSERT_TRUE(send_request(1, req, &res, port));
  17141. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17142. // Accepted: both field lines contribute to the declared set
  17143. EXPECT_EQ(2U, observed_trailer_count);
  17144. EXPECT_EQ(observed_hello, "hello");
  17145. EXPECT_EQ(observed_world, "world");
  17146. // Denied: a prohibited name stays prohibited on a later field line
  17147. EXPECT_FALSE(observed_content_length);
  17148. }
  17149. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17150. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17151. // unbounded run of fields that are never declared, because the counter would
  17152. // only advance for declared fields.
  17153. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17154. Server svr;
  17155. bool handler_called = false;
  17156. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17157. handler_called = true;
  17158. res.set_content("ok", "text/plain");
  17159. });
  17160. auto port = svr.bind_to_any_port(HOST);
  17161. thread t = thread([&]() { svr.listen_after_bind(); });
  17162. auto se = detail::scope_exit([&] {
  17163. svr.stop();
  17164. t.join();
  17165. ASSERT_FALSE(svr.is_running());
  17166. });
  17167. svr.wait_until_ready();
  17168. // Declare nothing, then send far more undeclared trailer fields than the
  17169. // header-count limit. Parsing must stop and reject the request rather than
  17170. // read every line.
  17171. std::string req = "GET / HTTP/1.1\r\n"
  17172. "Transfer-Encoding: chunked\r\n"
  17173. "\r\n"
  17174. "0\r\n";
  17175. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17176. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17177. }
  17178. req += "\r\n";
  17179. std::string res;
  17180. ASSERT_TRUE(send_request(1, req, &res, port));
  17181. // The request is rejected before the handler runs.
  17182. EXPECT_FALSE(handler_called);
  17183. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17184. }
  17185. // The set of declared trailer names is capped so a peer cannot grow it without
  17186. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17187. // declared past the cap is not honored, even if the field is actually sent.
  17188. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17189. Server svr;
  17190. // One name inside the cap and one past it, so the test tracks the cap rather
  17191. // than a fixed count.
  17192. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17193. const std::string within_cap_name = "X-T-0";
  17194. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17195. bool observed_within_cap = false;
  17196. bool observed_past_cap = false;
  17197. svr.Get("/", [&](const Request &req, Response &res) {
  17198. observed_within_cap = req.has_trailer(within_cap_name);
  17199. observed_past_cap = req.has_trailer(past_cap_name);
  17200. res.set_content("ok", "text/plain");
  17201. });
  17202. auto port = svr.bind_to_any_port(HOST);
  17203. thread t = thread([&]() { svr.listen_after_bind(); });
  17204. auto se = detail::scope_exit([&] {
  17205. svr.stop();
  17206. t.join();
  17207. ASSERT_FALSE(svr.is_running());
  17208. });
  17209. svr.wait_until_ready();
  17210. // Declare more trailer names than the cap in a single Trailer field, then
  17211. // actually send the first (within the cap) and the last (past it).
  17212. std::string trailer_decl = "Trailer: ";
  17213. for (int i = 0; i < declared_count; i++) {
  17214. if (i != 0) { trailer_decl += ", "; }
  17215. trailer_decl += "X-T-" + std::to_string(i);
  17216. }
  17217. trailer_decl += "\r\n";
  17218. const std::string req = "GET / HTTP/1.1\r\n"
  17219. "Transfer-Encoding: chunked\r\n" +
  17220. trailer_decl +
  17221. "\r\n"
  17222. "0\r\n" +
  17223. within_cap_name + ": a\r\n" + past_cap_name +
  17224. ": b\r\n"
  17225. "\r\n";
  17226. std::string res;
  17227. ASSERT_TRUE(send_request(1, req, &res, port));
  17228. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17229. // A name within the cap is honored; one declared past the cap is dropped.
  17230. EXPECT_TRUE(observed_within_cap);
  17231. EXPECT_FALSE(observed_past_cap);
  17232. }
  17233. // A direct client that is not listed in trusted_proxies must not be able to
  17234. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17235. // the peer address on the actual TCP connection determines whether the
  17236. // header is honored.
  17237. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17238. Server svr;
  17239. // Deliberately does NOT include the loopback address the test client
  17240. // actually connects from, so the direct connection is not a trusted proxy.
  17241. svr.set_trusted_proxies({"203.0.113.66"});
  17242. std::string observed_remote_addr;
  17243. svr.Get("/ip", [&](const Request &req, Response &res) {
  17244. observed_remote_addr = req.remote_addr;
  17245. res.set_content("ok", "text/plain");
  17246. });
  17247. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17248. auto se = detail::scope_exit([&] {
  17249. svr.stop();
  17250. t.join();
  17251. ASSERT_FALSE(svr.is_running());
  17252. });
  17253. svr.wait_until_ready();
  17254. Client cli(HOST, PORT);
  17255. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17257. EXPECT_EQ(StatusCode::OK_200, res->status);
  17258. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17259. // ignored entirely and the real connection-level address retained.
  17260. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17261. observed_remote_addr == "127.0.0.1");
  17262. }
  17263. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17264. Server svr;
  17265. std::string observed_remote_addr;
  17266. std::string observed_xff;
  17267. svr.Get("/ip", [&](const Request &req, Response &res) {
  17268. observed_remote_addr = req.remote_addr;
  17269. observed_xff = req.get_header_value("X-Forwarded-For");
  17270. res.set_content("ok", "text/plain");
  17271. });
  17272. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17273. auto se = detail::scope_exit([&] {
  17274. svr.stop();
  17275. t.join();
  17276. ASSERT_FALSE(svr.is_running());
  17277. });
  17278. svr.wait_until_ready();
  17279. Client cli(HOST, PORT);
  17280. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17282. EXPECT_EQ(StatusCode::OK_200, res->status);
  17283. EXPECT_EQ(observed_xff, "203.0.113.66");
  17284. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17285. observed_remote_addr == "127.0.0.1");
  17286. }
  17287. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17288. Server svr;
  17289. svr.set_trusted_proxies({"203.0.113.66"});
  17290. std::string observed_remote_addr;
  17291. std::string observed_xff;
  17292. svr.Get("/ip", [&](const Request &req, Response &res) {
  17293. observed_remote_addr = req.remote_addr;
  17294. observed_xff = req.get_header_value("X-Forwarded-For");
  17295. res.set_content("ok", "text/plain");
  17296. });
  17297. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17298. auto se = detail::scope_exit([&] {
  17299. svr.stop();
  17300. t.join();
  17301. ASSERT_FALSE(svr.is_running());
  17302. });
  17303. svr.wait_until_ready();
  17304. Client cli(HOST, PORT);
  17305. auto res = cli.Get("/ip");
  17306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17307. EXPECT_EQ(StatusCode::OK_200, res->status);
  17308. EXPECT_EQ(observed_xff, "");
  17309. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17310. observed_remote_addr == "127.0.0.1");
  17311. }
  17312. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17313. Server svr;
  17314. // Include the loopback address the test client actually connects from, so
  17315. // the direct connection itself is recognized as the trusted proxy hop.
  17316. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17317. std::string observed_remote_addr;
  17318. std::string observed_xff;
  17319. svr.Get("/ip", [&](const Request &req, Response &res) {
  17320. observed_remote_addr = req.remote_addr;
  17321. observed_xff = req.get_header_value("X-Forwarded-For");
  17322. res.set_content("ok", "text/plain");
  17323. });
  17324. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17325. auto se = detail::scope_exit([&] {
  17326. svr.stop();
  17327. t.join();
  17328. ASSERT_FALSE(svr.is_running());
  17329. });
  17330. svr.wait_until_ready();
  17331. Client cli(HOST, PORT);
  17332. auto res = cli.Get(
  17333. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17335. EXPECT_EQ(StatusCode::OK_200, res->status);
  17336. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17337. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17338. }
  17339. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17340. Server svr;
  17341. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17342. std::string observed_remote_addr;
  17343. std::string observed_xff;
  17344. svr.Get("/ip", [&](const Request &req, Response &res) {
  17345. observed_remote_addr = req.remote_addr;
  17346. observed_xff = req.get_header_value("X-Forwarded-For");
  17347. res.set_content("ok", "text/plain");
  17348. });
  17349. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17350. auto se = detail::scope_exit([&] {
  17351. svr.stop();
  17352. t.join();
  17353. ASSERT_FALSE(svr.is_running());
  17354. });
  17355. svr.wait_until_ready();
  17356. Client cli(HOST, PORT);
  17357. auto res = cli.Get(
  17358. "/ip",
  17359. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17361. EXPECT_EQ(StatusCode::OK_200, res->status);
  17362. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17363. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17364. }
  17365. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17366. Server svr;
  17367. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17368. std::string observed_remote_addr;
  17369. std::string observed_xff;
  17370. svr.Get("/ip", [&](const Request &req, Response &res) {
  17371. observed_remote_addr = req.remote_addr;
  17372. observed_xff = req.get_header_value("X-Forwarded-For");
  17373. res.set_content("ok", "text/plain");
  17374. });
  17375. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17376. auto se = detail::scope_exit([&] {
  17377. svr.stop();
  17378. t.join();
  17379. ASSERT_FALSE(svr.is_running());
  17380. });
  17381. svr.wait_until_ready();
  17382. Client cli(HOST, PORT);
  17383. auto res = cli.Get(
  17384. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17386. EXPECT_EQ(StatusCode::OK_200, res->status);
  17387. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17388. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17389. // and must not be selected.
  17390. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17391. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17392. }
  17393. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17394. Server svr;
  17395. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17396. std::string observed_remote_addr;
  17397. svr.Get("/ip", [&](const Request &req, Response &res) {
  17398. observed_remote_addr = req.remote_addr;
  17399. res.set_content("ok", "text/plain");
  17400. });
  17401. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17402. auto se = detail::scope_exit([&] {
  17403. svr.stop();
  17404. t.join();
  17405. ASSERT_FALSE(svr.is_running());
  17406. });
  17407. svr.wait_until_ready();
  17408. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17409. // a forged address and the trusted proxy's own address; the forged value must
  17410. // not win over the address the trusted proxy actually recorded.
  17411. Client cli(HOST, PORT);
  17412. auto res = cli.Get(
  17413. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17415. EXPECT_EQ(StatusCode::OK_200, res->status);
  17416. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17417. }
  17418. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17419. Server svr;
  17420. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17421. std::string observed_remote_addr;
  17422. std::string observed_xff;
  17423. svr.Get("/ip", [&](const Request &req, Response &res) {
  17424. observed_remote_addr = req.remote_addr;
  17425. observed_xff = req.get_header_value("X-Forwarded-For");
  17426. res.set_content("ok", "text/plain");
  17427. });
  17428. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17429. auto se = detail::scope_exit([&] {
  17430. svr.stop();
  17431. t.join();
  17432. ASSERT_FALSE(svr.is_running());
  17433. });
  17434. svr.wait_until_ready();
  17435. Client cli(HOST, PORT);
  17436. auto res = cli.Get(
  17437. "/ip",
  17438. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17440. EXPECT_EQ(StatusCode::OK_200, res->status);
  17441. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17442. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17443. }
  17444. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17445. Server svr;
  17446. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17447. std::string observed_remote_addr;
  17448. std::string observed_xff;
  17449. svr.Get("/ip", [&](const Request &req, Response &res) {
  17450. observed_remote_addr = req.remote_addr;
  17451. observed_xff = req.get_header_value("X-Forwarded-For");
  17452. res.set_content("ok", "text/plain");
  17453. });
  17454. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17455. auto se = detail::scope_exit([&] {
  17456. svr.stop();
  17457. t.join();
  17458. ASSERT_FALSE(svr.is_running());
  17459. });
  17460. svr.wait_until_ready();
  17461. std::string raw_req =
  17462. "GET /ip HTTP/1.1\r\n"
  17463. "Host: localhost\r\n"
  17464. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17465. "Connection: close\r\n"
  17466. "\r\n";
  17467. std::string out;
  17468. ASSERT_TRUE(send_request(5, raw_req, &out));
  17469. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17470. // Header parser trims surrounding whitespace of the header value
  17471. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17472. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17473. }
  17474. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17475. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17476. // their own X-Forwarded-For as a separate field line rather than extending the
  17477. // one the client sent, so every occurrence has to be taken into account.
  17478. // Reading only the first one hands back the address the client chose.
  17479. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17480. Server svr;
  17481. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17482. std::string observed_remote_addr;
  17483. size_t observed_xff_count = 0;
  17484. svr.Get("/ip", [&](const Request &req, Response &res) {
  17485. observed_remote_addr = req.remote_addr;
  17486. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17487. res.set_content("ok", "text/plain");
  17488. });
  17489. auto port = svr.bind_to_any_port(HOST);
  17490. thread t = thread([&]() { svr.listen_after_bind(); });
  17491. auto se = detail::scope_exit([&] {
  17492. svr.stop();
  17493. t.join();
  17494. ASSERT_FALSE(svr.is_running());
  17495. });
  17496. svr.wait_until_ready();
  17497. // The client supplies the first field line; the trusted proxy appends the
  17498. // address it observed as a second one.
  17499. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17500. "Host: localhost\r\n"
  17501. "X-Forwarded-For: 1.2.3.4\r\n"
  17502. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17503. "Connection: close\r\n"
  17504. "\r\n";
  17505. std::string out;
  17506. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17507. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17508. EXPECT_EQ(observed_xff_count, 2U);
  17509. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17510. // The same chain spread over one field line per hop derives the same client
  17511. // address, i.e. the split and the comma-joined representations agree.
  17512. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17513. "Host: localhost\r\n"
  17514. "X-Forwarded-For: 1.2.3.4\r\n"
  17515. "X-Forwarded-For: 198.51.100.23\r\n"
  17516. "X-Forwarded-For: 192.0.2.45\r\n"
  17517. "Connection: close\r\n"
  17518. "\r\n";
  17519. out.clear();
  17520. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17521. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17522. EXPECT_EQ(observed_xff_count, 3U);
  17523. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17524. }
  17525. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17526. // crash the server (it used to call front() on an empty vector inside
  17527. // get_client_ip). The connection-level remote address must be retained instead.
  17528. static void run_malformed_xff_test(const std::string &xff_value) {
  17529. Server svr;
  17530. svr.set_trusted_proxies({"192.0.2.45"});
  17531. std::string observed_remote_addr;
  17532. svr.Get("/ip", [&](const Request &req, Response &res) {
  17533. observed_remote_addr = req.remote_addr;
  17534. res.set_content("ok", "text/plain");
  17535. });
  17536. int port = 0;
  17537. thread t = thread([&]() {
  17538. port = svr.bind_to_any_port(HOST);
  17539. svr.listen_after_bind();
  17540. });
  17541. auto se = detail::scope_exit([&] {
  17542. svr.stop();
  17543. t.join();
  17544. ASSERT_FALSE(svr.is_running());
  17545. });
  17546. svr.wait_until_ready();
  17547. Client cli(HOST, port);
  17548. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17550. EXPECT_EQ(StatusCode::OK_200, res->status);
  17551. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17552. observed_remote_addr == "127.0.0.1");
  17553. }
  17554. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17555. run_malformed_xff_test("");
  17556. }
  17557. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17558. run_malformed_xff_test(",");
  17559. }
  17560. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17561. run_malformed_xff_test(", , ,");
  17562. }
  17563. // The same rule applies to Accept: a request whose acceptable types are spread
  17564. // over several field lines must be negotiated against all of them.
  17565. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17566. // case-insensitive connection options. Comparing the whole field value against
  17567. // one option misses a client that sends several of them, and misses every
  17568. // casing but the one written in the comparison.
  17569. //
  17570. // Sends req, reads the response, then reuses the same socket for a second
  17571. // request to find out whether the server kept the connection.
  17572. static void probe_connection_reuse(int port, const std::string &req,
  17573. bool *announced_close, bool *reusable) {
  17574. auto error = Error::Success;
  17575. auto sock = detail::create_client_socket(
  17576. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17577. /*connection_timeout_sec=*/5, 0,
  17578. /*read_timeout_sec=*/1, 0,
  17579. /*write_timeout_sec=*/5, 0, std::string(), error);
  17580. ASSERT_NE(sock, INVALID_SOCKET);
  17581. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17582. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17583. "Host: localhost\r\n"
  17584. "Connection: close\r\n"
  17585. "\r\n";
  17586. std::string first_response;
  17587. std::string second_response;
  17588. detail::process_client_socket(
  17589. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17590. [&](Stream &strm) {
  17591. if (strm.write(req.data(), req.size()) !=
  17592. static_cast<ssize_t>(req.size())) {
  17593. return false;
  17594. }
  17595. char buf[512];
  17596. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17597. // Headers plus the two-byte body of the handler below
  17598. while (reader.getline()) {
  17599. first_response += reader.ptr();
  17600. if (first_response.find("ok") != std::string::npos) { break; }
  17601. }
  17602. if (strm.write(second.data(), second.size()) !=
  17603. static_cast<ssize_t>(second.size())) {
  17604. return true;
  17605. }
  17606. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17607. while (reader2.getline()) {
  17608. second_response += reader2.ptr();
  17609. if (second_response.find("ok") != std::string::npos) { break; }
  17610. }
  17611. return true;
  17612. });
  17613. *announced_close =
  17614. first_response.find("Connection: close") != std::string::npos;
  17615. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17616. }
  17617. class ConnectionTokenTest : public ::testing::Test {
  17618. protected:
  17619. void SetUp() override {
  17620. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17621. res.set_content("ok", "text/plain");
  17622. });
  17623. port_ = svr_.bind_to_any_port(HOST);
  17624. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17625. svr_.wait_until_ready();
  17626. }
  17627. void TearDown() override {
  17628. svr_.stop();
  17629. if (thread_.joinable()) { thread_.join(); }
  17630. }
  17631. Server svr_;
  17632. int port_ = 0;
  17633. thread thread_;
  17634. };
  17635. // "close" alongside another option still closes the connection, and the
  17636. // response says so rather than leaving the peer to discover it.
  17637. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17638. bool announced_close = false;
  17639. bool reusable = true;
  17640. probe_connection_reuse(port_,
  17641. "GET /keepalive HTTP/1.1\r\n"
  17642. "Host: localhost\r\n"
  17643. "Connection: keep-alive, close\r\n"
  17644. "\r\n",
  17645. &announced_close, &reusable);
  17646. EXPECT_TRUE(announced_close);
  17647. EXPECT_FALSE(reusable);
  17648. }
  17649. // "close" split over two field lines is the same list, so it is honored too.
  17650. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17651. bool announced_close = false;
  17652. bool reusable = true;
  17653. probe_connection_reuse(port_,
  17654. "GET /keepalive HTTP/1.1\r\n"
  17655. "Host: localhost\r\n"
  17656. "Connection: keep-alive\r\n"
  17657. "Connection: close\r\n"
  17658. "\r\n",
  17659. &announced_close, &reusable);
  17660. EXPECT_TRUE(announced_close);
  17661. EXPECT_FALSE(reusable);
  17662. }
  17663. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17664. // keep-alive in the spelling everyone actually sends keeps its connection.
  17665. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17666. bool announced_close = false;
  17667. bool reusable = false;
  17668. probe_connection_reuse(port_,
  17669. "GET /keepalive HTTP/1.0\r\n"
  17670. "Host: localhost\r\n"
  17671. "Connection: keep-alive\r\n"
  17672. "\r\n",
  17673. &announced_close, &reusable);
  17674. EXPECT_FALSE(announced_close);
  17675. EXPECT_TRUE(reusable);
  17676. }
  17677. // A token the value merely contains is not the token itself.
  17678. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17679. bool announced_close = false;
  17680. bool reusable = false;
  17681. probe_connection_reuse(port_,
  17682. "GET /keepalive HTTP/1.1\r\n"
  17683. "Host: localhost\r\n"
  17684. "Connection: notclose\r\n"
  17685. "\r\n",
  17686. &announced_close, &reusable);
  17687. EXPECT_FALSE(announced_close);
  17688. EXPECT_TRUE(reusable);
  17689. }
  17690. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17691. Server svr;
  17692. std::vector<std::string> observed_types;
  17693. svr.Get("/", [&](const Request &req, Response &res) {
  17694. observed_types = req.accept_content_types;
  17695. res.set_content("ok", "text/plain");
  17696. });
  17697. auto port = svr.bind_to_any_port(HOST);
  17698. thread t = thread([&]() { svr.listen_after_bind(); });
  17699. auto se = detail::scope_exit([&] {
  17700. svr.stop();
  17701. t.join();
  17702. ASSERT_FALSE(svr.is_running());
  17703. });
  17704. svr.wait_until_ready();
  17705. Client cli(HOST, port);
  17706. Headers headers;
  17707. headers.emplace("Accept", "text/plain;q=0.5");
  17708. headers.emplace("Accept", "application/json");
  17709. auto res = cli.Get("/", headers);
  17710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17711. EXPECT_EQ(StatusCode::OK_200, res->status);
  17712. // Sorted by q-value, so the second field line's type comes first
  17713. ASSERT_EQ(2U, observed_types.size());
  17714. EXPECT_EQ("application/json", observed_types[0]);
  17715. EXPECT_EQ("text/plain", observed_types[1]);
  17716. }
  17717. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17718. // empty field line must not contribute a bare comma to the combined value.
  17719. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17720. Server svr;
  17721. std::vector<std::string> observed_types;
  17722. svr.Get("/", [&](const Request &req, Response &res) {
  17723. observed_types = req.accept_content_types;
  17724. res.set_content("ok", "text/plain");
  17725. });
  17726. auto port = svr.bind_to_any_port(HOST);
  17727. thread t = thread([&]() { svr.listen_after_bind(); });
  17728. auto se = detail::scope_exit([&] {
  17729. svr.stop();
  17730. t.join();
  17731. ASSERT_FALSE(svr.is_running());
  17732. });
  17733. svr.wait_until_ready();
  17734. // Empty first field line, then a real one
  17735. std::string raw_req = "GET / HTTP/1.1\r\n"
  17736. "Host: localhost\r\n"
  17737. "Accept:\r\n"
  17738. "Accept: application/json\r\n"
  17739. "Connection: close\r\n"
  17740. "\r\n";
  17741. std::string out;
  17742. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17743. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17744. ASSERT_EQ(1U, observed_types.size());
  17745. EXPECT_EQ("application/json", observed_types[0]);
  17746. }
  17747. // The skip in get_combined_header_value() is what keeps an empty field line
  17748. // from contributing a bare comma. Only a trailing empty field line exercises
  17749. // it: a leading one is already covered by the "combined is still empty" check,
  17750. // and parse_accept_header() now ignores the empty element either way, so the
  17751. // request-level test above can no longer tell the two apart.
  17752. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17753. Headers headers;
  17754. headers.emplace("Accept", "text/html");
  17755. headers.emplace("Accept", "");
  17756. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17757. headers.clear();
  17758. headers.emplace("Accept", "");
  17759. headers.emplace("Accept", "application/json");
  17760. EXPECT_EQ("application/json",
  17761. detail::get_combined_header_value(headers, "Accept"));
  17762. }
  17763. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17764. // An encoding offered on a later Accept-Encoding field line is still offered.
  17765. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17766. Server svr;
  17767. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17768. res.set_content(std::string(1024, 'x'), "text/plain");
  17769. });
  17770. auto port = svr.bind_to_any_port(HOST);
  17771. thread t = thread([&]() { svr.listen_after_bind(); });
  17772. auto se = detail::scope_exit([&] {
  17773. svr.stop();
  17774. t.join();
  17775. ASSERT_FALSE(svr.is_running());
  17776. });
  17777. svr.wait_until_ready();
  17778. Client cli(HOST, port);
  17779. cli.set_decompress(false);
  17780. Headers headers;
  17781. headers.emplace("Accept-Encoding", "identity");
  17782. headers.emplace("Accept-Encoding", "gzip");
  17783. auto res = cli.Get("/", headers);
  17784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17785. EXPECT_EQ(StatusCode::OK_200, res->status);
  17786. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17787. }
  17788. #endif
  17789. #ifndef _WIN32
  17790. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17791. Server svr;
  17792. svr.Post("/post", [&](const Request &req, Response &res) {
  17793. res.set_content(req.body, "text/plain");
  17794. });
  17795. svr.Put("/put", [&](const Request &req, Response &res) {
  17796. res.set_content(req.body, "text/plain");
  17797. });
  17798. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17799. res.set_content(req.body, "text/plain");
  17800. });
  17801. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17802. res.set_content(req.body, "text/plain");
  17803. });
  17804. thread t = thread([&]() { svr.listen(HOST, PORT); });
  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. std::string resp;
  17812. // POST without Content-Length
  17813. ASSERT_TRUE(send_request(5,
  17814. "POST /post HTTP/1.1\r\n"
  17815. "Host: localhost\r\n"
  17816. "Connection: close\r\n"
  17817. "\r\n",
  17818. &resp));
  17819. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17820. // PUT without Content-Length
  17821. resp.clear();
  17822. ASSERT_TRUE(send_request(5,
  17823. "PUT /put HTTP/1.1\r\n"
  17824. "Host: localhost\r\n"
  17825. "Connection: close\r\n"
  17826. "\r\n",
  17827. &resp));
  17828. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17829. // PATCH without Content-Length
  17830. resp.clear();
  17831. ASSERT_TRUE(send_request(5,
  17832. "PATCH /patch HTTP/1.1\r\n"
  17833. "Host: localhost\r\n"
  17834. "Connection: close\r\n"
  17835. "\r\n",
  17836. &resp));
  17837. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17838. // DELETE without Content-Length
  17839. resp.clear();
  17840. ASSERT_TRUE(send_request(5,
  17841. "DELETE /delete HTTP/1.1\r\n"
  17842. "Host: localhost\r\n"
  17843. "Connection: close\r\n"
  17844. "\r\n",
  17845. &resp));
  17846. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17847. }
  17848. #endif
  17849. //==============================================================================
  17850. // open_stream() Tests
  17851. //==============================================================================
  17852. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17853. std::string result;
  17854. char buf[8192];
  17855. ssize_t n;
  17856. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17857. result.append(buf, static_cast<size_t>(n));
  17858. }
  17859. return result;
  17860. }
  17861. // Mock stream for unit tests
  17862. class MockStream : public Stream {
  17863. public:
  17864. std::string data;
  17865. size_t pos = 0;
  17866. ssize_t error_after = -1; // -1 = no error
  17867. explicit MockStream(const std::string &d, ssize_t err = -1)
  17868. : data(d), error_after(err) {}
  17869. bool is_readable() const override { return true; }
  17870. bool wait_readable() const override { return true; }
  17871. bool wait_writable() const override { return true; }
  17872. ssize_t read(char *ptr, size_t size) override {
  17873. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17874. if (pos >= data.size()) return 0;
  17875. size_t limit =
  17876. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17877. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17878. std::memcpy(ptr, data.data() + pos, to_read);
  17879. pos += to_read;
  17880. return static_cast<ssize_t>(to_read);
  17881. }
  17882. ssize_t write(const char *, size_t) override { return -1; }
  17883. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17884. ip = "127.0.0.1";
  17885. port = 0;
  17886. }
  17887. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17888. ip = "127.0.0.1";
  17889. port = 0;
  17890. }
  17891. socket_t socket() const override { return INVALID_SOCKET; }
  17892. time_t duration() const override { return 0; }
  17893. };
  17894. TEST(StreamHandleTest, Basic) {
  17895. ClientImpl::StreamHandle handle;
  17896. EXPECT_FALSE(handle.is_valid());
  17897. handle.response = detail::make_unique<Response>();
  17898. handle.error = Error::Connection;
  17899. EXPECT_FALSE(handle.is_valid());
  17900. handle.error = Error::Success;
  17901. EXPECT_TRUE(handle.is_valid());
  17902. }
  17903. TEST(BodyReaderTest, Basic) {
  17904. MockStream stream("Hello, World!");
  17905. detail::BodyReader reader;
  17906. reader.stream = &stream;
  17907. reader.content_length = 13;
  17908. char buf[32];
  17909. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17910. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17911. EXPECT_TRUE(reader.eof);
  17912. }
  17913. TEST(BodyReaderTest, NoStream) {
  17914. detail::BodyReader reader;
  17915. char buf[32];
  17916. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17917. EXPECT_EQ(Error::Connection, reader.last_error);
  17918. }
  17919. TEST(BodyReaderTest, Error) {
  17920. MockStream stream("Hello, World!", 5);
  17921. detail::BodyReader reader;
  17922. reader.stream = &stream;
  17923. reader.content_length = 13;
  17924. char buf[32];
  17925. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17926. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17927. EXPECT_EQ(Error::Read, reader.last_error);
  17928. }
  17929. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17930. // Mock-based StreamHandle tests relying on private internals are removed.
  17931. class OpenStreamTest : public ::testing::Test {
  17932. protected:
  17933. void SetUp() override {
  17934. svr_.Get("/hello", [](const Request &, Response &res) {
  17935. res.set_content("Hello World!", "text/plain");
  17936. });
  17937. svr_.Get("/large", [](const Request &, Response &res) {
  17938. res.set_content(std::string(10000, 'X'), "text/plain");
  17939. });
  17940. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17941. res.set_content("Hello World!", "image/jpeg");
  17942. res.set_header("Content-Encoding", "UTF-8");
  17943. });
  17944. svr_.Get("/chunked", [](const Request &, Response &res) {
  17945. res.set_chunked_content_provider("text/plain",
  17946. [](size_t offset, DataSink &sink) {
  17947. if (offset < 15) {
  17948. sink.write("chunk", 5);
  17949. return true;
  17950. }
  17951. sink.done();
  17952. return true;
  17953. });
  17954. });
  17955. svr_.Get("/compressible", [](const Request &, Response &res) {
  17956. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17957. DataSink &sink) {
  17958. if (offset < 100 * 1024) {
  17959. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17960. sink.write(chunk.data(), chunk.size());
  17961. return true;
  17962. }
  17963. sink.done();
  17964. return true;
  17965. });
  17966. });
  17967. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17968. [](const Request & /*req*/, Response &res) {
  17969. auto i = new int(0);
  17970. res.set_header("Trailer", "Content-Length, X-Allowed");
  17971. res.set_chunked_content_provider(
  17972. "text/plain",
  17973. [i](size_t /*offset*/, DataSink &sink) {
  17974. switch (*i) {
  17975. case 0: sink.os << "123"; break;
  17976. case 1: sink.os << "456"; break;
  17977. case 2: sink.os << "789"; break;
  17978. case 3: {
  17979. sink.done_with_trailer(
  17980. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17981. } break;
  17982. }
  17983. (*i)++;
  17984. return true;
  17985. },
  17986. [i](bool success) {
  17987. EXPECT_TRUE(success);
  17988. delete i;
  17989. });
  17990. });
  17991. // Echo headers endpoint for header-related tests
  17992. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17993. std::string body;
  17994. for (const auto &h : req.headers) {
  17995. body.append(h.first);
  17996. body.push_back(':');
  17997. body.append(h.second);
  17998. body.push_back('\n');
  17999. }
  18000. res.set_content(body, "text/plain");
  18001. });
  18002. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18003. std::string body;
  18004. for (const auto &h : req.headers) {
  18005. body.append(h.first);
  18006. body.push_back(':');
  18007. body.append(h.second);
  18008. body.push_back('\n');
  18009. }
  18010. res.set_content(body, "text/plain");
  18011. });
  18012. port_ = svr_.bind_to_any_port("127.0.0.1");
  18013. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18014. svr_.wait_until_ready();
  18015. }
  18016. void TearDown() override {
  18017. svr_.stop();
  18018. if (thread_.joinable()) thread_.join();
  18019. }
  18020. Server svr_;
  18021. std::thread thread_;
  18022. int port_ = 0;
  18023. };
  18024. TEST_F(OpenStreamTest, Basic) {
  18025. Client cli("127.0.0.1", port_);
  18026. auto handle = cli.open_stream("GET", "/hello");
  18027. EXPECT_TRUE(handle.is_valid());
  18028. EXPECT_EQ("Hello World!", read_all(handle));
  18029. }
  18030. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18031. Client cli("127.0.0.1", port_);
  18032. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18033. ASSERT_TRUE(handle.is_valid());
  18034. EXPECT_EQ("Hello World!", read_all(handle));
  18035. }
  18036. TEST_F(OpenStreamTest, SmallBuffer) {
  18037. Client cli("127.0.0.1", port_);
  18038. auto handle = cli.open_stream("GET", "/hello");
  18039. std::string result;
  18040. char buf[4];
  18041. ssize_t n;
  18042. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18043. result.append(buf, static_cast<size_t>(n));
  18044. EXPECT_EQ("Hello World!", result);
  18045. }
  18046. TEST_F(OpenStreamTest, DefaultHeaders) {
  18047. Client cli("127.0.0.1", port_);
  18048. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18049. {
  18050. auto handle = cli.open_stream("GET", "/echo-headers");
  18051. ASSERT_TRUE(handle.is_valid());
  18052. auto body = read_all(handle);
  18053. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18054. std::string::npos);
  18055. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18056. std::string::npos);
  18057. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18058. }
  18059. // open_stream POST with body and no explicit content_type should NOT add
  18060. // text/plain Content-Type (behavior differs from non-streaming path), but
  18061. // should include Content-Length
  18062. {
  18063. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18064. ASSERT_TRUE(handle.is_valid());
  18065. auto body = read_all(handle);
  18066. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18067. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18068. }
  18069. // open_stream POST with explicit Content-Type should preserve it
  18070. {
  18071. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18072. {{"Content-Type", "application/custom"}},
  18073. "{}", "application/custom");
  18074. ASSERT_TRUE(handle.is_valid());
  18075. auto body = read_all(handle);
  18076. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18077. }
  18078. // User-specified User-Agent must not be overwritten for stream API
  18079. {
  18080. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18081. {{"User-Agent", "MyAgent/1.2"}});
  18082. ASSERT_TRUE(handle.is_valid());
  18083. auto body = read_all(handle);
  18084. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18085. }
  18086. }
  18087. TEST_F(OpenStreamTest, Large) {
  18088. Client cli("127.0.0.1", port_);
  18089. auto handle = cli.open_stream("GET", "/large");
  18090. EXPECT_EQ(10000u, read_all(handle).size());
  18091. }
  18092. TEST_F(OpenStreamTest, ConnectionError) {
  18093. Client cli("127.0.0.1", 9999);
  18094. auto handle = cli.open_stream("GET", "/hello");
  18095. EXPECT_FALSE(handle.is_valid());
  18096. }
  18097. TEST_F(OpenStreamTest, Chunked) {
  18098. Client cli("127.0.0.1", port_);
  18099. auto handle = cli.open_stream("GET", "/chunked");
  18100. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18101. "Transfer-Encoding") == "chunked");
  18102. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18103. }
  18104. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18105. Client cli("127.0.0.1", port_);
  18106. auto handle =
  18107. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18108. ASSERT_TRUE(handle.is_valid());
  18109. // Consume body to allow trailers to be received/parsed
  18110. auto body = read_all(handle);
  18111. // Explicitly parse trailers (ensure trailers are available for assertion)
  18112. handle.parse_trailers_if_needed();
  18113. EXPECT_EQ(std::string("123456789"), body);
  18114. // The response should include a Trailer header declaring both names
  18115. ASSERT_TRUE(handle.response);
  18116. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18117. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18118. handle.response->get_header_value("Trailer"));
  18119. // Prohibited trailer must not be present
  18120. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18121. // Allowed trailer should be present
  18122. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18123. EXPECT_EQ(std::string("yes"),
  18124. handle.response->get_trailer_value("X-Allowed"));
  18125. // Verify trailers are NOT present as regular headers
  18126. EXPECT_EQ(std::string(""),
  18127. handle.response->get_header_value("Content-Length"));
  18128. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18129. }
  18130. static std::thread serve_single_response(std::promise<int> &port_promise,
  18131. const std::string &response) {
  18132. return std::thread([&port_promise, response] {
  18133. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18134. default_socket_options(srv);
  18135. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18136. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18137. sockaddr_in addr{};
  18138. addr.sin_family = AF_INET;
  18139. addr.sin_port = htons(0); // Let OS assign a free port
  18140. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18141. int opt = 1;
  18142. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18143. #ifdef _WIN32
  18144. reinterpret_cast<const char *>(&opt),
  18145. #else
  18146. &opt,
  18147. #endif
  18148. sizeof(opt));
  18149. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18150. ::listen(srv, 1) != 0) {
  18151. port_promise.set_value(-1);
  18152. detail::close_socket(srv);
  18153. return;
  18154. }
  18155. socklen_t addr_len = sizeof(addr);
  18156. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18157. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18158. sockaddr_in cli_addr{};
  18159. socklen_t cli_len = sizeof(cli_addr);
  18160. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18161. if (cli != INVALID_SOCKET) {
  18162. // Read the complete HTTP request (until the blank line that terminates
  18163. // headers) before sending the response. If the server closes the socket
  18164. // while the client's request data is still unread in the kernel receive
  18165. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18166. // connection on both sides: it discards the client's receive buffer
  18167. // (which already holds our response) and causes any in-progress write on
  18168. // the client to fail with ECONNRESET. Reading all request data first
  18169. // ensures close() emits a graceful FIN.
  18170. {
  18171. char rbuf[256];
  18172. std::string req;
  18173. while (req.find("\r\n\r\n") == std::string::npos) {
  18174. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18175. if (n <= 0) { break; }
  18176. req.append(rbuf, static_cast<size_t>(n));
  18177. }
  18178. }
  18179. ::send(cli,
  18180. #ifdef _WIN32
  18181. static_cast<const char *>(response.c_str()),
  18182. static_cast<int>(response.size()),
  18183. #else
  18184. response.c_str(), response.size(),
  18185. #endif
  18186. 0);
  18187. detail::close_socket(cli);
  18188. }
  18189. detail::close_socket(srv);
  18190. });
  18191. }
  18192. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18193. #ifndef _WIN32
  18194. signal(SIGPIPE, SIG_IGN);
  18195. #endif
  18196. std::promise<int> port_promise;
  18197. auto port_future = port_promise.get_future();
  18198. auto server_thread =
  18199. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18200. "Content-Type: text/plain\r\n"
  18201. "Content-Length: not-a-number\r\n"
  18202. "Connection: close\r\n"
  18203. "\r\n"
  18204. "hello");
  18205. auto port = port_future.get();
  18206. ASSERT_GT(port, 0);
  18207. Client cli("127.0.0.1", port);
  18208. auto handle = cli.open_stream("GET", "/");
  18209. EXPECT_FALSE(handle.is_valid());
  18210. server_thread.join();
  18211. }
  18212. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18213. #ifndef _WIN32
  18214. signal(SIGPIPE, SIG_IGN);
  18215. #endif
  18216. std::promise<int> port_promise;
  18217. auto port_future = port_promise.get_future();
  18218. auto server_thread = serve_single_response(
  18219. port_promise, "HTTP/1.1 200 OK\r\n"
  18220. "Content-Type: text/plain\r\n"
  18221. "Content-Length: 99999999999999999999999999\r\n"
  18222. "Connection: close\r\n"
  18223. "\r\n"
  18224. "hello");
  18225. auto port = port_future.get();
  18226. ASSERT_GT(port, 0);
  18227. // Historically std::stoull would throw std::out_of_range here and crash
  18228. // the process, then parsing silently clamped to a bogus framing length and
  18229. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18230. // so the stream fails to open, matching the not-a-number case above. The
  18231. // process still must NOT terminate.
  18232. Client cli("127.0.0.1", port);
  18233. auto handle = cli.open_stream("GET", "/");
  18234. EXPECT_FALSE(handle.is_valid());
  18235. server_thread.join();
  18236. }
  18237. // Serves `response` to the single request `fn` makes with a fresh client.
  18238. template <typename Fn>
  18239. static void with_single_response(const std::string &response, Fn fn) {
  18240. #ifndef _WIN32
  18241. signal(SIGPIPE, SIG_IGN);
  18242. #endif
  18243. std::promise<int> port_promise;
  18244. auto port_future = port_promise.get_future();
  18245. auto server_thread = serve_single_response(port_promise, response);
  18246. auto se = detail::scope_exit([&] { server_thread.join(); });
  18247. auto port = port_future.get();
  18248. ASSERT_GT(port, 0);
  18249. Client cli("127.0.0.1", port);
  18250. fn(cli);
  18251. }
  18252. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18253. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18254. // the chunked coding and drop Content-Length, so a front-end that trusts
  18255. // Content-Length would disagree about where the body ends (response
  18256. // smuggling). The client must reject such a response.
  18257. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18258. for (const char *te : {"chunked", "gzip, chunked"}) {
  18259. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18260. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18261. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18262. "5\r\nhello\r\n0\r\n\r\n";
  18263. with_single_response(response, [&](Client &cli) {
  18264. auto res = cli.Get("/");
  18265. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18266. EXPECT_EQ(Error::Read, res.error()) << te;
  18267. });
  18268. with_single_response(response, [&](Client &cli) {
  18269. auto handle = cli.open_stream("GET", "/");
  18270. EXPECT_FALSE(handle.is_valid()) << te;
  18271. EXPECT_EQ(Error::Read, handle.error) << te;
  18272. });
  18273. }
  18274. }
  18275. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18276. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18277. // closing the connection (unlike a request, which must be rejected).
  18278. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18279. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18280. "Transfer-Encoding: chunked\r\n"
  18281. "Connection: close\r\n"
  18282. "\r\n"
  18283. "5\r\nhello\r\n0\r\n\r\n",
  18284. "HTTP/1.1 200 OK\r\n"
  18285. "Transfer-Encoding: gzip\r\n"
  18286. "Connection: close\r\n"
  18287. "\r\n"
  18288. "hello"}) {
  18289. with_single_response(response, [&](Client &cli) {
  18290. auto res = cli.Get("/");
  18291. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18292. EXPECT_EQ("hello", res->body);
  18293. });
  18294. with_single_response(response, [&](Client &cli) {
  18295. auto handle = cli.open_stream("GET", "/");
  18296. ASSERT_TRUE(handle.is_valid()) << response;
  18297. EXPECT_EQ("hello", read_all(handle));
  18298. });
  18299. }
  18300. }
  18301. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18302. // framing headers describe nothing to read and must not be rejected.
  18303. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18304. const std::string framing = "Content-Length: 5\r\n"
  18305. "Transfer-Encoding: chunked\r\n"
  18306. "Connection: close\r\n"
  18307. "\r\n";
  18308. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18309. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18310. });
  18311. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18312. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18313. });
  18314. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18315. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18316. with_single_response(response, [&](Client &cli) {
  18317. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18318. });
  18319. with_single_response(response, [&](Client &cli) {
  18320. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18321. });
  18322. }
  18323. }
  18324. // A payload max length of 0 means no limit, however the body is framed.
  18325. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18326. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18327. "Transfer-Encoding: chunked\r\n"
  18328. "\r\n"
  18329. "5\r\nhello\r\n0\r\n\r\n",
  18330. "HTTP/1.1 200 OK\r\n"
  18331. "Connection: close\r\n"
  18332. "\r\n"
  18333. "hello"}) {
  18334. with_single_response(response, [&](Client &cli) {
  18335. cli.set_payload_max_length(0);
  18336. auto res = cli.Get("/");
  18337. ASSERT_TRUE(res) << response;
  18338. EXPECT_EQ("hello", res->body) << response;
  18339. });
  18340. }
  18341. }
  18342. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18343. Server svr;
  18344. svr.set_payload_max_length(0);
  18345. svr.Post("/echo", [](const Request &req, Response &res) {
  18346. res.set_content(req.body, "text/plain");
  18347. });
  18348. auto port = svr.bind_to_any_port(HOST);
  18349. thread t = thread([&] { svr.listen_after_bind(); });
  18350. auto se = detail::scope_exit([&] {
  18351. svr.stop();
  18352. t.join();
  18353. ASSERT_FALSE(svr.is_running());
  18354. });
  18355. svr.wait_until_ready();
  18356. Client cli(HOST, port);
  18357. auto res = cli.Post(
  18358. "/echo",
  18359. [](size_t /*offset*/, DataSink &sink) {
  18360. sink.write("hello", 5);
  18361. sink.done();
  18362. return true;
  18363. },
  18364. "text/plain");
  18365. ASSERT_TRUE(res);
  18366. EXPECT_EQ(StatusCode::OK_200, res->status);
  18367. EXPECT_EQ("hello", res->body);
  18368. }
  18369. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18370. TEST_F(OpenStreamTest, Gzip) {
  18371. Client cli("127.0.0.1", port_);
  18372. auto handle = cli.open_stream("GET", "/compressible", {},
  18373. {{"Accept-Encoding", "gzip"}});
  18374. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18375. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18376. }
  18377. #endif
  18378. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18379. TEST_F(OpenStreamTest, Brotli) {
  18380. Client cli("127.0.0.1", port_);
  18381. auto handle =
  18382. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18383. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18384. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18385. }
  18386. #endif
  18387. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18388. TEST_F(OpenStreamTest, Zstd) {
  18389. Client cli("127.0.0.1", port_);
  18390. auto handle = cli.open_stream("GET", "/compressible", {},
  18391. {{"Accept-Encoding", "zstd"}});
  18392. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18393. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18394. }
  18395. #endif
  18396. #ifdef CPPHTTPLIB_SSL_ENABLED
  18397. class SSLOpenStreamTest : public ::testing::Test {
  18398. protected:
  18399. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18400. void SetUp() override {
  18401. svr_.Get("/hello", [](const Request &, Response &res) {
  18402. res.set_content("Hello SSL World!", "text/plain");
  18403. });
  18404. svr_.Get("/chunked", [](const Request &, Response &res) {
  18405. res.set_chunked_content_provider("text/plain",
  18406. [](size_t offset, DataSink &sink) {
  18407. if (offset < 15) {
  18408. sink.write("chunk", 5);
  18409. return true;
  18410. }
  18411. sink.done();
  18412. return true;
  18413. });
  18414. });
  18415. svr_.Post("/echo", [](const Request &req, Response &res) {
  18416. res.set_content(req.body, req.get_header_value("Content-Type"));
  18417. });
  18418. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18419. std::string body = req.body;
  18420. res.set_chunked_content_provider(
  18421. "text/plain", [body](size_t offset, DataSink &sink) {
  18422. if (offset < body.size()) {
  18423. sink.write(body.data() + offset, body.size() - offset);
  18424. }
  18425. sink.done();
  18426. return true;
  18427. });
  18428. });
  18429. port_ = svr_.bind_to_any_port("127.0.0.1");
  18430. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18431. svr_.wait_until_ready();
  18432. }
  18433. void TearDown() override {
  18434. svr_.stop();
  18435. if (thread_.joinable()) thread_.join();
  18436. }
  18437. SSLServer svr_;
  18438. std::thread thread_;
  18439. int port_ = 0;
  18440. };
  18441. TEST_F(SSLOpenStreamTest, Basic) {
  18442. SSLClient cli("127.0.0.1", port_);
  18443. cli.enable_server_certificate_verification(false);
  18444. auto handle = cli.open_stream("GET", "/hello");
  18445. ASSERT_TRUE(handle.is_valid());
  18446. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18447. }
  18448. TEST_F(SSLOpenStreamTest, Chunked) {
  18449. SSLClient cli("127.0.0.1", port_);
  18450. cli.enable_server_certificate_verification(false);
  18451. auto handle = cli.open_stream("GET", "/chunked");
  18452. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18453. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18454. "Transfer-Encoding") == "chunked");
  18455. auto body = read_all(handle);
  18456. EXPECT_EQ("chunkchunkchunk", body);
  18457. }
  18458. TEST_F(SSLOpenStreamTest, Post) {
  18459. SSLClient cli("127.0.0.1", port_);
  18460. cli.enable_server_certificate_verification(false);
  18461. auto handle =
  18462. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18463. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18464. EXPECT_EQ(200, handle.response->status);
  18465. auto body = read_all(handle);
  18466. EXPECT_EQ("Hello SSL POST", body);
  18467. }
  18468. TEST_F(SSLOpenStreamTest, PostChunked) {
  18469. SSLClient cli("127.0.0.1", port_);
  18470. cli.enable_server_certificate_verification(false);
  18471. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18472. "Chunked SSL Data", "text/plain");
  18473. ASSERT_TRUE(handle.is_valid());
  18474. EXPECT_EQ(200, handle.response->status);
  18475. auto body = read_all(handle);
  18476. EXPECT_EQ("Chunked SSL Data", body);
  18477. }
  18478. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18479. // Content-Length is terminated by the server closing the connection. When the
  18480. // SSL peer sends a close_notify after the body, the client must treat it as a
  18481. // clean EOF and return a successful response rather than an error.
  18482. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18483. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18484. ASSERT_TRUE(svr.is_valid());
  18485. svr.set_keep_alive_max_count(1);
  18486. const std::string expected_body = "Hello from connection-close response!";
  18487. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18488. res.set_content_provider("text/plain",
  18489. [&](size_t offset, DataSink &sink) -> bool {
  18490. if (offset < expected_body.size()) {
  18491. sink.write(expected_body.data() + offset,
  18492. expected_body.size() - offset);
  18493. }
  18494. sink.done();
  18495. return true;
  18496. });
  18497. });
  18498. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18499. auto se = detail::scope_exit([&] {
  18500. svr.stop();
  18501. listen_thread.join();
  18502. ASSERT_FALSE(svr.is_running());
  18503. });
  18504. svr.wait_until_ready();
  18505. SSLClient cli(HOST, PORT);
  18506. cli.enable_server_certificate_verification(false);
  18507. auto res = cli.Get("/no-content-length");
  18508. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18509. EXPECT_EQ(StatusCode::OK_200, res->status);
  18510. EXPECT_EQ(expected_body, res->body);
  18511. }
  18512. #endif // CPPHTTPLIB_SSL_ENABLED
  18513. //==============================================================================
  18514. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18515. // results for various scenarios.
  18516. //==============================================================================
  18517. TEST(ParityTest, GetVsOpenStream) {
  18518. Server svr;
  18519. const std::string path = "/parity";
  18520. const std::string content = "Parity test content: hello world";
  18521. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18522. res.set_content(content, "text/plain");
  18523. });
  18524. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18525. auto se = detail::scope_exit([&] {
  18526. svr.stop();
  18527. t.join();
  18528. ASSERT_FALSE(svr.is_running());
  18529. });
  18530. svr.wait_until_ready();
  18531. Client cli(HOST, PORT);
  18532. // Non-stream path
  18533. auto r1 = cli.Get(path);
  18534. ASSERT_TRUE(r1);
  18535. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18536. // Stream path
  18537. auto h = cli.open_stream("GET", path);
  18538. ASSERT_TRUE(h.is_valid());
  18539. EXPECT_EQ(r1->body, read_all(h));
  18540. }
  18541. // Helper to compress data with provided compressor type T
  18542. template <typename Compressor>
  18543. static std::string compress_payload_for_parity(const std::string &in) {
  18544. std::string out;
  18545. Compressor compressor;
  18546. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18547. [&](const char *data, size_t n) {
  18548. out.append(data, n);
  18549. return true;
  18550. });
  18551. EXPECT_TRUE(ok);
  18552. return out;
  18553. }
  18554. // Helper function for compression parity tests
  18555. template <typename Compressor>
  18556. static void test_compression_parity(const std::string &original,
  18557. const std::string &path,
  18558. const std::string &encoding) {
  18559. const std::string compressed =
  18560. compress_payload_for_parity<Compressor>(original);
  18561. Server svr;
  18562. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18563. res.set_content(compressed, "application/octet-stream");
  18564. res.set_header("Content-Encoding", encoding);
  18565. });
  18566. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18567. auto se = detail::scope_exit([&] {
  18568. svr.stop();
  18569. t.join();
  18570. ASSERT_FALSE(svr.is_running());
  18571. });
  18572. svr.wait_until_ready();
  18573. Client cli(HOST, PORT);
  18574. // Non-streaming
  18575. {
  18576. auto res = cli.Get(path);
  18577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18578. EXPECT_EQ(StatusCode::OK_200, res->status);
  18579. EXPECT_EQ(original, res->body);
  18580. }
  18581. // Streaming
  18582. {
  18583. auto h = cli.open_stream("GET", path);
  18584. ASSERT_TRUE(h.is_valid());
  18585. EXPECT_EQ(original, read_all(h));
  18586. }
  18587. }
  18588. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18589. TEST(ParityTest, Gzip) {
  18590. test_compression_parity<detail::gzip_compressor>(
  18591. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18592. }
  18593. #endif
  18594. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18595. TEST(ParityTest, Brotli) {
  18596. test_compression_parity<detail::brotli_compressor>(
  18597. "Hello, brotli parity test payload", "/parity-br", "br");
  18598. }
  18599. #endif
  18600. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18601. TEST(ParityTest, Zstd) {
  18602. test_compression_parity<detail::zstd_compressor>(
  18603. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18604. }
  18605. #endif
  18606. //==============================================================================
  18607. // New Stream API Tests
  18608. //==============================================================================
  18609. inline std::string read_body(httplib::stream::Result &result) {
  18610. std::string body;
  18611. while (result.next()) {
  18612. body.append(result.data(), result.size());
  18613. }
  18614. return body;
  18615. }
  18616. TEST(ClientConnectionTest, Basic) {
  18617. httplib::ClientConnection conn;
  18618. EXPECT_FALSE(conn.is_open());
  18619. conn.sock = 1;
  18620. EXPECT_TRUE(conn.is_open());
  18621. httplib::ClientConnection conn2(std::move(conn));
  18622. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18623. conn2.sock = INVALID_SOCKET;
  18624. }
  18625. // Unified test server for all stream::* tests
  18626. class StreamApiTest : public ::testing::Test {
  18627. protected:
  18628. void SetUp() override {
  18629. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18630. res.set_content("Hello World!", "text/plain");
  18631. });
  18632. svr_.Get("/echo-params",
  18633. [](const httplib::Request &req, httplib::Response &res) {
  18634. std::string r;
  18635. for (const auto &p : req.params) {
  18636. if (!r.empty()) r += "&";
  18637. r += p.first + "=" + p.second;
  18638. }
  18639. res.set_content(r, "text/plain");
  18640. });
  18641. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18642. res.set_content(req.body, req.get_header_value("Content-Type"));
  18643. });
  18644. svr_.Post("/echo-headers",
  18645. [](const httplib::Request &req, httplib::Response &res) {
  18646. std::string r;
  18647. for (const auto &h : req.headers)
  18648. r += h.first + ": " + h.second + "\n";
  18649. res.set_content(r, "text/plain");
  18650. });
  18651. svr_.Post("/echo-params",
  18652. [](const httplib::Request &req, httplib::Response &res) {
  18653. std::string r = "params:";
  18654. for (const auto &p : req.params)
  18655. r += p.first + "=" + p.second + ";";
  18656. res.set_content(r + " body:" + req.body, "text/plain");
  18657. });
  18658. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18659. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18660. });
  18661. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18662. res.set_content("PUT:" + req.body, "text/plain");
  18663. });
  18664. svr_.Patch("/echo",
  18665. [](const httplib::Request &req, httplib::Response &res) {
  18666. res.set_content("PATCH:" + req.body, "text/plain");
  18667. });
  18668. svr_.Delete(
  18669. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18670. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18671. "text/plain");
  18672. });
  18673. svr_.Get("/head-test",
  18674. [](const httplib::Request &, httplib::Response &res) {
  18675. res.set_content("body for HEAD", "text/plain");
  18676. });
  18677. svr_.Options("/options",
  18678. [](const httplib::Request &, httplib::Response &res) {
  18679. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18680. });
  18681. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18682. svr_.wait_until_ready();
  18683. }
  18684. void TearDown() override {
  18685. svr_.stop();
  18686. if (thread_.joinable()) thread_.join();
  18687. }
  18688. httplib::Server svr_;
  18689. std::thread thread_;
  18690. };
  18691. // stream::Get tests
  18692. TEST_F(StreamApiTest, GetBasic) {
  18693. httplib::Client cli(HOST, PORT);
  18694. auto result = httplib::stream::Get(cli, "/hello");
  18695. ASSERT_TRUE(result.is_valid());
  18696. EXPECT_EQ(200, result.status());
  18697. EXPECT_EQ("Hello World!", read_body(result));
  18698. }
  18699. TEST_F(StreamApiTest, GetWithParams) {
  18700. httplib::Client cli(HOST, PORT);
  18701. httplib::Params params{{"foo", "bar"}};
  18702. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18703. ASSERT_TRUE(result.is_valid());
  18704. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18705. }
  18706. TEST_F(StreamApiTest, GetConnectionError) {
  18707. httplib::Client cli(HOST, 9999);
  18708. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18709. }
  18710. TEST_F(StreamApiTest, Get404) {
  18711. httplib::Client cli(HOST, PORT);
  18712. auto result = httplib::stream::Get(cli, "/nonexistent");
  18713. EXPECT_TRUE(result.is_valid());
  18714. EXPECT_EQ(404, result.status());
  18715. }
  18716. // stream::Post tests
  18717. TEST_F(StreamApiTest, PostBasic) {
  18718. httplib::Client cli(HOST, PORT);
  18719. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18720. "application/json");
  18721. ASSERT_TRUE(result.is_valid());
  18722. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18723. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18724. }
  18725. TEST_F(StreamApiTest, PostWithHeaders) {
  18726. httplib::Client cli(HOST, PORT);
  18727. httplib::Headers headers{{"X-Custom", "value"}};
  18728. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18729. "text/plain");
  18730. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18731. }
  18732. TEST_F(StreamApiTest, PostWithParams) {
  18733. httplib::Client cli(HOST, PORT);
  18734. httplib::Params params{{"k", "v"}};
  18735. auto result =
  18736. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18737. auto body = read_body(result);
  18738. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18739. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18740. }
  18741. TEST_F(StreamApiTest, PostLarge) {
  18742. httplib::Client cli(HOST, PORT);
  18743. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18744. size_t total = 0;
  18745. while (result.next()) {
  18746. total += result.size();
  18747. }
  18748. EXPECT_EQ(100u * 1024u, total);
  18749. }
  18750. // stream::Put/Patch tests
  18751. TEST_F(StreamApiTest, PutAndPatch) {
  18752. httplib::Client cli(HOST, PORT);
  18753. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18754. EXPECT_EQ("PUT:test", read_body(put));
  18755. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18756. EXPECT_EQ("PATCH:test", read_body(patch));
  18757. }
  18758. // stream::Delete tests
  18759. TEST_F(StreamApiTest, Delete) {
  18760. httplib::Client cli(HOST, PORT);
  18761. auto del1 = httplib::stream::Delete(cli, "/resource");
  18762. EXPECT_EQ("Deleted", read_body(del1));
  18763. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18764. EXPECT_EQ("Deleted:data", read_body(del2));
  18765. }
  18766. // stream::Head/Options tests
  18767. TEST_F(StreamApiTest, HeadAndOptions) {
  18768. httplib::Client cli(HOST, PORT);
  18769. auto head = httplib::stream::Head(cli, "/head-test");
  18770. EXPECT_TRUE(head.is_valid());
  18771. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18772. auto opts = httplib::stream::Options(cli, "/options");
  18773. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18774. }
  18775. // SSL stream::* tests
  18776. #ifdef CPPHTTPLIB_SSL_ENABLED
  18777. class SSLStreamApiTest : public ::testing::Test {
  18778. protected:
  18779. void SetUp() override {
  18780. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18781. res.set_content("Hello SSL!", "text/plain");
  18782. });
  18783. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18784. res.set_content(req.body, "text/plain");
  18785. });
  18786. port_ = svr_.bind_to_any_port("127.0.0.1");
  18787. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18788. svr_.wait_until_ready();
  18789. }
  18790. void TearDown() override {
  18791. svr_.stop();
  18792. if (thread_.joinable()) thread_.join();
  18793. }
  18794. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18795. std::thread thread_;
  18796. int port_ = 0;
  18797. };
  18798. TEST_F(SSLStreamApiTest, GetAndPost) {
  18799. httplib::SSLClient cli("127.0.0.1", port_);
  18800. cli.enable_server_certificate_verification(false);
  18801. auto get = httplib::stream::Get(cli, "/hello");
  18802. EXPECT_EQ("Hello SSL!", read_body(get));
  18803. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18804. EXPECT_EQ("test", read_body(post));
  18805. }
  18806. #endif
  18807. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18808. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18809. // BodyReader
  18810. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18811. // Test that read timeout during streaming is detected
  18812. // Use a large content-length response where server delays mid-stream
  18813. Server svr;
  18814. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18815. // Send a large response with delay in the middle
  18816. res.set_content_provider(
  18817. 1000, // content_length
  18818. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18819. if (offset < 100) {
  18820. // Send first 100 bytes immediately
  18821. std::string data(100, 'A');
  18822. sink.write(data.c_str(), data.size());
  18823. return true;
  18824. }
  18825. // Then delay longer than client timeout
  18826. std::this_thread::sleep_for(std::chrono::seconds(3));
  18827. std::string data(900, 'B');
  18828. sink.write(data.c_str(), data.size());
  18829. return true;
  18830. });
  18831. });
  18832. auto port = 8091;
  18833. std::thread t([&]() { svr.listen("localhost", port); });
  18834. svr.wait_until_ready();
  18835. Client cli("localhost", port);
  18836. cli.set_read_timeout(1, 0); // 1 second timeout
  18837. auto handle = cli.open_stream("GET", "/slow-stream");
  18838. ASSERT_TRUE(handle.is_valid());
  18839. char buf[256];
  18840. ssize_t total = 0;
  18841. ssize_t n;
  18842. bool got_error = false;
  18843. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18844. total += n;
  18845. }
  18846. if (n < 0) {
  18847. got_error = true;
  18848. // Should be timeout or read error
  18849. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18850. handle.get_read_error() == Error::Read)
  18851. << "Actual error: " << to_string(handle.get_read_error());
  18852. }
  18853. // Either we got an error, or we got less data than expected
  18854. EXPECT_TRUE(got_error || total < 1000)
  18855. << "Expected timeout but got all " << total << " bytes";
  18856. svr.stop();
  18857. t.join();
  18858. }
  18859. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18860. // Test connection closed detection via BodyReader
  18861. Server svr;
  18862. std::atomic<bool> close_now{false};
  18863. svr.Get("/will-close", [&](const Request &, Response &res) {
  18864. res.set_content_provider(
  18865. 10000, // Large content_length that we won't fully send
  18866. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18867. if (offset < 100) {
  18868. std::string data(100, 'X');
  18869. sink.write(data.c_str(), data.size());
  18870. return true;
  18871. }
  18872. // Wait for signal then abort
  18873. while (!close_now) {
  18874. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18875. }
  18876. return false; // Abort - server will close connection
  18877. });
  18878. });
  18879. auto port = 8092;
  18880. std::thread t([&]() { svr.listen("localhost", port); });
  18881. svr.wait_until_ready();
  18882. Client cli("localhost", port);
  18883. auto handle = cli.open_stream("GET", "/will-close");
  18884. ASSERT_TRUE(handle.is_valid());
  18885. char buf[256];
  18886. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18887. EXPECT_GT(n, 0) << "First read should succeed";
  18888. // Signal server to close
  18889. close_now = true;
  18890. // Keep reading until error or EOF
  18891. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18892. // Keep reading
  18893. }
  18894. // Should get an error since content_length wasn't satisfied
  18895. if (n < 0) {
  18896. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18897. handle.get_read_error() == Error::Read)
  18898. << "Actual error: " << to_string(handle.get_read_error());
  18899. }
  18900. svr.stop();
  18901. t.join();
  18902. }
  18903. #ifdef CPPHTTPLIB_SSL_ENABLED
  18904. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18905. // Test that read timeout during SSL streaming is detected
  18906. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18907. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18908. res.set_content_provider(
  18909. 1000, "text/plain",
  18910. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18911. if (offset < 100) {
  18912. std::string data(100, 'A');
  18913. sink.write(data.c_str(), data.size());
  18914. return true;
  18915. }
  18916. std::this_thread::sleep_for(std::chrono::seconds(3));
  18917. std::string data(900, 'B');
  18918. sink.write(data.c_str(), data.size());
  18919. return true;
  18920. });
  18921. });
  18922. auto port = 8093;
  18923. std::thread t([&]() { svr.listen("localhost", port); });
  18924. svr.wait_until_ready();
  18925. SSLClient cli("localhost", port);
  18926. cli.enable_server_certificate_verification(false);
  18927. cli.set_read_timeout(1, 0); // 1 second timeout
  18928. auto handle = cli.open_stream("GET", "/slow-stream");
  18929. ASSERT_TRUE(handle.is_valid());
  18930. char buf[256];
  18931. ssize_t total = 0;
  18932. ssize_t n;
  18933. bool got_error = false;
  18934. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18935. total += n;
  18936. }
  18937. if (n < 0) {
  18938. got_error = true;
  18939. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18940. handle.get_read_error() == Error::Read)
  18941. << "Actual error: " << to_string(handle.get_read_error());
  18942. }
  18943. EXPECT_TRUE(got_error || total < 1000)
  18944. << "Expected timeout but got all " << total << " bytes";
  18945. svr.stop();
  18946. t.join();
  18947. }
  18948. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18949. // Test SSL connection closed detection
  18950. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18951. std::atomic<bool> close_now{false};
  18952. svr.Get("/will-close", [&](const Request &, Response &res) {
  18953. res.set_content_provider(
  18954. 10000, "text/plain",
  18955. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18956. if (offset < 100) {
  18957. std::string data(100, 'X');
  18958. sink.write(data.c_str(), data.size());
  18959. return true;
  18960. }
  18961. while (!close_now) {
  18962. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18963. }
  18964. return false;
  18965. });
  18966. });
  18967. auto port = 8094;
  18968. std::thread t([&]() { svr.listen("localhost", port); });
  18969. svr.wait_until_ready();
  18970. SSLClient cli("localhost", port);
  18971. cli.enable_server_certificate_verification(false);
  18972. auto handle = cli.open_stream("GET", "/will-close");
  18973. ASSERT_TRUE(handle.is_valid());
  18974. char buf[256];
  18975. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18976. EXPECT_GT(n, 0);
  18977. // Signal server to close
  18978. close_now = true;
  18979. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18980. // Keep reading
  18981. }
  18982. if (n < 0) {
  18983. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18984. handle.get_read_error() == Error::Read)
  18985. << "Actual error: " << to_string(handle.get_read_error());
  18986. }
  18987. svr.stop();
  18988. t.join();
  18989. }
  18990. #endif
  18991. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18992. using namespace httplib;
  18993. // Create a test file
  18994. const char *fname = "etag_testfile.txt";
  18995. const char *content = "etag-content";
  18996. {
  18997. std::ofstream ofs(fname);
  18998. ofs << content;
  18999. ASSERT_TRUE(ofs.good());
  19000. }
  19001. Server svr;
  19002. svr.set_mount_point("/static", ".");
  19003. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19004. svr.wait_until_ready();
  19005. Client cli(HOST, PORT);
  19006. // First request: should get 200 with ETag header
  19007. auto res1 = cli.Get("/static/etag_testfile.txt");
  19008. ASSERT_TRUE(res1);
  19009. ASSERT_EQ(200, res1->status);
  19010. ASSERT_TRUE(res1->has_header("ETag"));
  19011. std::string etag = res1->get_header_value("ETag");
  19012. EXPECT_FALSE(etag.empty());
  19013. // Verify ETag format: W/"hex-hex"
  19014. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19015. EXPECT_EQ('W', etag[0]);
  19016. EXPECT_EQ('/', etag[1]);
  19017. EXPECT_EQ('"', etag[2]);
  19018. EXPECT_EQ('"', etag.back());
  19019. // Exact match: expect 304 Not Modified
  19020. Headers h2 = {{"If-None-Match", etag}};
  19021. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19022. ASSERT_TRUE(res2);
  19023. EXPECT_EQ(304, res2->status);
  19024. // Wildcard match: expect 304 Not Modified
  19025. Headers h3 = {{"If-None-Match", "*"}};
  19026. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19027. ASSERT_TRUE(res3);
  19028. EXPECT_EQ(304, res3->status);
  19029. // Non-matching ETag: expect 200
  19030. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19031. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19032. ASSERT_TRUE(res4);
  19033. EXPECT_EQ(200, res4->status);
  19034. // Multiple ETags with one matching: expect 304
  19035. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19036. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19037. ASSERT_TRUE(res5);
  19038. EXPECT_EQ(304, res5->status);
  19039. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19040. // that equivalent to the single comma-separated list above, so the match on
  19041. // the second line must still be found.
  19042. Headers h6;
  19043. h6.emplace("If-None-Match", "W/\"other\"");
  19044. h6.emplace("If-None-Match", etag);
  19045. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19046. ASSERT_TRUE(res6);
  19047. EXPECT_EQ(304, res6->status);
  19048. svr.stop();
  19049. t.join();
  19050. std::remove(fname);
  19051. }
  19052. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19053. using namespace httplib;
  19054. Server svr;
  19055. svr.set_mount_point("/static", ".");
  19056. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19057. svr.wait_until_ready();
  19058. Client cli(HOST, PORT);
  19059. // Send If-None-Match: * to a non-existent file
  19060. Headers h = {{"If-None-Match", "*"}};
  19061. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19063. EXPECT_EQ(404, res->status);
  19064. svr.stop();
  19065. t.join();
  19066. }
  19067. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19068. using namespace httplib;
  19069. // Create a test file
  19070. const char *fname = "etag_boundary_testfile.txt";
  19071. const char *content = "boundary-test";
  19072. {
  19073. std::ofstream ofs(fname);
  19074. ofs << content;
  19075. ASSERT_TRUE(ofs.good());
  19076. }
  19077. Server svr;
  19078. svr.set_mount_point("/static", ".");
  19079. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19080. svr.wait_until_ready();
  19081. Client cli(HOST, PORT);
  19082. // Get the actual ETag
  19083. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19084. ASSERT_TRUE(res1);
  19085. ASSERT_EQ(200, res1->status);
  19086. ASSERT_TRUE(res1->has_header("ETag"));
  19087. std::string etag = res1->get_header_value("ETag");
  19088. // Test 1: Very long ETag value (longer than actual ETag)
  19089. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19090. Headers h1 = {{"If-None-Match", "W/"
  19091. "\"very-long-etag-value-that-is-much-longer-"
  19092. "than-the-actual-etag-value\""}};
  19093. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19094. ASSERT_TRUE(res2);
  19095. EXPECT_EQ(200, res2->status); // Should not match
  19096. // Test 2: Long string followed by wildcard
  19097. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19098. // string)
  19099. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19100. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19101. ASSERT_TRUE(res3);
  19102. EXPECT_EQ(304, res3->status); // Should match on "*"
  19103. // Test 3: Wildcard followed by long string
  19104. // Should match on "*" immediately and return 304
  19105. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19106. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19107. ASSERT_TRUE(res4);
  19108. EXPECT_EQ(304, res4->status); // Should match on "*"
  19109. // Test 4: Multiple long non-matching values
  19110. // Should NOT match and return 200 (test that all comparisons are safe)
  19111. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19112. "W/\"second-long-non-matching-value\", "
  19113. "W/\"third-long-non-matching-value\""}};
  19114. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19115. ASSERT_TRUE(res5);
  19116. EXPECT_EQ(200, res5->status); // Should not match
  19117. // Test 5: Single character that is not "*" (edge case)
  19118. Headers h5 = {{"If-None-Match", "X"}};
  19119. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19120. ASSERT_TRUE(res6);
  19121. EXPECT_EQ(200, res6->status); // Should not match
  19122. svr.stop();
  19123. t.join();
  19124. std::remove(fname);
  19125. }
  19126. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19127. using namespace httplib;
  19128. // Create a test file
  19129. const char *fname = "ims_testfile.txt";
  19130. const char *content = "if-modified-since-test";
  19131. {
  19132. std::ofstream ofs(fname);
  19133. ofs << content;
  19134. ASSERT_TRUE(ofs.good());
  19135. }
  19136. Server svr;
  19137. svr.set_mount_point("/static", ".");
  19138. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19139. svr.wait_until_ready();
  19140. Client cli(HOST, PORT);
  19141. // First request: should get 200 with Last-Modified header
  19142. auto res1 = cli.Get("/static/ims_testfile.txt");
  19143. ASSERT_TRUE(res1);
  19144. ASSERT_EQ(200, res1->status);
  19145. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19146. std::string last_modified = res1->get_header_value("Last-Modified");
  19147. EXPECT_FALSE(last_modified.empty());
  19148. // If-Modified-Since with same time: expect 304
  19149. Headers h2 = {{"If-Modified-Since", last_modified}};
  19150. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19151. ASSERT_TRUE(res2);
  19152. EXPECT_EQ(304, res2->status);
  19153. // If-Modified-Since with future time: expect 304
  19154. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19155. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19156. ASSERT_TRUE(res3);
  19157. EXPECT_EQ(304, res3->status);
  19158. // If-Modified-Since with past time: expect 200
  19159. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19160. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19161. ASSERT_TRUE(res4);
  19162. EXPECT_EQ(200, res4->status);
  19163. // If-None-Match takes precedence over If-Modified-Since
  19164. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19165. ASSERT_TRUE(res1->has_header("ETag"));
  19166. std::string etag = res1->get_header_value("ETag");
  19167. Headers h5 = {{"If-None-Match", etag},
  19168. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19169. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19170. ASSERT_TRUE(res5);
  19171. EXPECT_EQ(304, res5->status);
  19172. svr.stop();
  19173. t.join();
  19174. std::remove(fname);
  19175. }
  19176. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19177. using namespace httplib;
  19178. Server svr;
  19179. // Endpoint that returns compressible content
  19180. svr.Get("/compressible", [](const Request &, Response &res) {
  19181. // Return a large enough body to trigger compression
  19182. std::string body(1000, 'a');
  19183. res.set_content(body, "text/plain");
  19184. });
  19185. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19186. svr.wait_until_ready();
  19187. Client cli(HOST, PORT);
  19188. // Request with gzip support: should get Vary header when compressed
  19189. cli.set_compress(true);
  19190. auto res1 = cli.Get("/compressible");
  19191. ASSERT_TRUE(res1);
  19192. EXPECT_EQ(200, res1->status);
  19193. // If Content-Encoding is set, Vary should also be set
  19194. if (res1->has_header("Content-Encoding")) {
  19195. EXPECT_TRUE(res1->has_header("Vary"));
  19196. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19197. }
  19198. // Request without Accept-Encoding header: should not have compression
  19199. Headers h_no_compress;
  19200. auto res2 = cli.Get("/compressible", h_no_compress);
  19201. ASSERT_TRUE(res2);
  19202. EXPECT_EQ(200, res2->status);
  19203. // Verify Vary header is present when compression is applied
  19204. // (the exact behavior depends on server configuration)
  19205. svr.stop();
  19206. t.join();
  19207. }
  19208. TEST(ETagTest, IfRangeWithETag) {
  19209. using namespace httplib;
  19210. // Create a test file with known content
  19211. const char *fname = "if_range_testfile.txt";
  19212. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19213. {
  19214. std::ofstream ofs(fname);
  19215. ofs << content;
  19216. ASSERT_TRUE(ofs.good());
  19217. }
  19218. Server svr;
  19219. svr.set_mount_point("/static", ".");
  19220. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19221. svr.wait_until_ready();
  19222. Client cli(HOST, PORT);
  19223. // First request: get ETag
  19224. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19225. ASSERT_TRUE(res1);
  19226. ASSERT_EQ(200, res1->status);
  19227. ASSERT_TRUE(res1->has_header("ETag"));
  19228. std::string etag = res1->get_header_value("ETag");
  19229. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19230. // Since our server generates weak ETags (W/"..."), If-Range with our
  19231. // ETag should NOT result in partial content - it should return full content.
  19232. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19233. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19234. ASSERT_TRUE(res2);
  19235. // Weak ETag in If-Range -> full content (200), not partial (206)
  19236. EXPECT_EQ(200, res2->status);
  19237. EXPECT_EQ(content, res2->body);
  19238. EXPECT_FALSE(res2->has_header("Content-Range"));
  19239. // Range request with non-matching If-Range (ETag): should get 200 (full
  19240. // content)
  19241. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19242. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19243. ASSERT_TRUE(res3);
  19244. EXPECT_EQ(200, res3->status);
  19245. EXPECT_EQ(content, res3->body);
  19246. EXPECT_FALSE(res3->has_header("Content-Range"));
  19247. // Range request with strong ETag (hypothetical - our server doesn't generate
  19248. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19249. // should return full content)
  19250. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19251. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19252. ASSERT_TRUE(res4);
  19253. EXPECT_EQ(200, res4->status);
  19254. EXPECT_EQ(content, res4->body);
  19255. EXPECT_FALSE(res4->has_header("Content-Range"));
  19256. svr.stop();
  19257. t.join();
  19258. std::remove(fname);
  19259. }
  19260. TEST(ETagTest, IfRangeWithDate) {
  19261. using namespace httplib;
  19262. // Create a test file
  19263. const char *fname = "if_range_date_testfile.txt";
  19264. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19265. {
  19266. std::ofstream ofs(fname);
  19267. ofs << content;
  19268. ASSERT_TRUE(ofs.good());
  19269. }
  19270. Server svr;
  19271. svr.set_mount_point("/static", ".");
  19272. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19273. svr.wait_until_ready();
  19274. Client cli(HOST, PORT);
  19275. // First request: get Last-Modified
  19276. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19277. ASSERT_TRUE(res1);
  19278. ASSERT_EQ(200, res1->status);
  19279. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19280. std::string last_modified = res1->get_header_value("Last-Modified");
  19281. // Range request with matching If-Range (date): should get 206
  19282. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19283. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19284. ASSERT_TRUE(res2);
  19285. EXPECT_EQ(206, res2->status);
  19286. EXPECT_EQ("FGHIJ", res2->body);
  19287. // Range request with old If-Range date: should get 200 (full content)
  19288. Headers h3 = {{"Range", "bytes=5-9"},
  19289. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19290. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19291. ASSERT_TRUE(res3);
  19292. EXPECT_EQ(200, res3->status);
  19293. EXPECT_EQ(content, res3->body);
  19294. // Range request with future If-Range date: should get 206
  19295. Headers h4 = {{"Range", "bytes=0-4"},
  19296. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19297. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19298. ASSERT_TRUE(res4);
  19299. EXPECT_EQ(206, res4->status);
  19300. EXPECT_EQ("ABCDE", res4->body);
  19301. svr.stop();
  19302. t.join();
  19303. std::remove(fname);
  19304. }
  19305. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19306. using namespace httplib;
  19307. const char *fname = "etag_malformed.txt";
  19308. const char *content = "malformed-etag";
  19309. {
  19310. std::ofstream ofs(fname);
  19311. ofs << content;
  19312. ASSERT_TRUE(ofs.good());
  19313. }
  19314. Server svr;
  19315. svr.set_mount_point("/static", ".");
  19316. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19317. svr.wait_until_ready();
  19318. Client cli(HOST, PORT);
  19319. // baseline: should get 200 and an ETag
  19320. auto res1 = cli.Get("/static/etag_malformed.txt");
  19321. ASSERT_TRUE(res1);
  19322. ASSERT_EQ(200, res1->status);
  19323. ASSERT_TRUE(res1->has_header("ETag"));
  19324. // Malformed ETag value (missing quotes) should be treated as non-matching
  19325. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19326. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19327. ASSERT_TRUE(res_bad);
  19328. EXPECT_EQ(200, res_bad->status);
  19329. // Whitespace-only header value should be considered invalid / non-matching
  19330. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19331. "Host: localhost\r\n"
  19332. "If-None-Match: \r\n"
  19333. "Connection: close\r\n"
  19334. "\r\n";
  19335. std::string out;
  19336. ASSERT_TRUE(send_request(5, raw_req, &out));
  19337. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19338. svr.stop();
  19339. t.join();
  19340. std::remove(fname);
  19341. }
  19342. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19343. using namespace httplib;
  19344. const char *fname = "ims_invalid_format.txt";
  19345. const char *content = "ims-bad-format";
  19346. {
  19347. std::ofstream ofs(fname);
  19348. ofs << content;
  19349. ASSERT_TRUE(ofs.good());
  19350. }
  19351. Server svr;
  19352. svr.set_mount_point("/static", ".");
  19353. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19354. svr.wait_until_ready();
  19355. Client cli(HOST, PORT);
  19356. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19357. ASSERT_TRUE(res1);
  19358. ASSERT_EQ(200, res1->status);
  19359. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19360. // If-Modified-Since with invalid format should not result in 304
  19361. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19362. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19363. ASSERT_TRUE(res_bad);
  19364. EXPECT_EQ(200, res_bad->status);
  19365. // If-Range with invalid date format should be treated as mismatch -> full
  19366. // content (200)
  19367. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19368. {"If-Range", "invalid-date"}};
  19369. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19370. ASSERT_TRUE(res_ifrange);
  19371. EXPECT_EQ(200, res_ifrange->status);
  19372. svr.stop();
  19373. t.join();
  19374. std::remove(fname);
  19375. }
  19376. TEST(ETagTest, IfRangeWithMalformedETag) {
  19377. using namespace httplib;
  19378. const char *fname = "ifrange_malformed.txt";
  19379. const std::string content = "0123456789";
  19380. {
  19381. std::ofstream ofs(fname);
  19382. ofs << content;
  19383. ASSERT_TRUE(ofs.good());
  19384. }
  19385. Server svr;
  19386. svr.set_mount_point("/static", ".");
  19387. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19388. svr.wait_until_ready();
  19389. Client cli(HOST, PORT);
  19390. // First request: get ETag
  19391. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19392. ASSERT_TRUE(res1);
  19393. ASSERT_EQ(200, res1->status);
  19394. ASSERT_TRUE(res1->has_header("ETag"));
  19395. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19396. // full content (200)
  19397. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19398. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19399. ASSERT_TRUE(res2);
  19400. EXPECT_EQ(200, res2->status);
  19401. EXPECT_EQ(content, res2->body);
  19402. svr.stop();
  19403. t.join();
  19404. std::remove(fname);
  19405. }
  19406. TEST(ETagTest, ExtremeLargeDateValues) {
  19407. using namespace httplib;
  19408. const char *fname = "ims_extreme_date.txt";
  19409. const char *content = "ims-extreme-date";
  19410. {
  19411. std::ofstream ofs(fname);
  19412. ofs << content;
  19413. ASSERT_TRUE(ofs.good());
  19414. }
  19415. Server svr;
  19416. svr.set_mount_point("/static", ".");
  19417. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19418. svr.wait_until_ready();
  19419. Client cli(HOST, PORT);
  19420. auto res1 = cli.Get(std::string("/static/") + fname);
  19421. ASSERT_TRUE(res1);
  19422. ASSERT_EQ(200, res1->status);
  19423. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19424. // Extremely large year that may overflow date parsing routines.
  19425. Headers h_large_date = {
  19426. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19427. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19428. ASSERT_TRUE(res_bad);
  19429. // Expect server to treat this as invalid/mismatch and return full content
  19430. EXPECT_EQ(200, res_bad->status);
  19431. // If-Range with extremely large date should be treated as mismatch -> full
  19432. // content (200)
  19433. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19434. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19435. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19436. ASSERT_TRUE(res_ifrange);
  19437. EXPECT_EQ(200, res_ifrange->status);
  19438. svr.stop();
  19439. t.join();
  19440. std::remove(fname);
  19441. }
  19442. TEST(ETagTest, NegativeFileModificationTime) {
  19443. using namespace httplib;
  19444. const char *fname = "ims_negative_mtime.txt";
  19445. const std::string content = "negative-mtime";
  19446. {
  19447. std::ofstream ofs(fname);
  19448. ofs << content;
  19449. ASSERT_TRUE(ofs.good());
  19450. }
  19451. // Try to set file mtime to a negative value. This may fail on some
  19452. // platforms/filesystems; if it fails, the test will still verify server
  19453. // behaves safely by performing a regular conditional request.
  19454. #if defined(__APPLE__) || defined(__linux__)
  19455. bool set_negative = false;
  19456. do {
  19457. struct timeval times[2];
  19458. // access time: now
  19459. times[0].tv_sec = time(nullptr);
  19460. times[0].tv_usec = 0;
  19461. // modification time: negative (e.g., -1)
  19462. times[1].tv_sec = -1;
  19463. times[1].tv_usec = 0;
  19464. if (utimes(fname, times) == 0) { set_negative = true; }
  19465. } while (0);
  19466. #else
  19467. bool set_negative = false;
  19468. #endif
  19469. Server svr;
  19470. svr.set_mount_point("/static", ".");
  19471. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19472. svr.wait_until_ready();
  19473. Client cli(HOST, PORT);
  19474. auto res1 = cli.Get(std::string("/static/") + fname);
  19475. ASSERT_TRUE(res1);
  19476. ASSERT_EQ(200, res1->status);
  19477. bool has_last_modified = res1->has_header("Last-Modified");
  19478. std::string last_modified;
  19479. if (has_last_modified) {
  19480. last_modified = res1->get_header_value("Last-Modified");
  19481. }
  19482. if (set_negative) {
  19483. // If we successfully set a negative mtime, ensure server returns a
  19484. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19485. // with an old date and ensure server handles it without crash.
  19486. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19487. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19488. ASSERT_TRUE(res2);
  19489. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19490. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19491. } else {
  19492. // Could not set negative mtime on this platform; fall back to verifying
  19493. // that normal invalid/malformed dates are treated safely (non-304).
  19494. Headers h_bad_date = {
  19495. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19496. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19497. ASSERT_TRUE(res_bad);
  19498. EXPECT_EQ(200, res_bad->status);
  19499. }
  19500. svr.stop();
  19501. t.join();
  19502. std::remove(fname);
  19503. }
  19504. //==============================================================================
  19505. // Integration Tests with Server
  19506. //==============================================================================
  19507. class SSEIntegrationTest : public ::testing::Test {
  19508. protected:
  19509. void SetUp() override {
  19510. stop_server_.store(false);
  19511. events_.clear();
  19512. server_ = httplib::detail::make_unique<Server>();
  19513. setup_server();
  19514. start_server();
  19515. }
  19516. void TearDown() override {
  19517. stop_server_.store(true);
  19518. event_cv_.notify_all();
  19519. server_->stop();
  19520. if (server_thread_.joinable()) { server_thread_.join(); }
  19521. }
  19522. void setup_server() {
  19523. // Simple SSE endpoint
  19524. server_->Get("/events", [this](const Request &req, Response &res) {
  19525. auto last_id = req.get_header_value("Last-Event-ID");
  19526. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19527. res.set_chunked_content_provider(
  19528. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19529. std::unique_lock<std::mutex> lock(event_mutex_);
  19530. if (event_cv_.wait_for(
  19531. lock, std::chrono::milliseconds(200), [this] {
  19532. return !events_.empty() || stop_server_.load();
  19533. })) {
  19534. if (stop_server_.load()) { return false; }
  19535. if (!events_.empty()) {
  19536. std::string event = events_.front();
  19537. events_.erase(events_.begin());
  19538. sink.write(event.data(), event.size());
  19539. return true;
  19540. }
  19541. }
  19542. return !stop_server_.load();
  19543. });
  19544. });
  19545. // Endpoint that returns error
  19546. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19547. res.status = 500;
  19548. res.set_content("Internal Server Error", "text/plain");
  19549. });
  19550. // Endpoint for custom event types
  19551. server_->Get("/custom-events", [](const Request &, Response &res) {
  19552. res.set_chunked_content_provider(
  19553. "text/event-stream", [](size_t offset, DataSink &sink) {
  19554. if (offset == 0) {
  19555. std::string event = "event: update\ndata: updated\n\n"
  19556. "event: delete\ndata: deleted\n\n";
  19557. sink.write(event.data(), event.size());
  19558. }
  19559. return false; // End stream after sending
  19560. });
  19561. });
  19562. }
  19563. void start_server() {
  19564. port_ = server_->bind_to_any_port(HOST);
  19565. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19566. // Wait for server to start
  19567. while (!server_->is_running()) {
  19568. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19569. }
  19570. }
  19571. int get_port() const { return port_; }
  19572. void send_event(const std::string &event) {
  19573. std::lock_guard<std::mutex> lock(event_mutex_);
  19574. events_.push_back(event);
  19575. event_cv_.notify_all();
  19576. }
  19577. std::unique_ptr<Server> server_;
  19578. std::thread server_thread_;
  19579. std::mutex event_mutex_;
  19580. std::condition_variable event_cv_;
  19581. std::vector<std::string> events_;
  19582. std::atomic<bool> stop_server_{false};
  19583. std::string last_received_event_id_;
  19584. int port_ = 0;
  19585. };
  19586. //==============================================================================
  19587. // SSE Parsing Tests
  19588. //==============================================================================
  19589. class SSEParsingTest : public SSEIntegrationTest {
  19590. protected:
  19591. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19592. // A trailing sentinel event tells when the whole stream has been parsed.
  19593. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19594. auto body = stream + "event: end\ndata: end\n\n";
  19595. server_->Get("/parse", [body](const Request &, Response &res) {
  19596. res.set_content(body, "text/event-stream");
  19597. });
  19598. return collect("/parse");
  19599. }
  19600. // Runs SSEClient against path until an "end" event arrives and returns the
  19601. // messages dispatched before it
  19602. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19603. Client client(HOST, get_port());
  19604. sse::SSEClient sse(client, path);
  19605. std::mutex mutex;
  19606. std::condition_variable cv;
  19607. std::vector<sse::SSEMessage> messages;
  19608. auto done = false;
  19609. sse.on_message([&](const sse::SSEMessage &msg) {
  19610. std::lock_guard<std::mutex> lock(mutex);
  19611. // Ignore a replay from a reconnect that races with stop()
  19612. if (!done) { messages.push_back(msg); }
  19613. });
  19614. sse.on_event("end", [&](const sse::SSEMessage &) {
  19615. std::lock_guard<std::mutex> lock(mutex);
  19616. done = true;
  19617. cv.notify_all();
  19618. });
  19619. sse.set_reconnect_interval(100);
  19620. sse.start_async();
  19621. {
  19622. std::unique_lock<std::mutex> lock(mutex);
  19623. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19624. }
  19625. sse.stop();
  19626. EXPECT_TRUE(done);
  19627. return messages;
  19628. }
  19629. };
  19630. TEST_F(SSEParsingTest, SingleLineData) {
  19631. auto msgs = parse("data: hello\n\n");
  19632. ASSERT_EQ(msgs.size(), 1u);
  19633. EXPECT_EQ(msgs[0].data, "hello");
  19634. EXPECT_EQ(msgs[0].event, "message");
  19635. }
  19636. TEST_F(SSEParsingTest, MultiLineData) {
  19637. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19638. ASSERT_EQ(msgs.size(), 1u);
  19639. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19640. }
  19641. TEST_F(SSEParsingTest, CustomEventType) {
  19642. auto msgs = parse("event: update\ndata: payload\n\n");
  19643. ASSERT_EQ(msgs.size(), 1u);
  19644. EXPECT_EQ(msgs[0].event, "update");
  19645. EXPECT_EQ(msgs[0].data, "payload");
  19646. }
  19647. TEST_F(SSEParsingTest, EventIdHandling) {
  19648. auto msgs = parse("id: 12345\ndata: test\n\n");
  19649. ASSERT_EQ(msgs.size(), 1u);
  19650. EXPECT_EQ(msgs[0].id, "12345");
  19651. }
  19652. TEST_F(SSEParsingTest, EmptyEventId) {
  19653. auto msgs = parse("id:\ndata: test\n\n");
  19654. ASSERT_EQ(msgs.size(), 1u);
  19655. EXPECT_EQ(msgs[0].id, "");
  19656. }
  19657. TEST_F(SSEParsingTest, CommentsIgnored) {
  19658. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19659. ASSERT_EQ(msgs.size(), 1u);
  19660. EXPECT_EQ(msgs[0].data, "hello");
  19661. EXPECT_EQ(msgs[0].event, "message");
  19662. }
  19663. TEST_F(SSEParsingTest, ColonInValue) {
  19664. auto msgs = parse("data: hello:world:test\n\n");
  19665. ASSERT_EQ(msgs.size(), 1u);
  19666. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19667. }
  19668. TEST_F(SSEParsingTest, FieldNameOnly) {
  19669. // A line without a colon is a field name with an empty value
  19670. auto msgs = parse("data\n\n");
  19671. ASSERT_EQ(msgs.size(), 1u);
  19672. EXPECT_EQ(msgs[0].data, "");
  19673. }
  19674. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19675. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19676. ASSERT_EQ(msgs.size(), 1u);
  19677. EXPECT_EQ(msgs[0].event, "update");
  19678. EXPECT_EQ(msgs[0].data, "hello");
  19679. }
  19680. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19681. auto msgs = parse("data\r\n\r\n");
  19682. ASSERT_EQ(msgs.size(), 1u);
  19683. EXPECT_EQ(msgs[0].data, "");
  19684. }
  19685. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19686. auto msgs = parse("event: update\rdata: hello\r\r");
  19687. ASSERT_EQ(msgs.size(), 1u);
  19688. EXPECT_EQ(msgs[0].event, "update");
  19689. EXPECT_EQ(msgs[0].data, "hello");
  19690. }
  19691. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19692. // Chunk boundaries fall inside every \r\n and right before the first one
  19693. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19694. "\n\r", "\nevent: end\ndata: end\n\n"};
  19695. server_->Get("/split", [chunks](const Request &, Response &res) {
  19696. auto i = std::make_shared<size_t>(0);
  19697. res.set_chunked_content_provider(
  19698. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19699. if (*i == chunks.size()) {
  19700. sink.done();
  19701. } else {
  19702. sink.write(chunks[*i].data(), chunks[*i].size());
  19703. (*i)++;
  19704. }
  19705. return true;
  19706. });
  19707. });
  19708. auto msgs = collect("/split");
  19709. ASSERT_EQ(msgs.size(), 1u);
  19710. EXPECT_EQ(msgs[0].event, "update");
  19711. EXPECT_EQ(msgs[0].data, "hello");
  19712. }
  19713. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19714. // Only a BOM at the start of the stream is ignored
  19715. auto msgs = parse("\xEF\xBB\xBF"
  19716. "data: first\n\n"
  19717. "\xEF\xBB\xBF"
  19718. "data: second\n\n");
  19719. ASSERT_EQ(msgs.size(), 1u);
  19720. EXPECT_EQ(msgs[0].data, "first");
  19721. }
  19722. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19723. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19724. ASSERT_EQ(msgs.size(), 1u);
  19725. EXPECT_EQ(msgs[0].data, "hello");
  19726. EXPECT_EQ(msgs[0].event, "message");
  19727. }
  19728. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19729. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19730. ASSERT_EQ(msgs.size(), 2u);
  19731. EXPECT_EQ(msgs[0].data, "hello");
  19732. EXPECT_EQ(msgs[1].data, "hello");
  19733. }
  19734. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19735. // An event without data is not dispatched, and its type must not leak
  19736. // into the next event
  19737. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19738. ASSERT_EQ(msgs.size(), 1u);
  19739. EXPECT_EQ(msgs[0].event, "message");
  19740. EXPECT_EQ(msgs[0].data, "hello");
  19741. }
  19742. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19743. // The first connection sends only an id; the second echoes back the
  19744. // Last-Event-ID it was reconnected with
  19745. std::atomic<int> connection_count{0};
  19746. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19747. if (connection_count++ == 0) {
  19748. res.set_content("id: 42\n\n", "text/event-stream");
  19749. } else {
  19750. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19751. "\n\nevent: end\ndata: end\n\n",
  19752. "text/event-stream");
  19753. }
  19754. });
  19755. auto msgs = collect("/id-only");
  19756. ASSERT_EQ(msgs.size(), 1u);
  19757. EXPECT_EQ(msgs[0].data, "42");
  19758. }
  19759. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19760. // The first connection sets an id and then clears it with an empty one; the
  19761. // second reports whether it was reconnected with a Last-Event-ID
  19762. std::atomic<int> connection_count{0};
  19763. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19764. if (connection_count++ == 0) {
  19765. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19766. "text/event-stream");
  19767. } else {
  19768. res.set_content(
  19769. std::string("data: ") +
  19770. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19771. "\n\nevent: end\ndata: end\n\n",
  19772. "text/event-stream");
  19773. }
  19774. });
  19775. auto msgs = collect("/id-clear");
  19776. ASSERT_EQ(msgs.size(), 3u);
  19777. EXPECT_EQ(msgs[0].id, "1");
  19778. EXPECT_EQ(msgs[1].id, "");
  19779. EXPECT_EQ(msgs[2].data, "not sent");
  19780. }
  19781. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19782. // The first connection sets an id and then sends ids that cannot be carried
  19783. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19784. // with
  19785. std::atomic<int> connection_count{0};
  19786. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19787. if (connection_count++ == 0) {
  19788. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19789. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19790. "text/event-stream");
  19791. } else {
  19792. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19793. "\n\nevent: end\ndata: end\n\n",
  19794. "text/event-stream");
  19795. }
  19796. });
  19797. auto msgs = collect("/id-unsendable");
  19798. ASSERT_EQ(msgs.size(), 1u);
  19799. EXPECT_EQ(msgs[0].data, "42");
  19800. }
  19801. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19802. auto msgs = parse("event: notification\nid: evt-42\n"
  19803. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19804. ASSERT_EQ(msgs.size(), 1u);
  19805. EXPECT_EQ(msgs[0].event, "notification");
  19806. EXPECT_EQ(msgs[0].id, "evt-42");
  19807. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19808. }
  19809. TEST(SSEMessageTest, Clear) {
  19810. sse::SSEMessage msg;
  19811. msg.event = "custom";
  19812. msg.data = "some data";
  19813. msg.id = "123";
  19814. msg.clear();
  19815. EXPECT_EQ(msg.event, "message");
  19816. EXPECT_EQ(msg.data, "");
  19817. EXPECT_EQ(msg.id, "");
  19818. }
  19819. //==============================================================================
  19820. // SSE Integration Tests
  19821. //==============================================================================
  19822. // Test: Successful connection and on_open callback
  19823. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19824. // Add a simple endpoint that sends one event and closes
  19825. server_->Get("/simple-event", [](const Request &, Response &res) {
  19826. res.set_chunked_content_provider(
  19827. "text/event-stream", [](size_t offset, DataSink &sink) {
  19828. if (offset == 0) {
  19829. std::string event = "data: hello\n\n";
  19830. sink.write(event.data(), event.size());
  19831. }
  19832. return false; // Close stream after sending
  19833. });
  19834. });
  19835. Client client("localhost", get_port());
  19836. sse::SSEClient sse(client, "/simple-event");
  19837. std::atomic<bool> open_called{false};
  19838. std::atomic<bool> message_received{false};
  19839. sse.on_open([&open_called]() { open_called.store(true); });
  19840. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19841. if (msg.data == "hello") { message_received.store(true); }
  19842. });
  19843. sse.set_reconnect_interval(100);
  19844. sse.set_max_reconnect_attempts(1);
  19845. // Start async
  19846. sse.start_async();
  19847. // Wait for message to be processed
  19848. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19849. sse.stop();
  19850. EXPECT_TRUE(open_called.load());
  19851. EXPECT_TRUE(message_received.load());
  19852. }
  19853. // Test: on_message callback
  19854. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19855. // Endpoint that sends multiple events then closes
  19856. server_->Get("/multi-event", [](const Request &, Response &res) {
  19857. res.set_chunked_content_provider(
  19858. "text/event-stream", [](size_t offset, DataSink &sink) {
  19859. if (offset == 0) {
  19860. std::string events = "data: message1\n\ndata: message2\n\n";
  19861. sink.write(events.data(), events.size());
  19862. }
  19863. return false;
  19864. });
  19865. });
  19866. Client client("localhost", get_port());
  19867. sse::SSEClient sse(client, "/multi-event");
  19868. std::vector<std::string> received_messages;
  19869. std::mutex messages_mutex;
  19870. sse.on_message([&](const sse::SSEMessage &msg) {
  19871. std::lock_guard<std::mutex> lock(messages_mutex);
  19872. received_messages.push_back(msg.data);
  19873. });
  19874. sse.set_reconnect_interval(100);
  19875. sse.set_max_reconnect_attempts(1);
  19876. sse.start_async();
  19877. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19878. sse.stop();
  19879. std::lock_guard<std::mutex> lock(messages_mutex);
  19880. EXPECT_GE(received_messages.size(), 2u);
  19881. if (received_messages.size() >= 2) {
  19882. EXPECT_EQ(received_messages[0], "message1");
  19883. EXPECT_EQ(received_messages[1], "message2");
  19884. }
  19885. }
  19886. // Test: on_event for specific types
  19887. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19888. Client client("localhost", get_port());
  19889. sse::SSEClient sse(client, "/custom-events");
  19890. std::atomic<bool> update_received{false};
  19891. std::atomic<bool> delete_received{false};
  19892. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19893. if (msg.data == "updated") { update_received.store(true); }
  19894. });
  19895. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19896. if (msg.data == "deleted") { delete_received.store(true); }
  19897. });
  19898. sse.set_max_reconnect_attempts(1);
  19899. sse.start_async();
  19900. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19901. sse.stop();
  19902. EXPECT_TRUE(update_received.load());
  19903. EXPECT_TRUE(delete_received.load());
  19904. }
  19905. // Test: on_error callback on connection failure
  19906. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19907. // Connect to a non-existent port
  19908. Client client("localhost", 59999);
  19909. sse::SSEClient sse(client, "/events");
  19910. std::atomic<bool> error_called{false};
  19911. Error received_error = Error::Success;
  19912. sse.on_error([&](Error err) {
  19913. error_called.store(true);
  19914. received_error = err;
  19915. });
  19916. sse.set_reconnect_interval(50);
  19917. sse.set_max_reconnect_attempts(1);
  19918. sse.start_async();
  19919. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19920. sse.stop();
  19921. EXPECT_TRUE(error_called.load());
  19922. EXPECT_NE(received_error, Error::Success);
  19923. }
  19924. // Test: Last-Event-ID header sent on reconnect
  19925. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19926. // Endpoint that sends event with ID
  19927. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19928. res.set_chunked_content_provider(
  19929. "text/event-stream", [](size_t offset, DataSink &sink) {
  19930. if (offset == 0) {
  19931. std::string event = "id: evt-123\ndata: test\n\n";
  19932. sink.write(event.data(), event.size());
  19933. }
  19934. return false;
  19935. });
  19936. });
  19937. Client client("localhost", get_port());
  19938. sse::SSEClient sse(client, "/event-with-id");
  19939. std::atomic<bool> id_received{false};
  19940. sse.on_message([&](const sse::SSEMessage &msg) {
  19941. if (!msg.id.empty()) { id_received.store(true); }
  19942. });
  19943. sse.set_reconnect_interval(100);
  19944. sse.set_max_reconnect_attempts(1);
  19945. sse.start_async();
  19946. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19947. sse.stop();
  19948. EXPECT_TRUE(id_received.load());
  19949. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19950. }
  19951. // Test: Manual stop
  19952. TEST_F(SSEIntegrationTest, ManualStop) {
  19953. // Endpoint that sends one event and stays open briefly
  19954. std::atomic<bool> handler_running{true};
  19955. server_->Get("/stay-open", [&handler_running](const Request &,
  19956. Response &res) {
  19957. res.set_chunked_content_provider(
  19958. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19959. if (offset == 0) {
  19960. std::string event = "data: connected\n\n";
  19961. sink.write(event.data(), event.size());
  19962. }
  19963. // Keep connection open while handler_running is true
  19964. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19965. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19966. }
  19967. return false;
  19968. });
  19969. });
  19970. Client client("localhost", get_port());
  19971. sse::SSEClient sse(client, "/stay-open");
  19972. std::atomic<bool> connected{false};
  19973. sse.on_open([&connected]() { connected.store(true); });
  19974. sse.set_reconnect_interval(100);
  19975. sse.set_max_reconnect_attempts(1);
  19976. sse.start_async();
  19977. // Wait for connection to establish
  19978. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19979. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19980. }
  19981. EXPECT_TRUE(connected.load());
  19982. EXPECT_TRUE(sse.is_connected());
  19983. // Signal handler to stop
  19984. handler_running.store(false);
  19985. // Stop SSE client
  19986. sse.stop();
  19987. EXPECT_FALSE(sse.is_connected());
  19988. }
  19989. // Test: SSEClient with custom headers
  19990. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19991. // Setup a server endpoint that checks for custom header
  19992. std::atomic<bool> header_received{false};
  19993. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19994. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19995. header_received.store(true);
  19996. }
  19997. res.set_chunked_content_provider("text/event-stream",
  19998. [](size_t, DataSink &) { return false; });
  19999. });
  20000. Client client("localhost", get_port());
  20001. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20002. sse::SSEClient sse(client, "/header-check", headers);
  20003. sse.set_max_reconnect_attempts(1);
  20004. sse.start_async();
  20005. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20006. sse.stop();
  20007. EXPECT_TRUE(header_received.load());
  20008. }
  20009. // Test: Reconnect interval configuration
  20010. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20011. Client client("localhost", get_port());
  20012. sse::SSEClient sse(client, "/events");
  20013. auto &result = sse.set_reconnect_interval(500);
  20014. // Builder pattern should return reference to self
  20015. EXPECT_EQ(&result, &sse);
  20016. }
  20017. // Test: Max reconnect attempts
  20018. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20019. // Connect to non-existent port to force reconnects
  20020. Client client("localhost", 59998);
  20021. sse::SSEClient sse(client, "/events");
  20022. std::atomic<int> error_count{0};
  20023. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20024. sse.set_reconnect_interval(50);
  20025. sse.set_max_reconnect_attempts(2);
  20026. auto start = std::chrono::steady_clock::now();
  20027. sse.start(); // Blocking call
  20028. auto end = std::chrono::steady_clock::now();
  20029. // Should have stopped after 2 failed attempts
  20030. EXPECT_GE(error_count.load(), 2);
  20031. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20032. auto duration =
  20033. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20034. #ifdef _WIN32
  20035. // Windows is much slower for socket connection failures
  20036. EXPECT_LT(duration.count(), 7000);
  20037. #else
  20038. EXPECT_LT(duration.count(), 1000);
  20039. #endif
  20040. }
  20041. // Test: Multi-line data in integration
  20042. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20043. // Endpoint with multi-line data
  20044. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20045. res.set_chunked_content_provider(
  20046. "text/event-stream", [](size_t offset, DataSink &sink) {
  20047. if (offset == 0) {
  20048. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20049. sink.write(event.data(), event.size());
  20050. }
  20051. return false;
  20052. });
  20053. });
  20054. Client client("localhost", get_port());
  20055. sse::SSEClient sse(client, "/multiline-data");
  20056. std::string received_data;
  20057. std::mutex data_mutex;
  20058. sse.on_message([&](const sse::SSEMessage &msg) {
  20059. std::lock_guard<std::mutex> lock(data_mutex);
  20060. received_data = msg.data;
  20061. });
  20062. sse.set_reconnect_interval(100);
  20063. sse.set_max_reconnect_attempts(1);
  20064. sse.start_async();
  20065. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20066. sse.stop();
  20067. std::lock_guard<std::mutex> lock(data_mutex);
  20068. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20069. }
  20070. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20071. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20072. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20073. DataSink &sink) {
  20074. if (offset == 0) {
  20075. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20076. sink.write(events.data(), events.size());
  20077. }
  20078. return false;
  20079. });
  20080. });
  20081. Client client("localhost", get_port());
  20082. sse::SSEClient sse(client, "/empty-data-lines");
  20083. std::mutex mutex;
  20084. std::condition_variable cv;
  20085. std::vector<std::string> received;
  20086. sse.on_message([&](const sse::SSEMessage &msg) {
  20087. std::lock_guard<std::mutex> lock(mutex);
  20088. received.push_back(msg.data);
  20089. cv.notify_all();
  20090. });
  20091. sse.set_max_reconnect_attempts(1);
  20092. sse.start_async();
  20093. {
  20094. std::unique_lock<std::mutex> lock(mutex);
  20095. cv.wait_for(lock, std::chrono::seconds(2),
  20096. [&] { return received.size() >= 3; });
  20097. }
  20098. sse.stop();
  20099. ASSERT_GE(received.size(), 3u);
  20100. EXPECT_EQ(received[0], "");
  20101. EXPECT_EQ(received[1], "\nhello");
  20102. EXPECT_EQ(received[2], "");
  20103. }
  20104. // Test: Auto-reconnect after server disconnection
  20105. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20106. std::atomic<int> connection_count{0};
  20107. std::atomic<int> message_count{0};
  20108. // Endpoint that sends one event and closes, forcing reconnect
  20109. server_->Get("/reconnect-test",
  20110. [&connection_count](const Request &, Response &res) {
  20111. connection_count.fetch_add(1);
  20112. res.set_chunked_content_provider(
  20113. "text/event-stream", [](size_t offset, DataSink &sink) {
  20114. if (offset == 0) {
  20115. std::string event = "data: hello\n\n";
  20116. sink.write(event.data(), event.size());
  20117. }
  20118. return false; // Close connection after sending
  20119. });
  20120. });
  20121. Client client("localhost", get_port());
  20122. sse::SSEClient sse(client, "/reconnect-test");
  20123. sse.on_message([&message_count](const sse::SSEMessage &) {
  20124. message_count.fetch_add(1);
  20125. });
  20126. sse.set_reconnect_interval(100);
  20127. sse.set_max_reconnect_attempts(3);
  20128. sse.start_async();
  20129. // Wait long enough for multiple reconnects
  20130. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20131. sse.stop();
  20132. // Should have connected multiple times (initial + reconnects)
  20133. EXPECT_GE(connection_count.load(), 2);
  20134. // Should have received messages from multiple connections
  20135. EXPECT_GE(message_count.load(), 2);
  20136. }
  20137. // Test: A retry field that is not all ASCII digits is ignored
  20138. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20139. std::atomic<int> connection_count{0};
  20140. server_->Get("/bad-retry",
  20141. [&connection_count](const Request &, Response &res) {
  20142. connection_count.fetch_add(1);
  20143. res.set_chunked_content_provider(
  20144. "text/event-stream", [](size_t offset, DataSink &sink) {
  20145. if (offset == 0) {
  20146. std::string event = "retry: -1\ndata: hello\n\n";
  20147. sink.write(event.data(), event.size());
  20148. }
  20149. return false;
  20150. });
  20151. });
  20152. Client client("localhost", get_port());
  20153. sse::SSEClient sse(client, "/bad-retry");
  20154. sse.set_reconnect_interval(10000);
  20155. sse.start_async();
  20156. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20157. sse.stop();
  20158. EXPECT_EQ(connection_count.load(), 1);
  20159. }
  20160. // Test: A retry field of all ASCII digits sets the reconnection time
  20161. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20162. std::mutex mutex;
  20163. std::condition_variable cv;
  20164. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20165. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20166. {
  20167. std::lock_guard<std::mutex> lock(mutex);
  20168. connected_at.push_back(std::chrono::steady_clock::now());
  20169. cv.notify_all();
  20170. }
  20171. res.set_chunked_content_provider(
  20172. "text/event-stream", [](size_t offset, DataSink &sink) {
  20173. if (offset == 0) {
  20174. std::string event = "retry: 0\ndata: hello\n\n";
  20175. sink.write(event.data(), event.size());
  20176. }
  20177. return false;
  20178. });
  20179. });
  20180. Client client("localhost", get_port());
  20181. sse::SSEClient sse(client, "/zero-retry");
  20182. sse.set_reconnect_interval(10000);
  20183. sse.start_async();
  20184. {
  20185. std::unique_lock<std::mutex> lock(mutex);
  20186. cv.wait_for(lock, std::chrono::seconds(5),
  20187. [&] { return connected_at.size() >= 2; });
  20188. }
  20189. sse.stop();
  20190. // The server-supplied interval is applied, but never below 100ms, so
  20191. // "retry: 0" does not cause a busy reconnect loop
  20192. std::lock_guard<std::mutex> lock(mutex);
  20193. ASSERT_GE(connected_at.size(), 2u);
  20194. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20195. connected_at[1] - connected_at[0])
  20196. .count();
  20197. EXPECT_GE(interval_ms, 100);
  20198. }
  20199. // Test: Last-Event-ID sent on reconnect
  20200. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20201. std::atomic<int> connection_count{0};
  20202. std::vector<std::string> received_last_event_ids;
  20203. std::mutex id_mutex;
  20204. // Endpoint that checks Last-Event-ID header and sends event with ID
  20205. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20206. int conn = connection_count.fetch_add(1);
  20207. // Capture the Last-Event-ID header from each connection
  20208. {
  20209. std::lock_guard<std::mutex> lock(id_mutex);
  20210. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20211. }
  20212. res.set_chunked_content_provider(
  20213. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20214. if (offset == 0) {
  20215. std::string event =
  20216. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20217. sink.write(event.data(), event.size());
  20218. }
  20219. return false;
  20220. });
  20221. });
  20222. Client client("localhost", get_port());
  20223. sse::SSEClient sse(client, "/reconnect-with-id");
  20224. sse.set_reconnect_interval(100);
  20225. sse.set_max_reconnect_attempts(3);
  20226. sse.start_async();
  20227. // Wait for at least 2 connections
  20228. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20229. sse.stop();
  20230. // Verify behavior
  20231. std::lock_guard<std::mutex> lock(id_mutex);
  20232. EXPECT_GE(received_last_event_ids.size(), 2u);
  20233. // First connection should have no Last-Event-ID
  20234. if (!received_last_event_ids.empty()) {
  20235. EXPECT_EQ(received_last_event_ids[0], "");
  20236. }
  20237. // Second connection should have Last-Event-ID from first connection
  20238. if (received_last_event_ids.size() >= 2) {
  20239. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20240. }
  20241. }
  20242. // Test: set_headers updates headers used on reconnect
  20243. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20244. std::vector<std::string> received_tokens;
  20245. std::mutex token_mutex;
  20246. // Endpoint that captures Authorization header
  20247. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20248. {
  20249. std::lock_guard<std::mutex> lock(token_mutex);
  20250. received_tokens.push_back(req.get_header_value("Authorization"));
  20251. }
  20252. res.set_chunked_content_provider(
  20253. "text/event-stream", [](size_t offset, DataSink &sink) {
  20254. if (offset == 0) {
  20255. std::string event = "data: hello\n\n";
  20256. sink.write(event.data(), event.size());
  20257. }
  20258. return false; // Close connection to trigger reconnect
  20259. });
  20260. });
  20261. Client client("localhost", get_port());
  20262. Headers headers = {{"Authorization", "Bearer old-token"}};
  20263. sse::SSEClient sse(client, "/auth-check", headers);
  20264. // Update headers on each successful connection
  20265. sse.on_open(
  20266. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20267. sse.set_reconnect_interval(100);
  20268. sse.set_max_reconnect_attempts(3);
  20269. sse.start_async();
  20270. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20271. sse.stop();
  20272. std::lock_guard<std::mutex> lock(token_mutex);
  20273. ASSERT_GE(received_tokens.size(), 2u);
  20274. // First connection uses original header
  20275. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20276. // Second connection uses updated header from set_headers
  20277. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20278. }
  20279. // Test: 401 allows reconnection (so on_error can refresh headers)
  20280. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20281. std::atomic<int> connection_count{0};
  20282. // Endpoint: returns 401 on first attempt, 200 on second
  20283. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20284. int conn = connection_count.fetch_add(1);
  20285. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20286. res.status = StatusCode::Unauthorized_401;
  20287. res.set_content("Unauthorized", "text/plain");
  20288. return;
  20289. }
  20290. res.set_chunked_content_provider(
  20291. "text/event-stream", [](size_t offset, DataSink &sink) {
  20292. if (offset == 0) {
  20293. std::string event = "data: authenticated\n\n";
  20294. sink.write(event.data(), event.size());
  20295. }
  20296. return false;
  20297. });
  20298. });
  20299. Client client("localhost", get_port());
  20300. Headers headers = {{"Authorization", "Bearer expired"}};
  20301. sse::SSEClient sse(client, "/auth-retry", headers);
  20302. std::atomic<bool> message_received{false};
  20303. // Refresh token on error
  20304. sse.on_error(
  20305. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20306. sse.on_message([&](const sse::SSEMessage &msg) {
  20307. if (msg.data == "authenticated") { message_received.store(true); }
  20308. });
  20309. sse.set_reconnect_interval(100);
  20310. sse.set_max_reconnect_attempts(3);
  20311. sse.start_async();
  20312. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20313. sse.stop();
  20314. // Should have reconnected after 401 and succeeded with new token
  20315. EXPECT_GE(connection_count.load(), 2);
  20316. EXPECT_TRUE(message_received.load());
  20317. }
  20318. TEST(Issue2318Test, EmptyHostString) {
  20319. {
  20320. httplib::Client cli_empty("", PORT);
  20321. auto res = cli_empty.Get("/");
  20322. ASSERT_FALSE(res);
  20323. EXPECT_EQ(httplib::Error::Connection, res.error());
  20324. }
  20325. {
  20326. httplib::Client cli(" ", PORT);
  20327. auto res = cli.Get("/");
  20328. ASSERT_FALSE(res);
  20329. EXPECT_EQ(httplib::Error::Connection, res.error());
  20330. }
  20331. }
  20332. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20333. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20334. Server svr;
  20335. // Set a small payload limit (1KB)
  20336. svr.set_payload_max_length(1024);
  20337. svr.Post("/test", [&](const Request &req, Response &res) {
  20338. res.set_content("Body size: " + std::to_string(req.body.size()),
  20339. "text/plain");
  20340. });
  20341. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20342. auto se = detail::scope_exit([&] {
  20343. svr.stop();
  20344. listen_thread.join();
  20345. });
  20346. svr.wait_until_ready();
  20347. // Create data that compresses well but exceeds limit when decompressed
  20348. // 8KB of repeated null bytes compresses to a very small size
  20349. std::string original_data(8 * 1024, '\0');
  20350. // Compress the data using gzip
  20351. std::string compressed_data;
  20352. detail::gzip_compressor compressor;
  20353. compressor.compress(original_data.data(), original_data.size(), true,
  20354. [&](const char *data, size_t size) {
  20355. compressed_data.append(data, size);
  20356. return true;
  20357. });
  20358. // Verify compression worked (compressed should be much smaller)
  20359. ASSERT_LT(compressed_data.size(), original_data.size());
  20360. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20361. // Send compressed data with Content-Encoding: gzip
  20362. Client cli(HOST, PORT);
  20363. Headers headers = {{"Content-Encoding", "gzip"}};
  20364. auto res =
  20365. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20366. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20368. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20369. }
  20370. #endif
  20371. // ============================================================================
  20372. // OpenSSL-Specific Tests
  20373. // ============================================================================
  20374. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20375. X509 *readCertificate(const std::string &strFileName) {
  20376. std::ifstream inStream(strFileName);
  20377. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20378. std::istreambuf_iterator<char>());
  20379. if (strCertPEM.empty()) return (nullptr);
  20380. BIO *pbCert = BIO_new(BIO_s_mem());
  20381. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20382. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20383. BIO_free(pbCert);
  20384. return (pCert);
  20385. }
  20386. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20387. std::ifstream inStream(strFileName);
  20388. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20389. std::istreambuf_iterator<char>());
  20390. if (strPrivateKeyPEM.empty()) return (nullptr);
  20391. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20392. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20393. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20394. BIO_free(pbPrivKey);
  20395. return (pPrivateKey);
  20396. }
  20397. TEST(BindServerTest, UpdateCerts) {
  20398. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20399. int port = svr.bind_to_any_port("0.0.0.0");
  20400. ASSERT_TRUE(svr.is_valid());
  20401. ASSERT_TRUE(port > 0);
  20402. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20403. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20404. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20405. ASSERT_TRUE(cert != nullptr);
  20406. ASSERT_TRUE(ca_cert != nullptr);
  20407. ASSERT_TRUE(key != nullptr);
  20408. X509_STORE *cert_store = X509_STORE_new();
  20409. X509_STORE_add_cert(cert_store, ca_cert);
  20410. // svr.update_certs(cert, key, cert_store); // deprecated
  20411. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20412. CLIENT_CA_CERT_FILE);
  20413. ASSERT_TRUE(svr.is_valid());
  20414. svr.stop();
  20415. X509_STORE_free(cert_store);
  20416. X509_free(cert);
  20417. X509_free(ca_cert);
  20418. EVP_PKEY_free(key);
  20419. }
  20420. // Test that update_certs() updates client CA list correctly
  20421. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20422. // Start with file-based constructor
  20423. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20424. ASSERT_TRUE(svr.is_valid());
  20425. // Initially no client CA list should be set
  20426. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20427. ASSERT_TRUE(ssl_ctx != nullptr);
  20428. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20429. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20430. EXPECT_EQ(0, count_before);
  20431. // Now update with client CA (PEM string)
  20432. std::string cert_pem, key_pem, ca_pem;
  20433. read_file(SERVER_CERT_FILE, cert_pem);
  20434. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20435. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20436. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20437. ASSERT_TRUE(svr.is_valid());
  20438. // Now client CA list should be set
  20439. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20440. ASSERT_TRUE(ca_list_after != nullptr);
  20441. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20442. }
  20443. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20444. // Test that the file-path SSLServer constructor properly sets the client CA
  20445. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20447. ASSERT_TRUE(svr.is_valid());
  20448. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20449. ASSERT_TRUE(ssl_ctx != nullptr);
  20450. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20451. ASSERT_TRUE(ca_list != nullptr);
  20452. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20453. }
  20454. #endif
  20455. // ============================================================================
  20456. // MbedTLS-Specific Tests
  20457. // ============================================================================
  20458. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20459. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20460. using namespace httplib::tls;
  20461. // Track if callback was invoked
  20462. bool callback_invoked = false;
  20463. // The callback receives void* ctx which is actually MbedTlsContext*
  20464. // We can access the mbedtls_ssl_config via the context
  20465. auto setup_callback = [&callback_invoked](void *ctx) {
  20466. callback_invoked = true;
  20467. // Cast to MbedTlsContext* to access the ssl config
  20468. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20469. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20470. // Use static variables to hold certificate data (simplified for test)
  20471. static mbedtls_x509_crt own_cert;
  20472. static mbedtls_pk_context own_key;
  20473. static mbedtls_x509_crt ca_chain;
  20474. static bool initialized = false;
  20475. if (!initialized) {
  20476. mbedtls_x509_crt_init(&own_cert);
  20477. mbedtls_pk_init(&own_key);
  20478. mbedtls_x509_crt_init(&ca_chain);
  20479. // Load server certificate
  20480. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20481. return false;
  20482. }
  20483. // Load server private key.
  20484. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20485. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20486. #if MBEDTLS_VERSION_MAJOR == 3
  20487. ,
  20488. mbedtls_ctr_drbg_random, nullptr
  20489. #endif
  20490. ) != 0) {
  20491. return false;
  20492. }
  20493. // Load CA chain for client verification
  20494. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20495. return false;
  20496. }
  20497. initialized = true;
  20498. }
  20499. // Configure the SSL config
  20500. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20501. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20502. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20503. // Set minimum TLS version using mbedTLS native API
  20504. #if MBEDTLS_VERSION_MAJOR >= 3
  20505. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20506. #else
  20507. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20508. MBEDTLS_SSL_MINOR_VERSION_3);
  20509. #endif
  20510. return true;
  20511. };
  20512. SSLServer svr(setup_callback);
  20513. ASSERT_TRUE(svr.is_valid());
  20514. ASSERT_TRUE(callback_invoked);
  20515. svr.Get("/test", [&](const Request &req, Response &res) {
  20516. res.set_content("test", "text/plain");
  20517. auto cert = req.peer_cert();
  20518. ASSERT_TRUE(static_cast<bool>(cert));
  20519. auto common_name = cert.subject_cn();
  20520. EXPECT_EQ("Common Name", common_name);
  20521. });
  20522. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20523. auto se = detail::scope_exit([&] {
  20524. svr.stop();
  20525. t.join();
  20526. ASSERT_FALSE(svr.is_running());
  20527. });
  20528. svr.wait_until_ready();
  20529. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20530. cli.enable_server_certificate_verification(false);
  20531. cli.set_connection_timeout(30);
  20532. auto res = cli.Get("/test");
  20533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20534. ASSERT_EQ(StatusCode::OK_200, res->status);
  20535. }
  20536. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20537. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20538. // keep-alive SSL session, which reads through that config in
  20539. // mbedtls_ssl_close_notify.
  20540. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20541. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20542. ASSERT_TRUE(svr.is_valid());
  20543. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20544. res.set_content("test", "text/plain");
  20545. });
  20546. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20547. auto se = detail::scope_exit([&] {
  20548. svr.stop();
  20549. t.join();
  20550. ASSERT_FALSE(svr.is_running());
  20551. });
  20552. svr.wait_until_ready();
  20553. {
  20554. SSLClient cli(HOST, PORT);
  20555. cli.enable_server_certificate_verification(false);
  20556. cli.set_keep_alive(true);
  20557. auto res = cli.Get("/test");
  20558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20559. ASSERT_EQ(StatusCode::OK_200, res->status);
  20560. // cli is destructed here with the keep-alive SSL session still open.
  20561. }
  20562. }
  20563. #endif
  20564. // WebSocket Tests
  20565. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20566. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20567. // defining the meaning of these bits has been negotiated.
  20568. auto make_frame = [](uint8_t first_byte) {
  20569. std::string frame;
  20570. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20571. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20572. frame += "Hello";
  20573. return frame;
  20574. };
  20575. // RSV1 set (0x40)
  20576. {
  20577. detail::BufferStream strm;
  20578. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20579. ws::Opcode opcode;
  20580. std::string payload;
  20581. bool fin;
  20582. EXPECT_EQ(
  20583. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20584. ws::impl::FrameRead::Fail);
  20585. }
  20586. // RSV2 set (0x20)
  20587. {
  20588. detail::BufferStream strm;
  20589. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20590. ws::Opcode opcode;
  20591. std::string payload;
  20592. bool fin;
  20593. EXPECT_EQ(
  20594. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20595. ws::impl::FrameRead::Fail);
  20596. }
  20597. // RSV3 set (0x10)
  20598. {
  20599. detail::BufferStream strm;
  20600. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20601. ws::Opcode opcode;
  20602. std::string payload;
  20603. bool fin;
  20604. EXPECT_EQ(
  20605. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20606. ws::impl::FrameRead::Fail);
  20607. }
  20608. // No RSV bits set - should succeed
  20609. {
  20610. detail::BufferStream strm;
  20611. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20612. ws::Opcode opcode;
  20613. std::string payload;
  20614. bool fin;
  20615. EXPECT_EQ(
  20616. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20617. ws::impl::FrameRead::Ok);
  20618. EXPECT_EQ(ws::Opcode::Text, opcode);
  20619. EXPECT_EQ("Hello", payload);
  20620. EXPECT_TRUE(fin);
  20621. }
  20622. }
  20623. TEST(WebSocketTest, ControlFrameValidation) {
  20624. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20625. // payload length <= 125.
  20626. // Ping with FIN=0 - must be rejected
  20627. {
  20628. detail::BufferStream strm;
  20629. std::string frame;
  20630. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20631. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20632. strm.write(frame.data(), frame.size());
  20633. ws::Opcode opcode;
  20634. std::string payload;
  20635. bool fin;
  20636. EXPECT_EQ(
  20637. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20638. ws::impl::FrameRead::Fail);
  20639. }
  20640. // Close with FIN=0 - must be rejected
  20641. {
  20642. detail::BufferStream strm;
  20643. std::string frame;
  20644. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20645. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20646. strm.write(frame.data(), frame.size());
  20647. ws::Opcode opcode;
  20648. std::string payload;
  20649. bool fin;
  20650. EXPECT_EQ(
  20651. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20652. ws::impl::FrameRead::Fail);
  20653. }
  20654. // Ping with payload_len=126 (extended length) - must be rejected
  20655. {
  20656. detail::BufferStream strm;
  20657. std::string frame;
  20658. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20659. frame += static_cast<char>(126); // payload_len=126 (>125)
  20660. frame += static_cast<char>(0x00); // extended length high byte
  20661. frame += static_cast<char>(126); // extended length low byte
  20662. frame += std::string(126, 'x');
  20663. strm.write(frame.data(), frame.size());
  20664. ws::Opcode opcode;
  20665. std::string payload;
  20666. bool fin;
  20667. EXPECT_EQ(
  20668. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20669. ws::impl::FrameRead::Fail);
  20670. }
  20671. // Ping with FIN=1 and payload_len=125 - should succeed
  20672. {
  20673. detail::BufferStream strm;
  20674. std::string frame;
  20675. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20676. frame += static_cast<char>(125); // payload_len=125
  20677. frame += std::string(125, 'x');
  20678. strm.write(frame.data(), frame.size());
  20679. ws::Opcode opcode;
  20680. std::string payload;
  20681. bool fin;
  20682. EXPECT_EQ(
  20683. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20684. ws::impl::FrameRead::Ok);
  20685. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20686. EXPECT_EQ(125u, payload.size());
  20687. EXPECT_TRUE(fin);
  20688. }
  20689. }
  20690. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20691. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20692. // length MUST be 0.
  20693. // MSB set - must be rejected
  20694. {
  20695. detail::BufferStream strm;
  20696. std::string frame;
  20697. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20698. frame += static_cast<char>(127); // 64-bit extended length
  20699. frame += static_cast<char>(0x80); // MSB set (invalid)
  20700. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20701. strm.write(frame.data(), frame.size());
  20702. ws::Opcode opcode;
  20703. std::string payload;
  20704. bool fin;
  20705. EXPECT_EQ(
  20706. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20707. ws::impl::FrameRead::Fail);
  20708. }
  20709. // MSB clear - should pass length parsing (will be rejected by max_len,
  20710. // but that's a different check; use a small length to verify)
  20711. {
  20712. detail::BufferStream strm;
  20713. std::string frame;
  20714. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20715. frame += static_cast<char>(127); // 64-bit extended length
  20716. frame += std::string(7, '\0'); // high bytes = 0
  20717. frame += static_cast<char>(0x03); // length = 3
  20718. frame += "abc";
  20719. strm.write(frame.data(), frame.size());
  20720. ws::Opcode opcode;
  20721. std::string payload;
  20722. bool fin;
  20723. EXPECT_EQ(
  20724. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20725. ws::impl::FrameRead::Ok);
  20726. EXPECT_EQ(ws::Opcode::Text, opcode);
  20727. EXPECT_EQ("abc", payload);
  20728. }
  20729. }
  20730. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20731. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20732. // Valid UTF-8
  20733. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20734. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20735. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20736. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20737. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20738. // Invalid UTF-8
  20739. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20740. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20741. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20742. EXPECT_FALSE(
  20743. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20744. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20745. }
  20746. TEST(WebSocketTest, ConnectAndDisconnect) {
  20747. Server svr;
  20748. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20749. std::string msg;
  20750. while (ws.read(msg)) {}
  20751. });
  20752. auto port = svr.bind_to_any_port(HOST);
  20753. std::thread t([&]() { svr.listen_after_bind(); });
  20754. svr.wait_until_ready();
  20755. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20756. auto res = client.connect();
  20757. ASSERT_TRUE(res);
  20758. EXPECT_EQ(Error::Success, res.error());
  20759. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20760. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20761. EXPECT_TRUE(client.is_open());
  20762. client.close();
  20763. EXPECT_FALSE(client.is_open());
  20764. svr.stop();
  20765. t.join();
  20766. }
  20767. TEST(WebSocketTest, ValidURL) {
  20768. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20769. EXPECT_TRUE(ws1.is_valid());
  20770. ws::WebSocketClient ws2("ws://example.com/path");
  20771. EXPECT_TRUE(ws2.is_valid());
  20772. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20773. EXPECT_TRUE(ws3.is_valid());
  20774. #ifdef CPPHTTPLIB_SSL_ENABLED
  20775. ws::WebSocketClient wss1("wss://example.com/path");
  20776. EXPECT_TRUE(wss1.is_valid());
  20777. ws::WebSocketClient wss2("wss://example.com:443/path");
  20778. EXPECT_TRUE(wss2.is_valid());
  20779. #endif
  20780. }
  20781. TEST(WebSocketTest, InvalidURL) {
  20782. // No scheme
  20783. ws::WebSocketClient ws1("localhost:8080/path");
  20784. EXPECT_FALSE(ws1.is_valid());
  20785. // No path
  20786. ws::WebSocketClient ws2("ws://localhost:8080");
  20787. EXPECT_FALSE(ws2.is_valid());
  20788. // Empty string
  20789. ws::WebSocketClient ws3("");
  20790. EXPECT_FALSE(ws3.is_valid());
  20791. // Missing host
  20792. ws::WebSocketClient ws4("ws://:8080/path");
  20793. EXPECT_FALSE(ws4.is_valid());
  20794. // Port number overflow — should not crash
  20795. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20796. EXPECT_FALSE(ws5.is_valid());
  20797. // Port out of range
  20798. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20799. EXPECT_FALSE(ws6.is_valid());
  20800. }
  20801. TEST(WebSocketTest, UnsupportedScheme) {
  20802. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20803. ws::WebSocketClient ws1("http://localhost:8080/path");
  20804. EXPECT_FALSE(ws1.is_valid());
  20805. ws::WebSocketClient ws2("https://localhost:8080/path");
  20806. EXPECT_FALSE(ws2.is_valid());
  20807. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20808. EXPECT_FALSE(ws3.is_valid());
  20809. #else
  20810. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20811. std::invalid_argument);
  20812. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20813. std::invalid_argument);
  20814. #endif
  20815. }
  20816. TEST(WebSocketTest, ConnectWhenInvalid) {
  20817. ws::WebSocketClient ws("not a valid url");
  20818. EXPECT_FALSE(ws.is_valid());
  20819. auto res = ws.connect();
  20820. EXPECT_FALSE(res);
  20821. EXPECT_EQ(Error::Connection, res.error());
  20822. EXPECT_EQ(-1, res.status());
  20823. }
  20824. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20825. // Grab a port that is free, then close it again so nothing listens there
  20826. Server svr;
  20827. auto port = svr.bind_to_any_port(HOST);
  20828. svr.stop();
  20829. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20830. auto res = client.connect();
  20831. ASSERT_FALSE(res);
  20832. EXPECT_EQ(Error::Connection, res.error());
  20833. EXPECT_EQ(-1, res.status());
  20834. }
  20835. TEST(WebSocketTest, DefaultPort) {
  20836. ws::WebSocketClient ws1("ws://example.com/path");
  20837. EXPECT_TRUE(ws1.is_valid());
  20838. // ws:// defaults to port 80 (verified by successful parse)
  20839. #ifdef CPPHTTPLIB_SSL_ENABLED
  20840. ws::WebSocketClient ws2("wss://example.com/path");
  20841. EXPECT_TRUE(ws2.is_valid());
  20842. // wss:// defaults to port 443 (verified by successful parse)
  20843. #endif
  20844. }
  20845. TEST(WebSocketTest, IPv6LiteralAddress) {
  20846. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20847. EXPECT_TRUE(ws1.is_valid());
  20848. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20849. EXPECT_TRUE(ws2.is_valid());
  20850. }
  20851. TEST(WebSocketTest, ComplexPath) {
  20852. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20853. EXPECT_TRUE(ws1.is_valid());
  20854. ws::WebSocketClient ws2("ws://localhost:8080/");
  20855. EXPECT_TRUE(ws2.is_valid());
  20856. }
  20857. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20858. Server svr;
  20859. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20860. std::string msg;
  20861. while (ws.read(msg)) {}
  20862. });
  20863. auto port = svr.bind_to_any_port(HOST);
  20864. std::thread t([&]() { svr.listen_after_bind(); });
  20865. svr.wait_until_ready();
  20866. auto another_host = "example.com";
  20867. auto wrong_ip = "192.0.2.1";
  20868. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20869. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20870. ASSERT_TRUE(client.connect());
  20871. EXPECT_TRUE(client.is_open());
  20872. client.close();
  20873. svr.stop();
  20874. t.join();
  20875. }
  20876. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20877. Server svr;
  20878. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20879. std::string msg;
  20880. while (ws.read(msg)) {}
  20881. });
  20882. auto port = svr.bind_to_any_port(HOST);
  20883. std::thread t([&]() { svr.listen_after_bind(); });
  20884. svr.wait_until_ready();
  20885. auto wrong_ip = "192.0.2.1";
  20886. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20887. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20888. client.set_connection_timeout(1);
  20889. client.set_read_timeout(1);
  20890. client.set_write_timeout(1);
  20891. EXPECT_FALSE(client.connect());
  20892. EXPECT_FALSE(client.is_open());
  20893. svr.stop();
  20894. t.join();
  20895. }
  20896. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20897. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20898. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20899. // (RFC 6761) is only a map key and the Host header value.
  20900. auto host = "target.invalid";
  20901. Server svr;
  20902. std::string received_host;
  20903. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20904. received_host = req.get_header_value("Host");
  20905. std::string msg;
  20906. while (ws.read(msg)) {}
  20907. });
  20908. auto port = svr.bind_to_any_port(HOST);
  20909. std::thread t([&]() { svr.listen_after_bind(); });
  20910. // ASSERT_* below returns from the test body, which would leave t joinable
  20911. // and make ~thread call std::terminate.
  20912. auto se = detail::scope_exit([&] {
  20913. svr.stop();
  20914. if (t.joinable()) { t.join(); }
  20915. });
  20916. svr.wait_until_ready();
  20917. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20918. std::to_string(port) + "/ws");
  20919. client.set_hostname_addr_map({{host, HOST}});
  20920. ASSERT_TRUE(client.connect());
  20921. EXPECT_TRUE(client.is_open());
  20922. client.close();
  20923. svr.stop();
  20924. t.join();
  20925. // The mapping only redirects the connection; the identity stays host_.
  20926. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20927. }
  20928. class WebSocketIntegrationTest : public ::testing::Test {
  20929. protected:
  20930. void SetUp() override {
  20931. server_ = httplib::detail::make_unique<Server>();
  20932. setup_server();
  20933. start_server();
  20934. }
  20935. void TearDown() override {
  20936. server_->stop();
  20937. if (server_thread_.joinable()) { server_thread_.join(); }
  20938. }
  20939. void setup_server() {
  20940. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20941. std::string msg;
  20942. ws::ReadResult ret;
  20943. while ((ret = ws.read(msg))) {
  20944. if (ret == ws::Binary) {
  20945. ws.send(msg.data(), msg.size());
  20946. } else {
  20947. ws.send(msg);
  20948. }
  20949. }
  20950. });
  20951. server_->WebSocket("/ws-echo-string",
  20952. [](const Request &, ws::WebSocket &ws) {
  20953. std::string msg;
  20954. while (ws.read(msg)) {
  20955. ws.send("echo: " + msg);
  20956. }
  20957. });
  20958. server_->WebSocket(
  20959. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20960. // Echo back request metadata
  20961. ws.send("path:" + req.path);
  20962. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20963. std::string msg;
  20964. while (ws.read(msg)) {}
  20965. });
  20966. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20967. std::string msg;
  20968. ws.read(msg); // wait for a message
  20969. ws.close();
  20970. });
  20971. server_->WebSocket("/ws-close-status",
  20972. [](const Request &, ws::WebSocket &ws) {
  20973. std::string msg;
  20974. ws.read(msg); // wait for a message
  20975. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20976. });
  20977. server_->WebSocket(
  20978. "/ws-subprotocol",
  20979. [](const Request &, ws::WebSocket &ws) {
  20980. std::string msg;
  20981. while (ws.read(msg)) {
  20982. ws.send(msg);
  20983. }
  20984. },
  20985. [](const std::vector<std::string> &protocols) -> std::string {
  20986. for (const auto &p : protocols) {
  20987. if (p == "graphql-ws") { return p; }
  20988. }
  20989. return "";
  20990. });
  20991. server_->WebSocket(
  20992. "/ws-subprotocol-unoffered",
  20993. [](const Request &, ws::WebSocket &ws) {
  20994. std::string msg;
  20995. while (ws.read(msg)) {
  20996. ws.send(msg);
  20997. }
  20998. },
  20999. [](const std::vector<std::string> &) -> std::string {
  21000. return "admin";
  21001. });
  21002. }
  21003. void start_server() {
  21004. port_ = server_->bind_to_any_port(HOST);
  21005. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21006. server_->wait_until_ready();
  21007. }
  21008. std::unique_ptr<Server> server_;
  21009. std::thread server_thread_;
  21010. int port_ = 0;
  21011. };
  21012. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21013. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21014. "/ws-echo");
  21015. ASSERT_TRUE(client.connect());
  21016. ASSERT_TRUE(client.is_open());
  21017. ASSERT_TRUE(client.send("Hello WebSocket"));
  21018. std::string msg;
  21019. EXPECT_EQ(ws::Text, client.read(msg));
  21020. EXPECT_EQ("Hello WebSocket", msg);
  21021. client.close();
  21022. }
  21023. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21024. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21025. "/ws-echo");
  21026. ASSERT_TRUE(client.connect());
  21027. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21028. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21029. std::string msg;
  21030. EXPECT_EQ(ws::Binary, client.read(msg));
  21031. EXPECT_EQ(binary_data, msg);
  21032. client.close();
  21033. }
  21034. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21035. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21036. "/ws-echo");
  21037. ASSERT_TRUE(client.connect());
  21038. for (int i = 0; i < 10; i++) {
  21039. auto text = "message " + std::to_string(i);
  21040. ASSERT_TRUE(client.send(text));
  21041. std::string msg;
  21042. ASSERT_TRUE(client.read(msg));
  21043. EXPECT_EQ(text, msg);
  21044. }
  21045. client.close();
  21046. }
  21047. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21048. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21049. "/ws-close");
  21050. ASSERT_TRUE(client.connect());
  21051. // Send a message to trigger the server to close
  21052. ASSERT_TRUE(client.send("trigger close"));
  21053. // The server will close, so read should return false
  21054. std::string msg;
  21055. EXPECT_FALSE(client.read(msg));
  21056. EXPECT_FALSE(client.is_open());
  21057. }
  21058. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21059. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21060. "/ws-echo");
  21061. ASSERT_TRUE(client.connect());
  21062. // 128KB message
  21063. std::string large_data(128 * 1024, 'X');
  21064. ASSERT_TRUE(client.send(large_data));
  21065. std::string msg;
  21066. ASSERT_TRUE(client.read(msg));
  21067. EXPECT_EQ(large_data, msg);
  21068. client.close();
  21069. }
  21070. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21071. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21072. "/ws-echo");
  21073. ASSERT_TRUE(client.connect());
  21074. const int num_threads = 4;
  21075. std::vector<std::thread> threads;
  21076. std::atomic<int> send_count{0};
  21077. for (int t = 0; t < num_threads; t++) {
  21078. threads.emplace_back([&client, &send_count, t]() {
  21079. for (int i = 0; i < 5; i++) {
  21080. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21081. if (client.send(text)) { send_count++; }
  21082. }
  21083. });
  21084. }
  21085. for (auto &th : threads) {
  21086. th.join();
  21087. }
  21088. int received = 0;
  21089. std::string msg;
  21090. while (received < send_count.load()) {
  21091. if (!client.read(msg)) { break; }
  21092. received++;
  21093. }
  21094. EXPECT_EQ(send_count.load(), received);
  21095. client.close();
  21096. }
  21097. TEST_F(WebSocketIntegrationTest, ReadString) {
  21098. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21099. "/ws-echo-string");
  21100. ASSERT_TRUE(client.connect());
  21101. ASSERT_TRUE(client.send("hello"));
  21102. std::string msg;
  21103. ASSERT_TRUE(client.read(msg));
  21104. EXPECT_EQ("echo: hello", msg);
  21105. ASSERT_TRUE(client.send("world"));
  21106. ASSERT_TRUE(client.read(msg));
  21107. EXPECT_EQ("echo: world", msg);
  21108. client.close();
  21109. }
  21110. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21111. Headers headers = {{"X-Test-Header", "test-value"}};
  21112. ws::WebSocketClient client(
  21113. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21114. ASSERT_TRUE(client.connect());
  21115. std::string msg;
  21116. ASSERT_TRUE(client.read(msg));
  21117. EXPECT_EQ("path:/ws-request-info", msg);
  21118. ASSERT_TRUE(client.read(msg));
  21119. EXPECT_EQ("header:test-value", msg);
  21120. client.close();
  21121. }
  21122. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21123. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21124. "/ws-echo");
  21125. client.set_read_timeout(1, 0); // 1 second
  21126. ASSERT_TRUE(client.connect());
  21127. // Don't send anything — server echo handler waits for a message, so read()
  21128. // should time out. The connection survives it: nothing was consumed.
  21129. std::string msg;
  21130. EXPECT_EQ(client.read(msg), ws::Timeout);
  21131. EXPECT_TRUE(client.is_open());
  21132. // And it is still usable afterwards.
  21133. EXPECT_TRUE(client.send("after timeout"));
  21134. EXPECT_EQ(client.read(msg), ws::Text);
  21135. EXPECT_EQ(msg, "after timeout");
  21136. }
  21137. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21138. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21139. "/ws-echo");
  21140. client.set_read_timeout(1, 0);
  21141. ASSERT_TRUE(client.connect());
  21142. ASSERT_TRUE(client.send("first"));
  21143. std::string msg;
  21144. ASSERT_EQ(client.read(msg), ws::Text);
  21145. ASSERT_EQ(msg, "first");
  21146. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21147. // not be used with a read timeout: it would reprocess the previous message.
  21148. EXPECT_EQ(client.read(msg), ws::Timeout);
  21149. EXPECT_EQ(msg, "first");
  21150. }
  21151. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21152. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21153. "/ws-echo");
  21154. ASSERT_TRUE(client.connect());
  21155. // Setting it once the connection is open reaches the live stream, not just
  21156. // the seed for the next connect().
  21157. client.set_read_timeout(1, 0);
  21158. std::string msg;
  21159. EXPECT_EQ(client.read(msg), ws::Timeout);
  21160. EXPECT_TRUE(client.is_open());
  21161. }
  21162. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21163. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21164. "/ws-echo");
  21165. client.set_read_timeout(5, 0);
  21166. ASSERT_TRUE(client.connect());
  21167. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21168. // The server should reject it and close the connection.
  21169. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21170. client.send(oversized);
  21171. // The server's read() should have failed due to payload limit,
  21172. // so our read() should return false (connection closed).
  21173. std::string msg;
  21174. EXPECT_FALSE(client.read(msg));
  21175. }
  21176. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21177. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21178. "/ws-echo");
  21179. client.set_read_timeout(10, 0);
  21180. ASSERT_TRUE(client.connect());
  21181. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21182. // This should succeed.
  21183. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21184. ASSERT_TRUE(client.send(at_limit));
  21185. std::string msg;
  21186. ASSERT_TRUE(client.read(msg));
  21187. EXPECT_EQ(at_limit.size(), msg.size());
  21188. client.close();
  21189. }
  21190. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21191. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21192. "/nonexistent");
  21193. auto res = client.connect();
  21194. EXPECT_FALSE(res);
  21195. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21196. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21197. EXPECT_FALSE(client.is_open());
  21198. }
  21199. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21200. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21201. "/ws-echo");
  21202. ASSERT_TRUE(client.connect());
  21203. ASSERT_TRUE(client.send(""));
  21204. std::string msg;
  21205. EXPECT_EQ(ws::Text, client.read(msg));
  21206. EXPECT_EQ("", msg);
  21207. client.close();
  21208. }
  21209. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21210. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21211. "/ws-echo");
  21212. // First connection
  21213. ASSERT_TRUE(client.connect());
  21214. ASSERT_TRUE(client.send("first"));
  21215. std::string msg;
  21216. ASSERT_TRUE(client.read(msg));
  21217. EXPECT_EQ("first", msg);
  21218. client.close();
  21219. EXPECT_FALSE(client.is_open());
  21220. // Reconnect using the same client object
  21221. ASSERT_TRUE(client.connect());
  21222. ASSERT_TRUE(client.is_open());
  21223. ASSERT_TRUE(client.send("second"));
  21224. ASSERT_TRUE(client.read(msg));
  21225. EXPECT_EQ("second", msg);
  21226. client.close();
  21227. }
  21228. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21229. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21230. "/ws-close-status");
  21231. ASSERT_TRUE(client.connect());
  21232. // Trigger the server to close with GoingAway status
  21233. ASSERT_TRUE(client.send("trigger"));
  21234. // read() should return false after receiving the close frame
  21235. std::string msg;
  21236. EXPECT_FALSE(client.read(msg));
  21237. EXPECT_FALSE(client.is_open());
  21238. }
  21239. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21240. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21241. "/ws-echo");
  21242. ASSERT_TRUE(client.connect());
  21243. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21244. EXPECT_FALSE(client.is_open());
  21245. }
  21246. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21247. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21248. ws::WebSocketClient client(
  21249. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21250. ASSERT_TRUE(client.connect());
  21251. // Server should have selected graphql-ws
  21252. EXPECT_EQ("graphql-ws", client.subprotocol());
  21253. client.close();
  21254. }
  21255. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21256. Headers headers;
  21257. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21258. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21259. ws::WebSocketClient client(
  21260. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21261. ASSERT_TRUE(client.connect());
  21262. // The offer on the second field line counts too, so graphql-ws is selected
  21263. EXPECT_EQ("graphql-ws", client.subprotocol());
  21264. client.close();
  21265. }
  21266. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21267. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21268. ws::WebSocketClient client(
  21269. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21270. ASSERT_TRUE(client.connect());
  21271. // Server should not have selected any subprotocol
  21272. EXPECT_TRUE(client.subprotocol().empty());
  21273. client.close();
  21274. }
  21275. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21276. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21277. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21278. "/ws-subprotocol-unoffered",
  21279. headers);
  21280. ASSERT_TRUE(client.connect());
  21281. EXPECT_TRUE(client.subprotocol().empty());
  21282. client.close();
  21283. }
  21284. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21285. // Connect without requesting any subprotocol
  21286. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21287. "/ws-subprotocol");
  21288. ASSERT_TRUE(client.connect());
  21289. EXPECT_TRUE(client.subprotocol().empty());
  21290. client.close();
  21291. }
  21292. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21293. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21294. "/ws-echo");
  21295. client.set_tcp_nodelay(true);
  21296. client.set_connection_timeout(3, 0);
  21297. bool socket_options_called = false;
  21298. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21299. ASSERT_TRUE(client.connect());
  21300. ASSERT_TRUE(client.is_open());
  21301. EXPECT_TRUE(socket_options_called);
  21302. ASSERT_TRUE(client.send("hello"));
  21303. std::string msg;
  21304. auto result = client.read(msg);
  21305. EXPECT_EQ(result, ws::ReadResult::Text);
  21306. EXPECT_EQ(msg, "hello");
  21307. client.close();
  21308. }
  21309. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21310. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21311. "/ws-echo");
  21312. client.set_connection_timeout(std::chrono::seconds(3));
  21313. client.set_write_timeout(std::chrono::seconds(3));
  21314. // A sub-second remainder exercises the seconds/microseconds split.
  21315. client.set_read_timeout(std::chrono::milliseconds(1500));
  21316. ASSERT_TRUE(client.connect());
  21317. auto start = std::chrono::steady_clock::now();
  21318. std::string msg;
  21319. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21320. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21321. std::chrono::steady_clock::now() - start)
  21322. .count();
  21323. // Above 1s so that dropping the microseconds half of the split fails here.
  21324. // Ignoring the setter altogether would not reach this line at all: a client
  21325. // waits forever by default.
  21326. EXPECT_GE(elapsed, 1400);
  21327. EXPECT_LT(elapsed, 30000);
  21328. }
  21329. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21330. Server svr;
  21331. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21332. if (!req.has_header("Authorization")) {
  21333. res.status = StatusCode::Unauthorized_401;
  21334. res.set_content("Unauthorized", "text/plain");
  21335. return Server::HandlerResponse::Handled;
  21336. }
  21337. return Server::HandlerResponse::Unhandled;
  21338. });
  21339. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21340. std::string msg;
  21341. while (ws.read(msg)) {
  21342. ws.send(msg);
  21343. }
  21344. });
  21345. auto port = svr.bind_to_any_port("localhost");
  21346. std::thread t([&]() { svr.listen_after_bind(); });
  21347. svr.wait_until_ready();
  21348. // Without Authorization header - should be rejected before upgrade
  21349. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21350. EXPECT_FALSE(client1.connect());
  21351. // The rejection is framed like any other HTTP response
  21352. {
  21353. Client cli("localhost", port);
  21354. Headers headers = {{"Upgrade", "websocket"},
  21355. {"Connection", "Upgrade"},
  21356. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21357. {"Sec-WebSocket-Version", "13"}};
  21358. auto res = cli.Get("/ws", headers);
  21359. ASSERT_TRUE(res);
  21360. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21361. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21362. EXPECT_EQ("Unauthorized", res->body);
  21363. }
  21364. // With Authorization header - should succeed
  21365. Headers headers = {{"Authorization", "Bearer token123"}};
  21366. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21367. headers);
  21368. ASSERT_TRUE(client2.connect());
  21369. ASSERT_TRUE(client2.send("hello"));
  21370. std::string msg;
  21371. ASSERT_TRUE(client2.read(msg));
  21372. EXPECT_EQ("hello", msg);
  21373. client2.close();
  21374. svr.stop();
  21375. t.join();
  21376. }
  21377. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21378. Server svr;
  21379. std::atomic<int> pre_request_calls{0};
  21380. std::atomic<bool> route_matched{false};
  21381. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21382. pre_request_calls++;
  21383. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21384. if (req.get_header_value("Authorization") != "Bearer token123") {
  21385. res.status = StatusCode::Unauthorized_401;
  21386. res.set_content("Unauthorized", "text/plain");
  21387. return Server::HandlerResponse::Handled;
  21388. }
  21389. return Server::HandlerResponse::Unhandled;
  21390. });
  21391. std::atomic<bool> handler_called{false};
  21392. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21393. handler_called = true;
  21394. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21395. });
  21396. auto port = svr.bind_to_any_port("localhost");
  21397. std::thread t([&]() { svr.listen_after_bind(); });
  21398. svr.wait_until_ready();
  21399. // Without Authorization header - should be rejected before upgrade
  21400. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21401. "/ws/1");
  21402. EXPECT_FALSE(client1.connect());
  21403. EXPECT_FALSE(handler_called);
  21404. EXPECT_EQ(1, pre_request_calls);
  21405. EXPECT_TRUE(route_matched);
  21406. // The rejection is an ordinary HTTP response, not a protocol switch
  21407. {
  21408. Client cli("localhost", port);
  21409. Headers headers = {{"Upgrade", "websocket"},
  21410. {"Connection", "Upgrade"},
  21411. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21412. {"Sec-WebSocket-Version", "13"}};
  21413. auto res = cli.Get("/ws/1", headers);
  21414. ASSERT_TRUE(res);
  21415. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21416. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21417. EXPECT_EQ("Unauthorized", res->body);
  21418. }
  21419. EXPECT_FALSE(handler_called);
  21420. // With Authorization header - should succeed
  21421. Headers headers = {{"Authorization", "Bearer token123"}};
  21422. ws::WebSocketClient client2(
  21423. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21424. ASSERT_TRUE(client2.connect());
  21425. std::string msg;
  21426. ASSERT_TRUE(client2.read(msg));
  21427. EXPECT_EQ("/ws/:id 2", msg);
  21428. EXPECT_TRUE(handler_called);
  21429. client2.close();
  21430. svr.stop();
  21431. t.join();
  21432. }
  21433. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21434. Server svr;
  21435. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21436. // A read timeout is how a handler gets control back. Without it, a handler
  21437. // parked in read() can never write on the connection it is reading.
  21438. ws.set_read_timeout(std::chrono::milliseconds(100));
  21439. std::string msg;
  21440. while (ws.is_open()) {
  21441. auto r = ws.read(msg);
  21442. if (r == httplib::ws::Timeout) {
  21443. ws.send("tick");
  21444. continue;
  21445. }
  21446. if (r == httplib::ws::Fail) { break; }
  21447. ws.send(msg);
  21448. }
  21449. });
  21450. auto port = svr.bind_to_any_port("localhost");
  21451. std::thread t([&]() { svr.listen_after_bind(); });
  21452. svr.wait_until_ready();
  21453. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21454. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21455. ASSERT_TRUE(client.connect());
  21456. // The client sends nothing, so anything it receives came out of the
  21457. // handler's timeout path.
  21458. std::string msg;
  21459. ASSERT_EQ(client.read(msg), ws::Text);
  21460. EXPECT_EQ("tick", msg);
  21461. client.close();
  21462. svr.stop();
  21463. t.join();
  21464. }
  21465. // Stream::read may return fewer bytes than asked for. This is that contract at
  21466. // its worst -- one byte per call -- which is what a frame header straddling a
  21467. // read buffer's boundary looks like to the frame parser.
  21468. class WsByteAtATimeStream : public Stream {
  21469. public:
  21470. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21471. bool is_readable() const override { return true; }
  21472. bool wait_readable() const override { return true; }
  21473. bool wait_writable() const override { return true; }
  21474. ssize_t read(char *ptr, size_t size) override {
  21475. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21476. *ptr = data_[pos_++];
  21477. return 1;
  21478. }
  21479. ssize_t write(const char *, size_t size) override {
  21480. return static_cast<ssize_t>(size);
  21481. }
  21482. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21483. ip = "127.0.0.1";
  21484. port = 0;
  21485. }
  21486. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21487. ip = "127.0.0.1";
  21488. port = 0;
  21489. }
  21490. socket_t socket() const override { return INVALID_SOCKET; }
  21491. time_t duration() const override { return 0; }
  21492. private:
  21493. std::string data_;
  21494. size_t pos_ = 0;
  21495. };
  21496. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21497. // The payload uses the 16-bit extended length, so the header, the length
  21498. // and the mask key are all multi-byte fields here. Each used to be read
  21499. // with a single read() call, which fails as soon as one is split. The
  21500. // payload is also a little over one read chunk, so it is read in two.
  21501. std::string body;
  21502. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21503. body += static_cast<char>(i % 251);
  21504. }
  21505. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21506. std::string frame;
  21507. frame += static_cast<char>(0x81); // FIN + Text
  21508. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21509. frame += static_cast<char>(body.size() >> 8);
  21510. frame += static_cast<char>(body.size() & 0xff);
  21511. for (size_t i = 0; i < 4; i++) {
  21512. frame += static_cast<char>(mask[i]);
  21513. }
  21514. for (size_t i = 0; i < body.size(); i++) {
  21515. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21516. }
  21517. WsByteAtATimeStream strm(frame);
  21518. ws::Opcode opcode;
  21519. std::string payload;
  21520. bool fin = false;
  21521. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21522. /*expect_masked=*/true, body.size()),
  21523. ws::impl::FrameRead::Ok);
  21524. EXPECT_TRUE(fin);
  21525. EXPECT_EQ(opcode, ws::Opcode::Text);
  21526. EXPECT_EQ(payload, body);
  21527. }
  21528. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21529. // The header announces the largest payload allowed, and only 3 bytes of it
  21530. // ever arrive.
  21531. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21532. std::string frame;
  21533. frame += static_cast<char>(0x82); // FIN + Binary
  21534. frame += static_cast<char>(127); // 64-bit length follows
  21535. for (int shift = 56; shift >= 0; shift -= 8) {
  21536. frame += static_cast<char>((len >> shift) & 0xff);
  21537. }
  21538. frame += "abc";
  21539. detail::BufferStream strm;
  21540. strm.write(frame.data(), frame.size());
  21541. ws::Opcode opcode;
  21542. std::string payload;
  21543. bool fin;
  21544. EXPECT_EQ(
  21545. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  21546. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  21547. ws::impl::FrameRead::Fail);
  21548. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  21549. }
  21550. TEST(WebSocketTest, QueryStringInHandshake) {
  21551. Server svr;
  21552. std::mutex mtx;
  21553. std::string received_target;
  21554. std::string received_token;
  21555. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21556. {
  21557. std::lock_guard<std::mutex> lock(mtx);
  21558. received_target = req.target;
  21559. if (req.has_param("token")) {
  21560. received_token = req.get_param_value("token");
  21561. }
  21562. }
  21563. std::string msg;
  21564. while (ws.read(msg)) {
  21565. ws.send(msg);
  21566. }
  21567. });
  21568. auto port = svr.bind_to_any_port("localhost");
  21569. std::thread t([&]() { svr.listen_after_bind(); });
  21570. svr.wait_until_ready();
  21571. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21572. "/ws?token=ABC&session=123");
  21573. ASSERT_TRUE(client.connect());
  21574. // Round-trip ensures the handler has run and captured the request.
  21575. ASSERT_TRUE(client.send("hello"));
  21576. std::string msg;
  21577. ASSERT_TRUE(client.read(msg));
  21578. EXPECT_EQ("hello", msg);
  21579. client.close();
  21580. {
  21581. std::lock_guard<std::mutex> lock(mtx);
  21582. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21583. EXPECT_EQ("ABC", received_token);
  21584. }
  21585. svr.stop();
  21586. t.join();
  21587. }
  21588. // Run a handshake against a throwaway server and hand the request the server
  21589. // received back to the caller, so tests can assert on the headers the client
  21590. // actually put on the wire.
  21591. static void capture_websocket_handshake_request(
  21592. const Headers &client_headers,
  21593. std::function<void(const Request &, int port)> verify) {
  21594. Server svr;
  21595. std::mutex mtx;
  21596. Request received;
  21597. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21598. {
  21599. std::lock_guard<std::mutex> lock(mtx);
  21600. received = req;
  21601. }
  21602. std::string msg;
  21603. while (ws.read(msg)) {
  21604. ws.send(msg);
  21605. }
  21606. });
  21607. auto port = svr.bind_to_any_port("localhost");
  21608. std::thread t([&]() { svr.listen_after_bind(); });
  21609. auto se = detail::scope_exit([&] {
  21610. svr.stop();
  21611. t.join();
  21612. });
  21613. svr.wait_until_ready();
  21614. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21615. client_headers);
  21616. ASSERT_TRUE(client.connect());
  21617. ASSERT_TRUE(client.send("hello"));
  21618. std::string msg;
  21619. ASSERT_TRUE(client.read(msg));
  21620. client.close();
  21621. {
  21622. std::lock_guard<std::mutex> lock(mtx);
  21623. verify(received, port);
  21624. }
  21625. }
  21626. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21627. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21628. // Non-default port must be present in the Host header. Default ports
  21629. // (80/443) are omitted; that logic is covered by
  21630. // MakeHostAndPortStringTest.
  21631. EXPECT_EQ("localhost:" + std::to_string(port),
  21632. req.get_header_value("Host"));
  21633. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21634. req.get_header_value("User-Agent"));
  21635. EXPECT_FALSE(req.has_header("Accept"));
  21636. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21637. EXPECT_FALSE(req.has_header("Content-Length"));
  21638. });
  21639. }
  21640. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21641. capture_websocket_handshake_request(
  21642. {{"Host", "example.com"},
  21643. {"User-Agent", "custom-agent"},
  21644. {"X-Custom", "value"}},
  21645. [](const Request &req, int) {
  21646. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21647. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21648. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21649. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21650. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21651. });
  21652. }
  21653. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21654. capture_websocket_handshake_request(
  21655. {{"Upgrade", "bogus"},
  21656. {"Connection", "close"},
  21657. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21658. {"Sec-WebSocket-Version", "8"}},
  21659. [](const Request &req, int) {
  21660. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21661. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21662. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21663. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21664. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21665. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21666. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21667. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21668. req.get_header_value("Sec-WebSocket-Key"));
  21669. });
  21670. }
  21671. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21672. // A header the client refuses to send must abort the handshake before any
  21673. // part of it reaches the wire; a lone request line would otherwise sit in
  21674. // the peer's buffer as a truncated request.
  21675. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21676. ASSERT_NE(INVALID_SOCKET, srv);
  21677. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21678. sockaddr_in addr{};
  21679. addr.sin_family = AF_INET;
  21680. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21681. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21682. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21683. ASSERT_EQ(0, ::listen(srv, 1));
  21684. sockaddr_in bound{};
  21685. socklen_t bound_len = sizeof(bound);
  21686. ASSERT_EQ(
  21687. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21688. auto port = ntohs(bound.sin_port);
  21689. ssize_t received = -1;
  21690. std::thread t([&] {
  21691. // Bound every blocking call so a regression fails the test with a bad
  21692. // value instead of hanging the suite.
  21693. fd_set rfds;
  21694. FD_ZERO(&rfds);
  21695. FD_SET(srv, &rfds);
  21696. timeval tv{5, 0};
  21697. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21698. 0) {
  21699. return;
  21700. }
  21701. sockaddr_in cli_addr{};
  21702. socklen_t cli_len = sizeof(cli_addr);
  21703. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21704. if (cli == INVALID_SOCKET) { return; }
  21705. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21706. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21707. char buf[4096];
  21708. received = ::recv(cli, buf, sizeof(buf), 0);
  21709. });
  21710. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21711. // connect() has already shut the socket down by the time it returns false,
  21712. // so the peer sees EOF without waiting for the client to be destroyed.
  21713. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21714. {{"X-Bad", "a\r\nInjected: 1"}});
  21715. EXPECT_FALSE(client.connect());
  21716. t.join();
  21717. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21718. EXPECT_EQ(0, received);
  21719. }
  21720. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21721. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21722. // contains "upgrade" as a substring is a different token and must not
  21723. // start a WebSocket handshake.
  21724. auto make_request = [](const std::vector<std::string> &connection_values) {
  21725. Request req;
  21726. req.method = "GET";
  21727. req.headers.emplace("Upgrade", "websocket");
  21728. for (const auto &value : connection_values) {
  21729. req.headers.emplace("Connection", value);
  21730. }
  21731. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21732. req.headers.emplace("Sec-WebSocket-Version", "13");
  21733. return req;
  21734. };
  21735. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21736. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21737. EXPECT_TRUE(
  21738. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21739. EXPECT_TRUE(
  21740. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21741. EXPECT_TRUE(
  21742. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21743. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21744. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21745. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21746. EXPECT_FALSE(
  21747. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21748. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21749. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21750. }
  21751. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21752. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21753. // asks recipients to match each protocol-name case-insensitively, and RFC
  21754. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21755. // client naming websocket alongside another protocol, or on a second field
  21756. // line, is offering websocket; a value that merely contains "websocket" as a
  21757. // substring is a different protocol name and is not.
  21758. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21759. Request req;
  21760. req.method = "GET";
  21761. for (const auto &value : upgrade_values) {
  21762. req.headers.emplace("Upgrade", value);
  21763. }
  21764. req.headers.emplace("Connection", "Upgrade");
  21765. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21766. req.headers.emplace("Sec-WebSocket-Version", "13");
  21767. return req;
  21768. };
  21769. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21770. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21771. EXPECT_TRUE(
  21772. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21773. EXPECT_TRUE(
  21774. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21775. EXPECT_TRUE(
  21776. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21777. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21778. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21779. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21780. EXPECT_FALSE(
  21781. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21782. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21783. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21784. }
  21785. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21786. Server svr;
  21787. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21788. auto port = svr.bind_to_any_port("localhost");
  21789. std::thread t([&]() { svr.listen_after_bind(); });
  21790. auto se = detail::scope_exit([&] {
  21791. svr.stop();
  21792. t.join();
  21793. });
  21794. svr.wait_until_ready();
  21795. Headers headers = {{"Upgrade", "websocket"},
  21796. {"Connection", "notupgrade"},
  21797. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21798. {"Sec-WebSocket-Version", "13"}};
  21799. Client cli("localhost", port);
  21800. auto res = cli.Get("/ws", headers);
  21801. // The route exists only as a WebSocket route, so a request that fails the
  21802. // handshake check falls through to ordinary routing.
  21803. ASSERT_TRUE(res);
  21804. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21805. }
  21806. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21807. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21808. // Connection value is the only thing left for the client to reject.
  21809. Server svr;
  21810. svr.Get("/ws", [](const Request &req, Response &res) {
  21811. res.status = StatusCode::SwitchingProtocol_101;
  21812. res.set_header("Upgrade", "websocket");
  21813. res.set_header("Connection", "notupgrade");
  21814. res.set_header("Sec-WebSocket-Accept",
  21815. detail::websocket_accept_key(
  21816. req.get_header_value("Sec-WebSocket-Key")));
  21817. });
  21818. auto port = svr.bind_to_any_port("localhost");
  21819. std::thread t([&]() { svr.listen_after_bind(); });
  21820. auto se = detail::scope_exit([&] {
  21821. svr.stop();
  21822. t.join();
  21823. });
  21824. svr.wait_until_ready();
  21825. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21826. auto res = client.connect();
  21827. EXPECT_FALSE(res);
  21828. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21829. EXPECT_FALSE(client.is_open());
  21830. }
  21831. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21832. Server svr;
  21833. svr.Get("/ws", [](const Request &req, Response &res) {
  21834. res.status = StatusCode::SwitchingProtocol_101;
  21835. res.set_header("Upgrade", "websocket");
  21836. res.set_header("Connection", "Upgrade");
  21837. res.set_header("Sec-WebSocket-Accept",
  21838. detail::websocket_accept_key(
  21839. req.get_header_value("Sec-WebSocket-Key")));
  21840. res.set_header("Sec-WebSocket-Protocol", "admin");
  21841. });
  21842. auto port = svr.bind_to_any_port("localhost");
  21843. std::thread t([&]() { svr.listen_after_bind(); });
  21844. auto se = detail::scope_exit([&] {
  21845. svr.stop();
  21846. t.join();
  21847. });
  21848. svr.wait_until_ready();
  21849. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21850. // Server selects a subprotocol the client never offered
  21851. {
  21852. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21853. ws::WebSocketClient client(url, headers);
  21854. auto res = client.connect();
  21855. EXPECT_FALSE(res);
  21856. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21857. EXPECT_FALSE(client.is_open());
  21858. EXPECT_TRUE(client.subprotocol().empty());
  21859. }
  21860. // Client offered none but the server named one anyway
  21861. {
  21862. ws::WebSocketClient client(url);
  21863. auto res = client.connect();
  21864. EXPECT_FALSE(res);
  21865. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21866. EXPECT_FALSE(client.is_open());
  21867. EXPECT_TRUE(client.subprotocol().empty());
  21868. }
  21869. }
  21870. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21871. // The socket path doubles as the URL host, so it must not contain '/'.
  21872. const char *shard = getenv("GTEST_SHARD_INDEX");
  21873. const std::string sock_path =
  21874. shard ? std::string("httplib-ws-") + shard + ".sock"
  21875. : std::string("httplib-ws.sock");
  21876. std::remove(sock_path.c_str());
  21877. Server svr;
  21878. std::mutex mtx;
  21879. std::string received_host;
  21880. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21881. {
  21882. std::lock_guard<std::mutex> lock(mtx);
  21883. received_host = req.get_header_value("Host");
  21884. }
  21885. std::string msg;
  21886. while (ws.read(msg)) {
  21887. ws.send(msg);
  21888. }
  21889. });
  21890. svr.set_address_family(AF_UNIX);
  21891. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21892. auto se = detail::scope_exit([&] {
  21893. svr.stop();
  21894. t.join();
  21895. std::remove(sock_path.c_str());
  21896. });
  21897. svr.wait_until_ready();
  21898. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21899. client.set_address_family(AF_UNIX);
  21900. ASSERT_TRUE(client.connect());
  21901. ASSERT_TRUE(client.send("hello"));
  21902. std::string msg;
  21903. ASSERT_TRUE(client.read(msg));
  21904. client.close();
  21905. {
  21906. std::lock_guard<std::mutex> lock(mtx);
  21907. // There is no host:port for a Unix socket, so the same "localhost"
  21908. // placeholder the HTTP client uses is expected.
  21909. EXPECT_EQ("localhost", received_host);
  21910. }
  21911. }
  21912. // Two threads must never parse WebSocket frames from the same stream.
  21913. // close() used to read the peer's Close reply with its own frame read, so it
  21914. // raced a reader thread that was in the middle of a payload: the payload loop
  21915. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21916. // so bytes taken by close() were replaced with bytes from further along the
  21917. // stream. The message kept its length and silently changed content.
  21918. //
  21919. // The raw peer below sends a frame header plus part of the payload, waits for
  21920. // the handler to call close(), and only then sends the rest. Whichever thread
  21921. // would win the race for those bytes, the message must arrive intact, because
  21922. // close() must not touch the stream while read() owns it.
  21923. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21924. #ifndef _WIN32
  21925. signal(SIGPIPE, SIG_IGN);
  21926. #endif
  21927. const size_t payload_len = 120; // fits the 7-bit length field
  21928. const size_t prefix_len = 8;
  21929. const int attempts = 8;
  21930. std::string expected(payload_len, '\0');
  21931. for (size_t i = 0; i < payload_len; i++) {
  21932. expected[i] = static_cast<char>('a' + i % 26);
  21933. }
  21934. std::atomic<bool> peer_stalled{false};
  21935. std::atomic<bool> handler_done{false};
  21936. std::mutex received_mutex;
  21937. std::vector<std::string> received;
  21938. // Bound every wait, so a regression fails the test instead of hanging the
  21939. // suite.
  21940. auto wait_for = [](const std::atomic<bool> &flag) {
  21941. for (int i = 0; i < 500 && !flag; i++) {
  21942. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21943. }
  21944. };
  21945. Server svr;
  21946. svr.set_websocket_ping_interval(0);
  21947. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21948. std::thread reader([&]() {
  21949. std::string msg;
  21950. while (ws.read(msg)) {
  21951. std::lock_guard<std::mutex> guard(received_mutex);
  21952. received.push_back(msg);
  21953. }
  21954. });
  21955. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21956. // inside read_websocket_frame() when close() runs.
  21957. wait_for(peer_stalled);
  21958. ws.close();
  21959. reader.join();
  21960. handler_done = true;
  21961. });
  21962. auto port = svr.bind_to_any_port("127.0.0.1");
  21963. std::thread t([&]() { svr.listen_after_bind(); });
  21964. auto se = detail::scope_exit([&] {
  21965. svr.stop();
  21966. t.join();
  21967. });
  21968. svr.wait_until_ready();
  21969. auto send_bytes = [](socket_t s, const std::string &data) {
  21970. #ifdef _WIN32
  21971. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21972. #else
  21973. auto n = ::send(s, data.data(), data.size(), 0);
  21974. #endif
  21975. return n == static_cast<decltype(n)>(data.size());
  21976. };
  21977. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21978. // Every length used here fits the 7-bit length field.
  21979. auto masked_header = [](uint8_t first_byte, size_t len) {
  21980. std::string h;
  21981. h += static_cast<char>(first_byte);
  21982. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21983. h.append(4, '\0'); // mask key
  21984. return h;
  21985. };
  21986. for (int attempt = 0; attempt < attempts; attempt++) {
  21987. peer_stalled = false;
  21988. handler_done = false;
  21989. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21990. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21991. auto se_sock = detail::scope_exit([&] {
  21992. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21993. });
  21994. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21995. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21996. sockaddr_in addr{};
  21997. addr.sin_family = AF_INET;
  21998. addr.sin_port = htons(static_cast<uint16_t>(port));
  21999. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22000. ASSERT_EQ(
  22001. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22002. << "attempt " << attempt;
  22003. ASSERT_TRUE(send_bytes(sock,
  22004. "GET /ws HTTP/1.1\r\n"
  22005. "Host: 127.0.0.1\r\n"
  22006. "Upgrade: websocket\r\n"
  22007. "Connection: Upgrade\r\n"
  22008. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22009. "Sec-WebSocket-Version: 13\r\n"
  22010. "\r\n"))
  22011. << "attempt " << attempt;
  22012. std::string response;
  22013. while (response.find("\r\n\r\n") == std::string::npos) {
  22014. char buf[512];
  22015. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22016. if (n <= 0) { break; }
  22017. response.append(buf, static_cast<size_t>(n));
  22018. }
  22019. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22020. << "attempt " << attempt;
  22021. // Send the header of a Binary message but only the first prefix_len bytes
  22022. // of its payload, leaving the reader thread stalled inside the payload.
  22023. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22024. expected.substr(0, prefix_len)))
  22025. << "attempt " << attempt;
  22026. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22027. peer_stalled = true;
  22028. // Let close() send its Close frame and park in its own read before the
  22029. // rest of the payload arrives, so both threads are waiting for it.
  22030. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22031. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22032. close_frame += static_cast<char>(0x03); // status 1000
  22033. close_frame += static_cast<char>(0xE8);
  22034. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22035. << "attempt " << attempt;
  22036. // Closing the peer releases the reader thread even on the buggy path,
  22037. // where it waits for bytes another thread already consumed.
  22038. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22039. detail::close_socket(sock);
  22040. sock = INVALID_SOCKET;
  22041. wait_for(handler_done);
  22042. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22043. }
  22044. std::lock_guard<std::mutex> guard(received_mutex);
  22045. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22046. << "a message in flight when close() ran was dropped";
  22047. for (size_t i = 0; i < received.size(); i++) {
  22048. EXPECT_EQ(expected, received[i]) << "message " << i;
  22049. }
  22050. }
  22051. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22052. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22053. protected:
  22054. void SetUp() override {
  22055. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22056. SERVER_PRIVATE_KEY_FILE);
  22057. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22058. std::string msg;
  22059. ws::ReadResult ret;
  22060. while ((ret = ws.read(msg))) {
  22061. if (ret == ws::Binary) {
  22062. ws.send(msg.data(), msg.size());
  22063. } else {
  22064. ws.send(msg);
  22065. }
  22066. }
  22067. });
  22068. port_ = server_->bind_to_any_port(HOST);
  22069. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22070. server_->wait_until_ready();
  22071. }
  22072. void TearDown() override {
  22073. server_->stop();
  22074. if (server_thread_.joinable()) { server_thread_.join(); }
  22075. }
  22076. std::unique_ptr<SSLServer> server_;
  22077. std::thread server_thread_;
  22078. int port_ = 0;
  22079. };
  22080. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22081. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22082. "/ws-echo");
  22083. client.enable_server_certificate_verification(false);
  22084. ASSERT_TRUE(client.connect());
  22085. ASSERT_TRUE(client.is_open());
  22086. ASSERT_TRUE(client.send("Hello WSS"));
  22087. std::string msg;
  22088. EXPECT_EQ(ws::Text, client.read(msg));
  22089. EXPECT_EQ("Hello WSS", msg);
  22090. client.close();
  22091. }
  22092. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22093. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22094. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22095. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22096. // client (without calling close() first) is the only path that runs
  22097. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22098. // bug exactly.
  22099. //
  22100. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22101. // when linked against an instrumented libssl; run under Valgrind to catch it
  22102. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22103. // suite (the freed session otherwise stalls on the close handshake) — this test
  22104. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22105. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22106. {
  22107. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22108. "/ws-echo");
  22109. client.enable_server_certificate_verification(false);
  22110. client.set_read_timeout(2, 0);
  22111. client.set_write_timeout(2, 0);
  22112. ASSERT_TRUE(client.connect());
  22113. ASSERT_TRUE(client.is_open());
  22114. ASSERT_TRUE(client.send("still open"));
  22115. // Intentionally do NOT call client.close(): leaving scope runs
  22116. // shutdown_and_close() with the WebSocket still open, which must send the
  22117. // close frame while the TLS session is still alive.
  22118. }
  22119. }
  22120. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22121. // shutdown_and_close() at the start of connect(), reproducing the same
  22122. // use-after-free within the test body rather than at scope exit. The second
  22123. // connect must succeed and echo, proving the close handshake ran over a live
  22124. // session. See the note above about memory-tool requirements.
  22125. TEST_F(WebSocketSSLIntegrationTest,
  22126. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22127. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22128. "/ws-echo");
  22129. client.enable_server_certificate_verification(false);
  22130. client.set_read_timeout(2, 0);
  22131. client.set_write_timeout(2, 0);
  22132. ASSERT_TRUE(client.connect());
  22133. ASSERT_TRUE(client.is_open());
  22134. ASSERT_TRUE(client.send("still open"));
  22135. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22136. // the still-open connection, which must not touch a freed TLS session.
  22137. ASSERT_TRUE(client.connect());
  22138. ASSERT_TRUE(client.is_open());
  22139. ASSERT_TRUE(client.send("after reconnect"));
  22140. std::string msg;
  22141. EXPECT_EQ(ws::Text, client.read(msg));
  22142. EXPECT_EQ("after reconnect", msg);
  22143. client.close();
  22144. }
  22145. #endif
  22146. #ifdef CPPHTTPLIB_SSL_ENABLED
  22147. class WebSocketSSLCATest : public ::testing::Test {
  22148. protected:
  22149. void SetUp() override {
  22150. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22151. SERVER_PRIVATE_KEY_FILE);
  22152. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22153. std::string msg;
  22154. while (ws.read(msg)) {
  22155. ws.send(msg);
  22156. }
  22157. });
  22158. port_ = server_->bind_to_any_port("127.0.0.1");
  22159. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22160. server_->wait_until_ready();
  22161. }
  22162. void TearDown() override {
  22163. server_->stop();
  22164. if (server_thread_.joinable()) { server_thread_.join(); }
  22165. }
  22166. std::string url() const {
  22167. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22168. }
  22169. std::unique_ptr<SSLServer> server_;
  22170. std::thread server_thread_;
  22171. int port_ = 0;
  22172. };
  22173. // A custom CA loaded as PEM verifies the server with full certificate
  22174. // verification enabled
  22175. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22176. ws::WebSocketClient client(url());
  22177. std::string cert;
  22178. read_file(SERVER_CERT2_FILE, cert);
  22179. client.load_ca_cert_store(cert.c_str(), cert.size());
  22180. ASSERT_TRUE(client.connect());
  22181. ASSERT_TRUE(client.send("hello"));
  22182. std::string msg;
  22183. EXPECT_EQ(ws::Text, client.read(msg));
  22184. EXPECT_EQ("hello", msg);
  22185. client.close();
  22186. }
  22187. // A custom CA that does not cover the server must fail verification (the
  22188. // custom CA is exclusive; system certs are not loaded alongside it)
  22189. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22190. ws::WebSocketClient client(url());
  22191. std::string cert;
  22192. read_file(CLIENT_CA_CERT_FILE, cert);
  22193. client.load_ca_cert_store(cert.c_str(), cert.size());
  22194. auto res = client.connect();
  22195. ASSERT_FALSE(res);
  22196. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22197. EXPECT_EQ(-1, res.status());
  22198. EXPECT_NE(0u, res.ssl_backend_error());
  22199. }
  22200. // The same CA as a file path rather than PEM in memory
  22201. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22202. ws::WebSocketClient client(url());
  22203. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22204. ASSERT_TRUE(client.connect());
  22205. ASSERT_TRUE(client.send("hello"));
  22206. std::string msg;
  22207. EXPECT_EQ(ws::Text, client.read(msg));
  22208. EXPECT_EQ("hello", msg);
  22209. client.close();
  22210. }
  22211. // ...and a CA file that does not cover the server still fails, so it is the
  22212. // path above that decides the outcome
  22213. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22214. ws::WebSocketClient client(url());
  22215. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22216. ASSERT_FALSE(client.connect());
  22217. }
  22218. // Regression test: reconnecting with a native custom CA store used to reuse
  22219. // a store handle the previous TLS context had already freed (use-after-free
  22220. // under the OpenSSL backend). The context now lives as long as the client.
  22221. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22222. ws::WebSocketClient client(url());
  22223. std::string cert;
  22224. read_file(SERVER_CERT2_FILE, cert);
  22225. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22226. ASSERT_TRUE(client.connect());
  22227. client.close();
  22228. ASSERT_TRUE(client.connect());
  22229. ASSERT_TRUE(client.send("again"));
  22230. std::string msg;
  22231. EXPECT_EQ(ws::Text, client.read(msg));
  22232. EXPECT_EQ("again", msg);
  22233. client.close();
  22234. }
  22235. // Regression test: a certificate with a trusted chain but no identity match
  22236. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22237. // verification entirely for IP hosts, so this connection succeeded there.
  22238. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22239. // chain verification while the identity check must still fail.
  22240. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22241. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22242. ASSERT_TRUE(svr.is_valid());
  22243. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22244. std::string msg;
  22245. while (ws.read(msg)) {
  22246. ws.send(msg);
  22247. }
  22248. });
  22249. auto port = svr.bind_to_any_port("127.0.0.1");
  22250. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22251. auto se = detail::scope_exit([&] {
  22252. svr.stop();
  22253. t.join();
  22254. });
  22255. svr.wait_until_ready();
  22256. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22257. "/echo");
  22258. std::string cert;
  22259. read_file(SERVER_CERT_FILE, cert);
  22260. client.load_ca_cert_store(cert.c_str(), cert.size());
  22261. ASSERT_FALSE(client.connect());
  22262. }
  22263. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22264. // SNI, so nothing binds the host name to the TLS session. These bind the
  22265. // server to "localhost" instead, the only shape that exercises the SNI and
  22266. // hostname-verification path with certificate verification left enabled.
  22267. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22268. protected:
  22269. void Start(const char *cert_file) {
  22270. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22271. SERVER_PRIVATE_KEY_FILE);
  22272. ASSERT_TRUE(server_->is_valid());
  22273. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22274. std::string msg;
  22275. while (ws.read(msg)) {
  22276. ws.send(msg);
  22277. }
  22278. });
  22279. port_ = server_->bind_to_any_port("localhost");
  22280. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22281. server_->wait_until_ready();
  22282. }
  22283. void TearDown() override {
  22284. if (server_) { server_->stop(); }
  22285. if (server_thread_.joinable()) { server_thread_.join(); }
  22286. }
  22287. std::string url() const {
  22288. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22289. }
  22290. std::unique_ptr<SSLServer> server_;
  22291. std::thread server_thread_;
  22292. int port_ = 0;
  22293. };
  22294. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22295. // out and the connection is usable
  22296. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22297. Start(SERVER_CERT2_FILE);
  22298. ws::WebSocketClient client(url());
  22299. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22300. ASSERT_TRUE(client.connect());
  22301. ASSERT_TRUE(client.send("hello"));
  22302. std::string msg;
  22303. EXPECT_EQ(ws::Text, client.read(msg));
  22304. EXPECT_EQ("hello", msg);
  22305. client.close();
  22306. }
  22307. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22308. // while the identity check must still reject "localhost"
  22309. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22310. Start(SERVER_CERT_FILE);
  22311. ws::WebSocketClient client(url());
  22312. client.set_ca_cert_path(SERVER_CERT_FILE);
  22313. auto res = client.connect();
  22314. ASSERT_FALSE(res);
  22315. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22316. EXPECT_EQ(-1, res.status());
  22317. }
  22318. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22319. // disabled: the chain is still checked, only the identity check is skipped
  22320. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22321. Start(SERVER_CERT_FILE);
  22322. ws::WebSocketClient client(url());
  22323. client.set_ca_cert_path(SERVER_CERT_FILE);
  22324. client.enable_server_hostname_verification(false);
  22325. ASSERT_TRUE(client.connect());
  22326. ASSERT_TRUE(client.send("hello"));
  22327. std::string msg;
  22328. EXPECT_EQ(ws::Text, client.read(msg));
  22329. EXPECT_EQ("hello", msg);
  22330. client.close();
  22331. }
  22332. // A CA that did not sign the server certificate fails the chain, even though
  22333. // the name would match
  22334. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22335. Start(SERVER_CERT2_FILE);
  22336. ws::WebSocketClient client(url());
  22337. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22338. ASSERT_FALSE(client.connect());
  22339. }
  22340. // With verification disabled, neither the chain nor the name is checked
  22341. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22342. Start(SERVER_CERT_FILE);
  22343. ws::WebSocketClient client(url());
  22344. client.enable_server_certificate_verification(false);
  22345. ASSERT_TRUE(client.connect());
  22346. ASSERT_TRUE(client.send("hello"));
  22347. std::string msg;
  22348. EXPECT_EQ(ws::Text, client.read(msg));
  22349. EXPECT_EQ("hello", msg);
  22350. client.close();
  22351. }
  22352. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22353. protected:
  22354. void SetUp() override {
  22355. server_ = httplib::detail::make_unique<SSLServer>(
  22356. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22357. ASSERT_TRUE(server_->is_valid());
  22358. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22359. std::string msg;
  22360. while (ws.read(msg)) {
  22361. ws.send(msg);
  22362. }
  22363. });
  22364. port_ = server_->bind_to_any_port("localhost");
  22365. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22366. server_->wait_until_ready();
  22367. }
  22368. void TearDown() override {
  22369. server_->stop();
  22370. if (server_thread_.joinable()) { server_thread_.join(); }
  22371. }
  22372. std::string url() const {
  22373. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22374. }
  22375. void ConnectWithClientCert(const std::string &client_cert_file,
  22376. const std::string &client_private_key_file,
  22377. const char *private_key_password) {
  22378. std::string cert_pem, key_pem;
  22379. read_file(client_cert_file, cert_pem);
  22380. read_file(client_private_key_file, key_pem);
  22381. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22382. key_pem.c_str(), key_pem.size(),
  22383. private_key_password};
  22384. ws::WebSocketClient client(url(), pem);
  22385. ASSERT_TRUE(client.is_valid());
  22386. client.enable_server_certificate_verification(false);
  22387. ASSERT_TRUE(client.connect());
  22388. ASSERT_TRUE(client.send("hello"));
  22389. std::string msg;
  22390. EXPECT_EQ(ws::Text, client.read(msg));
  22391. EXPECT_EQ("hello", msg);
  22392. client.close();
  22393. }
  22394. std::unique_ptr<SSLServer> server_;
  22395. std::thread server_thread_;
  22396. int port_ = 0;
  22397. };
  22398. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22399. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22400. }
  22401. // Control for the tests above: the fixture's server really does require a
  22402. // client certificate, so it is the PEM the constructor installed that decides
  22403. // the outcome.
  22404. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22405. ws::WebSocketClient client(url());
  22406. ASSERT_TRUE(client.is_valid());
  22407. client.enable_server_certificate_verification(false);
  22408. EXPECT_FALSE(client.connect());
  22409. }
  22410. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22411. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22412. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22413. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22414. }
  22415. #endif
  22416. #if !defined(_WIN32)
  22417. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22418. auto secret_dir = std::string("./symlink_test_secret");
  22419. auto served_dir = std::string("./symlink_test_served");
  22420. auto secret_file = secret_dir + "/secret.txt";
  22421. auto symlink_path = served_dir + "/escape";
  22422. // Setup: create directories and files
  22423. mkdir(secret_dir.c_str(), 0755);
  22424. mkdir(served_dir.c_str(), 0755);
  22425. {
  22426. std::ofstream ofs(secret_file);
  22427. ofs << "SECRET_DATA";
  22428. }
  22429. // Create symlink using absolute path so it resolves correctly
  22430. #ifdef PATH_MAX
  22431. char abs_secret[PATH_MAX];
  22432. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22433. #else
  22434. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22435. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22436. ASSERT_NE(nullptr, abs_secret);
  22437. #endif
  22438. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22439. auto se = detail::scope_exit([&] {
  22440. unlink(symlink_path.c_str());
  22441. unlink(secret_file.c_str());
  22442. rmdir(served_dir.c_str());
  22443. rmdir(secret_dir.c_str());
  22444. });
  22445. Server svr;
  22446. svr.set_mount_point("/", served_dir);
  22447. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22448. auto se2 = detail::scope_exit([&] {
  22449. svr.stop();
  22450. listen_thread.join();
  22451. });
  22452. svr.wait_until_ready();
  22453. Client cli("localhost", PORT);
  22454. // Symlink pointing outside base dir should be blocked
  22455. auto res = cli.Get("/escape/secret.txt");
  22456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22457. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22458. }
  22459. #endif
  22460. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22461. // "GET /smuggled" request), reads the first response, and only then sends the
  22462. // embedded request as the body. Returns how many times /smuggled ran.
  22463. //
  22464. // The body is sent AFTER receiving the first response (as in the original
  22465. // PoC) so that the stream_line_reader cannot buffer it together with the
  22466. // headers of the first request.
  22467. static int count_smuggled_requests(const std::string &outer_head,
  22468. std::string &first_response) {
  22469. Server svr;
  22470. svr.set_mount_point("/", "./www");
  22471. std::atomic<int> smuggled_count(0);
  22472. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22473. smuggled_count++;
  22474. res.set_content("oops", "text/plain");
  22475. });
  22476. svr.Post("/post", [&](const Request &req, Response &res) {
  22477. res.set_content(req.body, "text/plain");
  22478. });
  22479. auto port = svr.bind_to_any_port("localhost");
  22480. thread t = thread([&] { svr.listen_after_bind(); });
  22481. auto se = detail::scope_exit([&] {
  22482. svr.stop();
  22483. t.join();
  22484. });
  22485. svr.wait_until_ready();
  22486. auto error = Error::Success;
  22487. auto sock = detail::create_client_socket(
  22488. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22489. /*connection_timeout_sec=*/2, 0,
  22490. /*read_timeout_sec=*/2, 0,
  22491. /*write_timeout_sec=*/2, 0, std::string(), error);
  22492. EXPECT_NE(INVALID_SOCKET, sock);
  22493. if (sock == INVALID_SOCKET) { return -1; }
  22494. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22495. // The "smuggled" request will be sent as the body of the outer request
  22496. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22497. "Host: localhost\r\n"
  22498. "Connection: close\r\n"
  22499. "\r\n";
  22500. auto head = outer_head;
  22501. auto len = std::to_string(smuggled.size());
  22502. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22503. pos = head.find("{len}", pos + len.size())) {
  22504. head.replace(pos, 5, len);
  22505. }
  22506. // Step 1: Send only the outer request headers (no body yet)
  22507. auto sent = send(sock, head.data(), head.size(), 0);
  22508. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22509. // Step 2: Read the first response
  22510. char buf[4096];
  22511. for (;;) {
  22512. auto n = recv(sock, buf, sizeof(buf), 0);
  22513. if (n <= 0) break;
  22514. first_response.append(buf, static_cast<size_t>(n));
  22515. // Stop once we have a complete response (headers + body)
  22516. auto hdr_end = first_response.find("\r\n\r\n");
  22517. if (hdr_end != std::string::npos) {
  22518. // Check for Content-Length to know when the body is complete
  22519. auto cl_pos = first_response.find("Content-Length:");
  22520. if (cl_pos != std::string::npos) {
  22521. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22522. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22523. auto cl = std::stoul(
  22524. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22525. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22526. } else {
  22527. break; // No Content-Length, assume headers-only response
  22528. }
  22529. }
  22530. }
  22531. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22532. // vulnerable server the keep-alive loop reads this as a second request. The
  22533. // server may already have closed the connection, so the result is ignored.
  22534. send(sock, smuggled.data(), smuggled.size(), 0);
  22535. // Half-close so that a server which drained the body sees EOF and closes,
  22536. // instead of the read below waiting for the read timeout.
  22537. #ifdef _WIN32
  22538. ::shutdown(sock, SD_SEND);
  22539. #else
  22540. ::shutdown(sock, SHUT_WR);
  22541. #endif
  22542. // Step 4: Read until the server closes the connection
  22543. for (;;) {
  22544. auto n = recv(sock, buf, sizeof(buf), 0);
  22545. if (n <= 0) break;
  22546. }
  22547. return smuggled_count.load();
  22548. }
  22549. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22550. // A GET request with Content-Length to a static file handler must have its
  22551. // body drained before the keep-alive connection is reused. Otherwise the
  22552. // unread body bytes are interpreted as the next HTTP request.
  22553. std::string first_response;
  22554. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22555. "Host: localhost\r\n"
  22556. "Content-Length: {len}\r\n"
  22557. "\r\n",
  22558. first_response));
  22559. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22560. }
  22561. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22562. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22563. // be answered with 400 and the connection closed. Treating it as "no body"
  22564. // leaves the body to be parsed as the next request.
  22565. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22566. const char *targets[] = {
  22567. "GET /file", // handler that never reads the body
  22568. "GET /not-found", // no handler matches (404)
  22569. "POST /post", // handler that reads the body
  22570. };
  22571. for (auto target : targets) {
  22572. for (auto value : values) {
  22573. std::string first_response;
  22574. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22575. " HTTP/1.1\r\n"
  22576. "Host: localhost\r\n"
  22577. "Content-Length: " +
  22578. value + "\r\n\r\n",
  22579. first_response))
  22580. << target << " with Content-Length: " << value;
  22581. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22582. << target << " with Content-Length: " << value;
  22583. }
  22584. }
  22585. }
  22586. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22587. // A 400 for an unparseable request line leaves the rest of the message
  22588. // unread, so the connection must be closed rather than reused.
  22589. std::string first_response;
  22590. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22591. "Host: localhost\r\n"
  22592. "Content-Length: {len}\r\n"
  22593. "\r\n",
  22594. first_response));
  22595. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22596. }
  22597. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22598. // Same as above for a header block that fails to parse.
  22599. std::string first_response;
  22600. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22601. "Host: localhost\r\n"
  22602. "Bad Header\r\n"
  22603. "Content-Length: {len}\r\n"
  22604. "\r\n",
  22605. first_response));
  22606. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22607. }
  22608. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22609. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22610. // server must not read another request on that connection, even when the
  22611. // request had no body to drain.
  22612. std::string first_response;
  22613. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22614. "Host: localhost\r\n"
  22615. "\r\n",
  22616. first_response));
  22617. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22618. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22619. }
  22620. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  22621. // A content reader that stops early leaves the stream inside the body.
  22622. // Draining the whole Content-Length from there, or reading the body again,
  22623. // reads into the next request, and whatever follows is parsed as a request
  22624. // of its own.
  22625. Server svr;
  22626. std::atomic<int> smuggled_count(0);
  22627. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  22628. svr.Post("/upload", [](const Request &req, Response &res,
  22629. const ContentReader &content_reader) {
  22630. // Stop at the last chunk, so the whole body has been read however it
  22631. // arrives.
  22632. auto length = req.get_header_value_u64("Content-Length");
  22633. size_t total = 0;
  22634. auto consumed = content_reader([&](const char *, size_t n) {
  22635. total += n;
  22636. return total < length;
  22637. });
  22638. EXPECT_FALSE(consumed);
  22639. if (req.has_param("retry")) {
  22640. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  22641. }
  22642. // Replace the 400 the aborted read set, which would close the connection.
  22643. res.set_redirect("/done");
  22644. });
  22645. auto port = svr.bind_to_any_port(HOST);
  22646. thread t = thread([&] { svr.listen_after_bind(); });
  22647. auto se = detail::scope_exit([&] {
  22648. svr.stop();
  22649. t.join();
  22650. });
  22651. svr.wait_until_ready();
  22652. // A front end sees the second request as a POST whose body is the GET. The
  22653. // first body is as long as the POST's headers, so draining it again reads
  22654. // exactly those and leaves the GET to be parsed next.
  22655. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  22656. "Host: localhost\r\n"
  22657. "\r\n";
  22658. std::string second_head = "POST /post HTTP/1.1\r\n"
  22659. "Host: localhost\r\n"
  22660. "Content-Length: " +
  22661. std::to_string(inner.size()) +
  22662. "\r\n"
  22663. "\r\n";
  22664. for (auto target : {"/upload", "/upload?retry"}) {
  22665. smuggled_count = 0;
  22666. std::string request = "POST " + std::string(target) +
  22667. " HTTP/1.1\r\n"
  22668. "Host: localhost\r\n"
  22669. "Content-Length: " +
  22670. std::to_string(second_head.size()) +
  22671. "\r\n"
  22672. "\r\n" +
  22673. std::string(second_head.size(), 'A') + second_head +
  22674. inner;
  22675. std::string response;
  22676. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  22677. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  22678. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  22679. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  22680. EXPECT_EQ(0, smuggled_count.load()) << target;
  22681. }
  22682. }
  22683. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22684. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22685. // must be rejected with 400 Bad Request.
  22686. Server svr;
  22687. svr.Post("/test", [&](const Request &, Response &res) {
  22688. res.set_content("ok", "text/plain");
  22689. });
  22690. thread t = thread([&] { svr.listen(HOST, PORT); });
  22691. auto se = detail::scope_exit([&] {
  22692. svr.stop();
  22693. t.join();
  22694. ASSERT_FALSE(svr.is_running());
  22695. });
  22696. svr.wait_until_ready();
  22697. // Exact "chunked"
  22698. {
  22699. auto req = "POST /test HTTP/1.1\r\n"
  22700. "Host: localhost\r\n"
  22701. "Content-Length: 5\r\n"
  22702. "Transfer-Encoding: chunked\r\n"
  22703. "Connection: close\r\n"
  22704. "\r\n"
  22705. "hello";
  22706. std::string response;
  22707. ASSERT_TRUE(send_request(1, req, &response));
  22708. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22709. response.substr(0, response.find("\r\n")));
  22710. }
  22711. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22712. {
  22713. auto req = "POST /test HTTP/1.1\r\n"
  22714. "Host: localhost\r\n"
  22715. "Content-Length: 5\r\n"
  22716. "Transfer-Encoding: gzip, chunked\r\n"
  22717. "Connection: close\r\n"
  22718. "\r\n"
  22719. "hello";
  22720. std::string response;
  22721. ASSERT_TRUE(send_request(1, req, &response));
  22722. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22723. response.substr(0, response.find("\r\n")));
  22724. }
  22725. }
  22726. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22727. Server svr;
  22728. svr.Post("/test", [&](const Request &, Response &res) {
  22729. res.set_content("ok", "text/plain");
  22730. });
  22731. thread t = thread([&] { svr.listen(HOST, PORT); });
  22732. auto se = detail::scope_exit([&] {
  22733. svr.stop();
  22734. t.join();
  22735. ASSERT_FALSE(svr.is_running());
  22736. });
  22737. svr.wait_until_ready();
  22738. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22739. // length cannot be determined, so the server must answer 400 and close
  22740. // rather than treat the request as bodyless and leave the body in the
  22741. // socket for the next request to pick up.
  22742. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22743. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22744. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22745. std::string response;
  22746. ASSERT_TRUE(send_request(1, req, &response));
  22747. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22748. response.substr(0, response.find("\r\n")))
  22749. << transfer_encoding;
  22750. }
  22751. // RFC 9110 5.3: the codings may also be split across several
  22752. // Transfer-Encoding lines, which combine in the order they were received.
  22753. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22754. // just like the single-line "chunked, gzip" above.
  22755. {
  22756. auto req = "POST /test HTTP/1.1\r\n"
  22757. "Host: localhost\r\n"
  22758. "Transfer-Encoding: chunked\r\n"
  22759. "Transfer-Encoding: gzip\r\n"
  22760. "\r\n"
  22761. "0\r\n\r\n";
  22762. std::string response;
  22763. ASSERT_TRUE(send_request(1, req, &response));
  22764. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22765. response.substr(0, response.find("\r\n")));
  22766. }
  22767. // A sequence ending in chunked stays valid.
  22768. auto req = "POST /test HTTP/1.1\r\n"
  22769. "Host: localhost\r\n"
  22770. "Transfer-Encoding: gzip, chunked\r\n"
  22771. "Connection: close\r\n"
  22772. "\r\n"
  22773. "0\r\n\r\n";
  22774. std::string response;
  22775. ASSERT_TRUE(send_request(1, req, &response));
  22776. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22777. // ...including when it is spread over several lines.
  22778. auto split_req = "POST /test HTTP/1.1\r\n"
  22779. "Host: localhost\r\n"
  22780. "Transfer-Encoding: gzip\r\n"
  22781. "Transfer-Encoding: chunked\r\n"
  22782. "Connection: close\r\n"
  22783. "\r\n"
  22784. "0\r\n\r\n";
  22785. std::string split_response;
  22786. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22787. EXPECT_EQ("HTTP/1.1 200 OK",
  22788. split_response.substr(0, split_response.find("\r\n")));
  22789. }
  22790. // Regression for issue #2450: a DELETE without Content-Length on a
  22791. // keep-alive connection must not let the post-response drain consume the
  22792. // next request's bytes.
  22793. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22794. Server svr;
  22795. std::atomic<int> delete_count(0);
  22796. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22797. delete_count++;
  22798. res.status = StatusCode::NoContent_204;
  22799. });
  22800. auto port = svr.bind_to_any_port(HOST);
  22801. thread t = thread([&] { svr.listen_after_bind(); });
  22802. auto se = detail::scope_exit([&] {
  22803. svr.stop();
  22804. t.join();
  22805. });
  22806. svr.wait_until_ready();
  22807. auto error = Error::Success;
  22808. auto sock = detail::create_client_socket(
  22809. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22810. /*connection_timeout_sec=*/2, 0,
  22811. /*read_timeout_sec=*/2, 0,
  22812. /*write_timeout_sec=*/2, 0, std::string(), error);
  22813. ASSERT_NE(INVALID_SOCKET, sock);
  22814. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22815. auto send_request_and_read_response = [&](const std::string &req,
  22816. std::string &out) -> bool {
  22817. auto sent = send(sock, req.data(), req.size(), 0);
  22818. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22819. char buf[4096];
  22820. for (;;) {
  22821. auto n = recv(sock, buf, sizeof(buf), 0);
  22822. if (n <= 0) { return !out.empty(); }
  22823. out.append(buf, static_cast<size_t>(n));
  22824. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22825. }
  22826. };
  22827. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22828. "Host: localhost\r\n"
  22829. "\r\n";
  22830. std::string resp1;
  22831. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22832. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22833. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22834. "Host: localhost\r\n"
  22835. "Connection: close\r\n"
  22836. "\r\n";
  22837. std::string resp2;
  22838. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22839. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22840. EXPECT_EQ(2, delete_count.load());
  22841. }
  22842. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22843. Server svr;
  22844. svr.Post("/ingest", [&](const Request &, Response &res,
  22845. const ContentReader &content_reader) {
  22846. auto consumed = content_reader([](const char *, size_t) { return false; });
  22847. EXPECT_FALSE(consumed);
  22848. res.status = StatusCode::Conflict_409;
  22849. res.set_header("Connection", "close");
  22850. });
  22851. auto port = svr.bind_to_any_port(HOST);
  22852. thread t = thread([&] { svr.listen_after_bind(); });
  22853. auto se = detail::scope_exit([&] {
  22854. svr.stop();
  22855. t.join();
  22856. });
  22857. svr.wait_until_ready();
  22858. auto error = Error::Success;
  22859. auto sock = detail::create_client_socket(
  22860. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22861. /*connection_timeout_sec=*/2, 0,
  22862. /*read_timeout_sec=*/1, 0,
  22863. /*write_timeout_sec=*/2, 0, std::string(), error);
  22864. ASSERT_NE(INVALID_SOCKET, sock);
  22865. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22866. std::string request = "POST /ingest HTTP/1.1\r\n"
  22867. "Host: localhost\r\n"
  22868. "Transfer-Encoding: chunked\r\n"
  22869. "\r\n"
  22870. "4\r\n"
  22871. "data\r\n";
  22872. auto sent = send(sock, request.data(), request.size(), 0);
  22873. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22874. std::string response;
  22875. ssize_t received = 0;
  22876. do {
  22877. char buf[4096];
  22878. received = recv(sock, buf, sizeof(buf), 0);
  22879. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22880. } while (received > 0);
  22881. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22882. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22883. EXPECT_EQ(0, received);
  22884. }
  22885. namespace no_proxy_test {
  22886. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22887. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22888. // calling listen().
  22889. class ScopedServer {
  22890. public:
  22891. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22892. ~ScopedServer() {
  22893. svr_.stop();
  22894. if (th_.joinable()) { th_.join(); }
  22895. }
  22896. Server &svr() { return svr_; }
  22897. int port() const { return port_; }
  22898. void listen() {
  22899. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22900. svr_.wait_until_ready();
  22901. }
  22902. private:
  22903. Server svr_;
  22904. std::thread th_;
  22905. int port_ = 0;
  22906. };
  22907. class ProxyAndTargetServers {
  22908. public:
  22909. ProxyAndTargetServers() {
  22910. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22911. proxy_hits_++;
  22912. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22913. res.set_content("via-proxy", "text/plain");
  22914. });
  22915. target_.Get(".*", [this](const Request &req, Response &res) {
  22916. target_hits_++;
  22917. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22918. res.set_content("direct", "text/plain");
  22919. });
  22920. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22921. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22922. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22923. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22924. proxy_mock_.wait_until_ready();
  22925. target_.wait_until_ready();
  22926. }
  22927. ~ProxyAndTargetServers() {
  22928. proxy_mock_.stop();
  22929. target_.stop();
  22930. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22931. if (target_thread_.joinable()) { target_thread_.join(); }
  22932. }
  22933. Server &proxy_mock() { return proxy_mock_; }
  22934. Server &target() { return target_; }
  22935. int proxy_port() const { return proxy_port_; }
  22936. int target_port() const { return target_port_; }
  22937. int proxy_hits() const { return proxy_hits_.load(); }
  22938. int target_hits() const { return target_hits_.load(); }
  22939. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22940. void reset_counters() {
  22941. proxy_hits_ = 0;
  22942. target_hits_ = 0;
  22943. last_had_proxy_authz_ = false;
  22944. }
  22945. private:
  22946. Server proxy_mock_;
  22947. Server target_;
  22948. std::thread proxy_thread_;
  22949. std::thread target_thread_;
  22950. int proxy_port_ = 0;
  22951. int target_port_ = 0;
  22952. std::atomic<int> proxy_hits_{0};
  22953. std::atomic<int> target_hits_{0};
  22954. std::atomic<bool> last_had_proxy_authz_{false};
  22955. };
  22956. inline std::unique_ptr<Client> make_client(const std::string &host,
  22957. ProxyAndTargetServers &s) {
  22958. auto cli = detail::make_unique<Client>(host, s.target_port());
  22959. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22960. cli->set_proxy("127.0.0.1", s.proxy_port());
  22961. return cli;
  22962. }
  22963. } // namespace no_proxy_test
  22964. using no_proxy_test::make_client;
  22965. using no_proxy_test::ProxyAndTargetServers;
  22966. TEST(NoProxyTest, ExactHostnameBypasses) {
  22967. ProxyAndTargetServers s;
  22968. auto cli = make_client("example.com", s);
  22969. cli->set_no_proxy({"example.com"});
  22970. auto res = cli->Get("/");
  22971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22972. EXPECT_EQ(0, s.proxy_hits());
  22973. EXPECT_EQ(1, s.target_hits());
  22974. }
  22975. TEST(NoProxyTest, SubdomainBypasses) {
  22976. ProxyAndTargetServers s;
  22977. auto cli = make_client("foo.example.com", s);
  22978. cli->set_no_proxy({"example.com"});
  22979. auto res = cli->Get("/");
  22980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22981. EXPECT_EQ(0, s.proxy_hits());
  22982. EXPECT_EQ(1, s.target_hits());
  22983. }
  22984. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  22985. // Regression guard: "evilexample.com" must not be considered a subdomain
  22986. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22987. // check would let traffic bypass the proxy and leak credentials direct
  22988. // to the attacker host.
  22989. ProxyAndTargetServers s;
  22990. auto cli = make_client("evilexample.com", s);
  22991. cli->set_no_proxy({"example.com"});
  22992. auto res = cli->Get("/");
  22993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22994. EXPECT_GE(s.proxy_hits(), 1);
  22995. EXPECT_EQ(0, s.target_hits());
  22996. }
  22997. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22998. ProxyAndTargetServers s;
  22999. auto cli = make_client("example.com.evil.com", s);
  23000. cli->set_no_proxy({"example.com"});
  23001. auto res = cli->Get("/");
  23002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23003. EXPECT_GE(s.proxy_hits(), 1);
  23004. EXPECT_EQ(0, s.target_hits());
  23005. }
  23006. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23007. ProxyAndTargetServers s;
  23008. auto cli = make_client("example.com", s);
  23009. cli->set_no_proxy({".example.com"});
  23010. auto res = cli->Get("/");
  23011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23012. EXPECT_EQ(0, s.proxy_hits());
  23013. EXPECT_EQ(1, s.target_hits());
  23014. }
  23015. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23016. ProxyAndTargetServers s;
  23017. auto cli = make_client("Example.COM", s);
  23018. cli->set_no_proxy({"EXAMPLE.com"});
  23019. auto res = cli->Get("/");
  23020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23021. EXPECT_EQ(0, s.proxy_hits());
  23022. EXPECT_EQ(1, s.target_hits());
  23023. }
  23024. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23025. ProxyAndTargetServers s;
  23026. auto cli = make_client("example.com.", s);
  23027. cli->set_no_proxy({"example.com"});
  23028. auto res = cli->Get("/");
  23029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23030. EXPECT_EQ(0, s.proxy_hits());
  23031. EXPECT_EQ(1, s.target_hits());
  23032. }
  23033. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23034. // Trailing dots must be normalized on BOTH sides — host and entry.
  23035. // An implementation that only strips the host-side trailing dot would
  23036. // fail to match host "example.com" against entry "example.com." because
  23037. // a literal substring search would compare 11 chars against 12.
  23038. ProxyAndTargetServers s;
  23039. auto cli = make_client("example.com", s);
  23040. cli->set_no_proxy({"example.com."});
  23041. auto res = cli->Get("/");
  23042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23043. EXPECT_EQ(0, s.proxy_hits());
  23044. EXPECT_EQ(1, s.target_hits());
  23045. }
  23046. TEST(NoProxyTest, WildcardBypassesEverything) {
  23047. ProxyAndTargetServers s;
  23048. auto cli = make_client("anything.invalid.test", s);
  23049. cli->set_no_proxy({"*"});
  23050. auto res = cli->Get("/");
  23051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23052. EXPECT_EQ(0, s.proxy_hits());
  23053. EXPECT_EQ(1, s.target_hits());
  23054. }
  23055. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23056. ProxyAndTargetServers s;
  23057. Client cli("127.0.0.1", s.target_port());
  23058. cli.set_proxy("127.0.0.1", s.proxy_port());
  23059. cli.set_no_proxy({"127.0.0.1"});
  23060. auto res = cli.Get("/");
  23061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23062. EXPECT_EQ(0, s.proxy_hits());
  23063. EXPECT_EQ(1, s.target_hits());
  23064. }
  23065. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23066. ProxyAndTargetServers s;
  23067. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23068. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23069. cli.set_proxy("127.0.0.1", s.proxy_port());
  23070. cli.set_no_proxy({"::1"});
  23071. auto res = cli.Get("/");
  23072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23073. EXPECT_EQ(0, s.proxy_hits());
  23074. EXPECT_EQ(1, s.target_hits());
  23075. }
  23076. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23077. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23078. // must still be recognized as IPv6 for CIDR matching. Implementations
  23079. // that detect IPv6 only when the host begins with '[' would parse the
  23080. // host as a hostname and miss the match.
  23081. ProxyAndTargetServers s;
  23082. Client cli("fe80::1", s.target_port());
  23083. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23084. cli.set_proxy("127.0.0.1", s.proxy_port());
  23085. cli.set_no_proxy({"fe80::/10"});
  23086. auto res = cli.Get("/");
  23087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23088. EXPECT_EQ(0, s.proxy_hits());
  23089. EXPECT_EQ(1, s.target_hits());
  23090. }
  23091. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23092. ProxyAndTargetServers s;
  23093. Client cli("::1", s.target_port());
  23094. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23095. cli.set_proxy("127.0.0.1", s.proxy_port());
  23096. cli.set_no_proxy({"[::1]"});
  23097. auto res = cli.Get("/");
  23098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23099. EXPECT_EQ(0, s.proxy_hits());
  23100. EXPECT_EQ(1, s.target_hits());
  23101. }
  23102. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23103. ProxyAndTargetServers s;
  23104. Client cli("fe80::1", s.target_port());
  23105. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23106. cli.set_proxy("127.0.0.1", s.proxy_port());
  23107. cli.set_no_proxy({"[fe80::]/10"});
  23108. auto res = cli.Get("/");
  23109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23110. EXPECT_EQ(0, s.proxy_hits());
  23111. EXPECT_EQ(1, s.target_hits());
  23112. }
  23113. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23114. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23115. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23116. // tricks via address-family conversion.
  23117. ProxyAndTargetServers s;
  23118. Client cli("::ffff:127.0.0.1", s.target_port());
  23119. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23120. cli.set_proxy("127.0.0.1", s.proxy_port());
  23121. cli.set_no_proxy({"127.0.0.1"});
  23122. auto res = cli.Get("/");
  23123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23124. EXPECT_GE(s.proxy_hits(), 1);
  23125. EXPECT_EQ(0, s.target_hits());
  23126. }
  23127. TEST(NoProxyTest, IPv4CidrMatch) {
  23128. ProxyAndTargetServers s;
  23129. Client cli("127.0.0.1", s.target_port());
  23130. cli.set_proxy("127.0.0.1", s.proxy_port());
  23131. cli.set_no_proxy({"127.0.0.0/8"});
  23132. auto res = cli.Get("/");
  23133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23134. EXPECT_EQ(0, s.proxy_hits());
  23135. EXPECT_EQ(1, s.target_hits());
  23136. }
  23137. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23138. ProxyAndTargetServers s;
  23139. Client cli("127.0.0.1", s.target_port());
  23140. cli.set_proxy("127.0.0.1", s.proxy_port());
  23141. cli.set_no_proxy({"10.0.0.0/8"});
  23142. auto res = cli.Get("/");
  23143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23144. EXPECT_GE(s.proxy_hits(), 1);
  23145. EXPECT_EQ(0, s.target_hits());
  23146. }
  23147. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23148. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23149. // IPv4 target matches.
  23150. ProxyAndTargetServers s;
  23151. Client cli("127.0.0.1", s.target_port());
  23152. cli.set_proxy("127.0.0.1", s.proxy_port());
  23153. cli.set_no_proxy({"0.0.0.0/0"});
  23154. auto res = cli.Get("/");
  23155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23156. EXPECT_EQ(0, s.proxy_hits());
  23157. EXPECT_EQ(1, s.target_hits());
  23158. }
  23159. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23160. ProxyAndTargetServers s;
  23161. Client cli("127.0.0.1", s.target_port());
  23162. cli.set_proxy("127.0.0.1", s.proxy_port());
  23163. cli.set_no_proxy({"127.0.0.1"});
  23164. auto res = cli.Get("/");
  23165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23166. EXPECT_EQ(0, s.proxy_hits());
  23167. EXPECT_EQ(1, s.target_hits());
  23168. }
  23169. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23170. ProxyAndTargetServers s;
  23171. Client cli("127.0.0.1", s.target_port());
  23172. cli.set_proxy("127.0.0.1", s.proxy_port());
  23173. cli.set_no_proxy({"127.0.0.0/33"});
  23174. auto res = cli.Get("/");
  23175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23176. EXPECT_GE(s.proxy_hits(), 1);
  23177. EXPECT_EQ(0, s.target_hits());
  23178. }
  23179. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23180. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23181. ProxyAndTargetServers s;
  23182. Client cli("127.0.0.1", s.target_port());
  23183. cli.set_proxy("127.0.0.1", s.proxy_port());
  23184. cli.set_no_proxy({"127.0.0.1/"});
  23185. auto res = cli.Get("/");
  23186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23187. EXPECT_GE(s.proxy_hits(), 1);
  23188. EXPECT_EQ(0, s.target_hits());
  23189. }
  23190. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23191. ProxyAndTargetServers s;
  23192. auto cli = make_client("internal.corp", s);
  23193. cli->set_proxy_basic_auth("u", "p");
  23194. cli->set_no_proxy({"internal.corp"});
  23195. auto res = cli->Get("/");
  23196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23197. EXPECT_EQ(1, s.target_hits());
  23198. EXPECT_EQ(0, s.proxy_hits());
  23199. EXPECT_FALSE(s.last_had_proxy_authz())
  23200. << "Proxy-Authorization must not be sent direct to the target";
  23201. }
  23202. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23203. ProxyAndTargetServers s;
  23204. auto cli = make_client("public.example", s);
  23205. cli->set_proxy_basic_auth("u", "p");
  23206. cli->set_no_proxy({"internal.corp"}); // does not match
  23207. auto res = cli->Get("/");
  23208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23209. EXPECT_GE(s.proxy_hits(), 1);
  23210. EXPECT_TRUE(s.last_had_proxy_authz());
  23211. }
  23212. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23213. std::atomic<int> hits{0};
  23214. std::atomic<int> hits_with_authz{0};
  23215. no_proxy_test::ScopedServer proxy_mock;
  23216. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23217. hits++;
  23218. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23219. if (req.target.find("/redir") != std::string::npos) {
  23220. res.set_redirect("http://other.example/landed");
  23221. } else {
  23222. res.set_content("via-proxy", "text/plain");
  23223. }
  23224. });
  23225. proxy_mock.listen();
  23226. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23227. hits = 0;
  23228. hits_with_authz = 0;
  23229. Client cli("public.example", 80);
  23230. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23231. cli.set_proxy_basic_auth(c.first, c.second);
  23232. cli.set_follow_location(true);
  23233. // The redirect to another host goes through the proxy as well
  23234. auto res = cli.Get("/redir");
  23235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23236. EXPECT_EQ(2, hits.load());
  23237. EXPECT_EQ(2, hits_with_authz.load());
  23238. }
  23239. }
  23240. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23241. ProxyAndTargetServers s;
  23242. auto cli = make_client("anything.test", s);
  23243. auto res = cli->Get("/");
  23244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23245. EXPECT_GE(s.proxy_hits(), 1);
  23246. EXPECT_EQ(0, s.target_hits());
  23247. }
  23248. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23249. ProxyAndTargetServers s;
  23250. auto cli = make_client("example.com", s);
  23251. cli->set_no_proxy({"example.com:8080"});
  23252. auto res = cli->Get("/");
  23253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23254. EXPECT_GE(s.proxy_hits(), 1);
  23255. EXPECT_EQ(0, s.target_hits());
  23256. }
  23257. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23258. ProxyAndTargetServers s;
  23259. auto cli = make_client("anything.test", s);
  23260. cli->set_no_proxy({"", " ", "\t"});
  23261. auto res = cli->Get("/");
  23262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23263. EXPECT_GE(s.proxy_hits(), 1);
  23264. EXPECT_EQ(0, s.target_hits());
  23265. }
  23266. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23267. // An entry with leading/trailing whitespace must still match — env-style
  23268. // values are commonly pasted with stray spaces and an implementation
  23269. // that feeds the raw token directly to inet_pton would fail to match
  23270. // valid CIDRs because of the spaces.
  23271. ProxyAndTargetServers s;
  23272. Client cli("127.0.0.1", s.target_port());
  23273. cli.set_proxy("127.0.0.1", s.proxy_port());
  23274. cli.set_no_proxy({" 127.0.0.0/8 "});
  23275. auto res = cli.Get("/");
  23276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23277. EXPECT_EQ(0, s.proxy_hits());
  23278. EXPECT_EQ(1, s.target_hits());
  23279. }
  23280. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23281. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23282. // go direct and must NOT carry Proxy-Authorization.
  23283. std::atomic<int> proxy_hits{0};
  23284. std::atomic<int> target_hits{0};
  23285. std::atomic<bool> target_saw_authz{false};
  23286. no_proxy_test::ScopedServer proxy_mock, target;
  23287. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23288. proxy_hits++;
  23289. res.status = 302;
  23290. res.set_header("Location", "http://127.0.0.1:" +
  23291. std::to_string(target.port()) + "/landed");
  23292. });
  23293. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23294. target_hits++;
  23295. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23296. res.set_content("direct", "text/plain");
  23297. });
  23298. proxy_mock.listen();
  23299. target.listen();
  23300. Client cli("public.example", target.port());
  23301. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23302. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23303. cli.set_proxy_basic_auth("u", "p");
  23304. cli.set_no_proxy({"127.0.0.1"});
  23305. cli.set_follow_location(true);
  23306. auto res = cli.Get("/redir");
  23307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23308. EXPECT_GE(proxy_hits.load(), 1);
  23309. EXPECT_GE(target_hits.load(), 1);
  23310. EXPECT_FALSE(target_saw_authz.load());
  23311. }
  23312. #ifdef CPPHTTPLIB_SSL_ENABLED
  23313. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23314. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23315. // proxy creds would be sent to the (possibly hostile) origin.
  23316. std::atomic<int> target_hits{0};
  23317. std::atomic<bool> target_saw_proxy_authz{false};
  23318. no_proxy_test::ScopedServer target;
  23319. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23320. target_hits++;
  23321. if (req.has_header("Proxy-Authorization")) {
  23322. target_saw_proxy_authz = true;
  23323. }
  23324. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23325. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23326. "nonce=\"abc\", algorithm=MD5");
  23327. });
  23328. target.listen();
  23329. // The proxy address is set to the target's port: the bypass MUST kick in;
  23330. // if it doesn't, the test still routes "via proxy" to the same server and
  23331. // the Proxy-Authorization assertion below catches the leak.
  23332. Client cli("evil.example", target.port());
  23333. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23334. cli.set_proxy("127.0.0.1", target.port());
  23335. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23336. cli.set_no_proxy({"evil.example"});
  23337. auto res = cli.Get("/x");
  23338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23339. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23340. EXPECT_EQ(1, target_hits.load());
  23341. EXPECT_FALSE(target_saw_proxy_authz.load());
  23342. }
  23343. #endif
  23344. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23345. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23346. std::atomic<int> proxy_hits{0};
  23347. std::atomic<int> bypass_hits{0};
  23348. std::atomic<bool> proxy_saw_c_url{false};
  23349. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23350. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23351. proxy_hits++;
  23352. if (req.path.find("/start") != std::string::npos) {
  23353. res.status = 302;
  23354. res.set_header("Location", "http://127.0.0.1:" +
  23355. std::to_string(bypass_server.port()) +
  23356. "/middle");
  23357. return;
  23358. }
  23359. if (req.path.find("/end") != std::string::npos) {
  23360. proxy_saw_c_url = true;
  23361. res.set_content("c-via-proxy", "text/plain");
  23362. return;
  23363. }
  23364. res.set_content("unexpected", "text/plain");
  23365. });
  23366. // public.example's "advertised" port is arbitrary (the request never lands
  23367. // there — it goes through the proxy), but use a dynamic value to stay
  23368. // friendly with sharded parallel runs.
  23369. int public_port = bypass_server.port();
  23370. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23371. bypass_hits++;
  23372. res.status = 302;
  23373. res.set_header("Location", "http://public.example:" +
  23374. std::to_string(public_port) + "/end");
  23375. });
  23376. proxy_mock.listen();
  23377. bypass_server.listen();
  23378. Client cli("public.example", public_port);
  23379. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23380. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23381. cli.set_no_proxy({"127.0.0.1"});
  23382. cli.set_follow_location(true);
  23383. auto res = cli.Get("/start");
  23384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23385. EXPECT_EQ(StatusCode::OK_200, res->status);
  23386. EXPECT_EQ("c-via-proxy", res->body);
  23387. EXPECT_GE(proxy_hits.load(), 2);
  23388. EXPECT_GE(bypass_hits.load(), 1);
  23389. EXPECT_TRUE(proxy_saw_c_url.load());
  23390. }
  23391. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23392. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23393. // request reconnects to the correct endpoint.
  23394. std::atomic<int> proxy_hits{0};
  23395. std::atomic<int> target_hits{0};
  23396. no_proxy_test::ScopedServer proxy_mock, target;
  23397. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23398. proxy_hits++;
  23399. res.set_content("via-proxy", "text/plain");
  23400. });
  23401. target.svr().Get(".*", [&](const Request &, Response &res) {
  23402. target_hits++;
  23403. res.set_content("direct", "text/plain");
  23404. });
  23405. proxy_mock.listen();
  23406. target.listen();
  23407. Client cli("public.example", target.port());
  23408. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23409. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23410. cli.set_keep_alive(true);
  23411. auto res1 = cli.Get("/a");
  23412. ASSERT_TRUE(res1);
  23413. EXPECT_EQ("via-proxy", res1->body);
  23414. EXPECT_EQ(1, proxy_hits.load());
  23415. EXPECT_EQ(0, target_hits.load());
  23416. cli.set_no_proxy({"public.example"});
  23417. auto res2 = cli.Get("/b");
  23418. ASSERT_TRUE(res2);
  23419. EXPECT_EQ("direct", res2->body);
  23420. EXPECT_EQ(1, proxy_hits.load());
  23421. EXPECT_EQ(1, target_hits.load());
  23422. }
  23423. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23424. namespace proxy_tunnel_test {
  23425. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23426. class ScopedSSLServer {
  23427. public:
  23428. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23429. port_ = svr_.bind_to_any_port("127.0.0.1");
  23430. }
  23431. ~ScopedSSLServer() {
  23432. svr_.stop();
  23433. if (th_.joinable()) { th_.join(); }
  23434. }
  23435. SSLServer &svr() { return svr_; }
  23436. int port() const { return port_; }
  23437. void listen() {
  23438. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23439. svr_.wait_until_ready();
  23440. }
  23441. private:
  23442. SSLServer svr_;
  23443. std::thread th_;
  23444. int port_ = 0;
  23445. };
  23446. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23447. class ScopedConnectProxy {
  23448. public:
  23449. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23450. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23451. if (listen_fd_ < 0) { return; }
  23452. int yes = 1;
  23453. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23454. sockaddr_in a{};
  23455. a.sin_family = AF_INET;
  23456. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23457. a.sin_port = 0;
  23458. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23459. return;
  23460. }
  23461. socklen_t alen = sizeof(a);
  23462. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23463. 0) {
  23464. return;
  23465. }
  23466. port_ = ntohs(a.sin_port);
  23467. if (::listen(listen_fd_, 1) != 0) { return; }
  23468. th_ = std::thread([this] { run(); });
  23469. }
  23470. ~ScopedConnectProxy() {
  23471. stop_ = true;
  23472. if (listen_fd_ >= 0) {
  23473. ::shutdown(listen_fd_, SHUT_RDWR);
  23474. ::close(listen_fd_);
  23475. }
  23476. if (th_.joinable()) { th_.join(); }
  23477. }
  23478. int port() const { return port_; }
  23479. int connect_hits() const { return connect_hits_.load(); }
  23480. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23481. std::string connect_request() const {
  23482. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23483. return connect_request_;
  23484. }
  23485. private:
  23486. void run() {
  23487. while (!stop_.load()) {
  23488. fd_set rfds;
  23489. FD_ZERO(&rfds);
  23490. FD_SET(listen_fd_, &rfds);
  23491. timeval tv{0, 100 * 1000};
  23492. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23493. if (sel <= 0) { continue; }
  23494. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23495. if (client_fd < 0) { continue; }
  23496. std::string req;
  23497. char buf[2048];
  23498. while (req.find("\r\n\r\n") == std::string::npos) {
  23499. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23500. if (n <= 0) { break; }
  23501. req.append(buf, static_cast<size_t>(n));
  23502. }
  23503. if (req.compare(0, 7, "CONNECT") != 0) {
  23504. ::close(client_fd);
  23505. continue;
  23506. }
  23507. connect_hits_++;
  23508. {
  23509. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23510. connect_request_ = req;
  23511. }
  23512. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23513. ::send(client_fd, ok, std::strlen(ok), 0);
  23514. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23515. sockaddr_in o{};
  23516. o.sin_family = AF_INET;
  23517. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23518. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23519. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23520. 0) {
  23521. ::close(client_fd);
  23522. ::close(origin_fd);
  23523. continue;
  23524. }
  23525. auto forward = [](int from, int to) {
  23526. char b[8192];
  23527. for (;;) {
  23528. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23529. if (n <= 0) { break; }
  23530. ssize_t off = 0;
  23531. while (off < n) {
  23532. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23533. if (s <= 0) {
  23534. off = n;
  23535. break;
  23536. }
  23537. off += s;
  23538. }
  23539. }
  23540. ::shutdown(to, SHUT_WR);
  23541. };
  23542. std::thread t1([&] { forward(client_fd, origin_fd); });
  23543. std::thread t2([&] { forward(origin_fd, client_fd); });
  23544. t1.join();
  23545. t2.join();
  23546. ::close(client_fd);
  23547. ::close(origin_fd);
  23548. }
  23549. }
  23550. int forward_port_ = -1;
  23551. int listen_fd_ = -1;
  23552. int port_ = 0;
  23553. std::thread th_;
  23554. std::atomic<bool> stop_{false};
  23555. std::atomic<int> connect_hits_{0};
  23556. mutable std::mutex connect_request_mutex_;
  23557. std::string connect_request_;
  23558. };
  23559. // Sends one request through the CONNECT proxy to the TLS origin with a
  23560. // credential configured for each hop, and checks that each credential reaches
  23561. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23562. // origin's (every header in origin_headers) on the tunnelled request.
  23563. void CredentialsStayWithTheirHop(
  23564. const std::function<void(SSLClient &)> &set_credentials,
  23565. const std::string &scheme,
  23566. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23567. std::atomic<int> origin_hits{0};
  23568. std::atomic<bool> origin_saw_proxy_authz{false};
  23569. std::atomic<bool> origin_saw_headers{false};
  23570. ScopedSSLServer origin;
  23571. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23572. origin_hits++;
  23573. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23574. origin_saw_headers =
  23575. std::all_of(origin_headers.begin(), origin_headers.end(),
  23576. [&](const std::string &h) { return req.has_header(h); });
  23577. res.set_content("ok", "text/plain");
  23578. });
  23579. origin.listen();
  23580. ScopedConnectProxy proxy(origin.port());
  23581. ASSERT_NE(0, proxy.port());
  23582. // Pinned to 127.0.0.1 for the same reason as the test below.
  23583. SSLClient cli("127.0.0.1", origin.port());
  23584. cli.enable_server_certificate_verification(false);
  23585. cli.set_proxy("127.0.0.1", proxy.port());
  23586. set_credentials(cli);
  23587. auto res = cli.Get("/x");
  23588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23589. EXPECT_EQ(StatusCode::OK_200, res->status);
  23590. EXPECT_EQ(1, origin_hits.load());
  23591. EXPECT_EQ(1, proxy.connect_hits());
  23592. EXPECT_TRUE(origin_saw_headers.load());
  23593. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23594. << "Proxy-Authorization must not be sent inside the tunnel";
  23595. auto connect_req = proxy.connect_request();
  23596. EXPECT_NE(std::string::npos,
  23597. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23598. for (const auto &h : origin_headers) {
  23599. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23600. << h << " must not be sent to the proxy on CONNECT";
  23601. }
  23602. }
  23603. } // namespace proxy_tunnel_test
  23604. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23605. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23606. [](SSLClient &cli) {
  23607. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23608. cli.set_basic_auth("origin-user", "origin-pass");
  23609. },
  23610. "Basic");
  23611. }
  23612. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23613. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23614. [](SSLClient &cli) {
  23615. cli.set_proxy_bearer_token_auth("proxy-token");
  23616. cli.set_bearer_token_auth("origin-token");
  23617. },
  23618. "Bearer");
  23619. }
  23620. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23621. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23622. [](SSLClient &cli) {
  23623. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23624. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23625. {"Cookie", "sid=origin-session"},
  23626. {"X-Api-Key", "origin-key"}});
  23627. },
  23628. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23629. }
  23630. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23631. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23632. // retry; otherwise proxy creds would be sent to the origin.
  23633. std::atomic<int> origin_hits{0};
  23634. std::atomic<bool> origin_saw_proxy_authz{false};
  23635. proxy_tunnel_test::ScopedSSLServer origin;
  23636. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23637. origin_hits++;
  23638. if (req.has_header("Proxy-Authorization")) {
  23639. origin_saw_proxy_authz = true;
  23640. }
  23641. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23642. res.set_header("Proxy-Authenticate",
  23643. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23644. "algorithm=MD5");
  23645. });
  23646. origin.listen();
  23647. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23648. ASSERT_NE(0, proxy.port());
  23649. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23650. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23651. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23652. // and answer with its own status, making this test flaky.
  23653. SSLClient cli("127.0.0.1", origin.port());
  23654. cli.enable_server_certificate_verification(false);
  23655. cli.set_proxy("127.0.0.1", proxy.port());
  23656. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23657. auto res = cli.Get("/x");
  23658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23659. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23660. EXPECT_EQ(1, origin_hits.load());
  23661. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23662. EXPECT_EQ(1, proxy.connect_hits());
  23663. }
  23664. #endif