1
0

test.cc 874 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012
  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_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  305. // accept() reports failures through WSAGetLastError() on Windows and through
  306. // errno everywhere else. Asking the wrong one is what made the accept loop
  307. // treat every recoverable failure as fatal on Windows.
  308. struct Classification {
  309. bool resource;
  310. bool transient;
  311. };
  312. auto classify = [](int err) {
  313. #ifdef _WIN32
  314. WSASetLastError(err);
  315. #else
  316. errno = err;
  317. #endif
  318. // Read both before asserting: an assertion may clobber the error slot.
  319. Classification c;
  320. c.resource = detail::is_accept_resource_error();
  321. c.transient = detail::is_accept_transient_error();
  322. return c;
  323. };
  324. #ifdef _WIN32
  325. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  326. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  327. WSAECONNRESET, WSAECONNABORTED};
  328. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  329. #else
  330. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  331. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  332. ECONNABORTED};
  333. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  334. #endif
  335. for (auto err : resource_errors) {
  336. const auto c = classify(err);
  337. EXPECT_TRUE(c.resource) << "error " << err;
  338. EXPECT_FALSE(c.transient) << "error " << err;
  339. }
  340. for (auto err : transient_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.transient) << "error " << err;
  343. EXPECT_FALSE(c.resource) << "error " << err;
  344. }
  345. for (auto err : fatal_errors) {
  346. const auto c = classify(err);
  347. EXPECT_FALSE(c.resource) << "error " << err;
  348. EXPECT_FALSE(c.transient) << "error " << err;
  349. }
  350. #ifdef _WIN32
  351. WSASetLastError(0);
  352. #else
  353. errno = 0;
  354. #endif
  355. }
  356. TEST(ClientTest, MoveConstructible) {
  357. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  358. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  359. }
  360. TEST(ClientTest, MoveAssignable) {
  361. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  362. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  363. }
  364. #ifdef _WIN32
  365. TEST(StartupTest, WSAStartup) {
  366. WSADATA wsaData;
  367. int ret = WSAStartup(0x0002, &wsaData);
  368. ASSERT_EQ(0, ret);
  369. }
  370. #endif
  371. TEST(DecodePathTest, PercentCharacter) {
  372. EXPECT_EQ(
  373. decode_path_component(
  374. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  375. U8("descrip=Gastos áéíóúñÑ 6"));
  376. }
  377. TEST(DecodePathTest, PercentCharacterNUL) {
  378. string expected;
  379. expected.push_back('x');
  380. expected.push_back('\0');
  381. expected.push_back('x');
  382. EXPECT_EQ(decode_path_component("x%00x"), expected);
  383. }
  384. TEST(DecodePathTest, UnicodeEncoding) {
  385. // %u0041 = 'A' (1-byte UTF-8)
  386. EXPECT_EQ("A", decode_path_component("%u0041"));
  387. // %u00E9 = 'é' (2-byte UTF-8)
  388. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  389. // %u3042 = 'あ' (3-byte UTF-8)
  390. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  391. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  392. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  393. // %uD800 = surrogate (invalid, silently dropped)
  394. EXPECT_EQ("", decode_path_component("%uD800"));
  395. }
  396. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  397. // A sign or whitespace inside the two-character escape window must not be
  398. // accepted as a valid percent-encoding; the sequence is passed through
  399. // literally, matching decode_uri_component / decode_path_component.
  400. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  401. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  402. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  403. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  404. // Well-formed escapes still decode.
  405. EXPECT_EQ("-", decode_query_component("%2D", false));
  406. EXPECT_EQ("A", decode_query_component("%41", false));
  407. }
  408. TEST(SanitizeFilenameTest, VariousPatterns) {
  409. // Path traversal
  410. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  412. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  413. // Normal and edge cases
  414. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  415. EXPECT_EQ("filename.txt",
  416. httplib::sanitize_filename("/path/to/filename.txt"));
  417. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  418. EXPECT_EQ("", httplib::sanitize_filename(".."));
  419. EXPECT_EQ("", httplib::sanitize_filename(""));
  420. // Null bytes stripped
  421. EXPECT_EQ("safe.txt",
  422. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  423. // Whitespace-only rejected
  424. EXPECT_EQ("", httplib::sanitize_filename(" "));
  425. }
  426. // Forward declaration (see the base64_encode note below): split builds move the
  427. // definition into httplib.cc, so re-declaring it here lets the test link.
  428. namespace httplib {
  429. namespace detail {
  430. bool is_chunked_transfer_encoding(const Headers &headers);
  431. } // namespace detail
  432. } // namespace httplib
  433. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  434. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  435. auto make = [](std::initializer_list<const char *> lines) {
  436. Headers h;
  437. for (auto te : lines) {
  438. if (te) { h.emplace("Transfer-Encoding", te); }
  439. }
  440. return h;
  441. };
  442. // Sole coding, matched case-insensitively.
  443. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  446. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  450. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  451. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  455. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  456. // were received, into one list. Headers preserves that order, so the answer
  457. // is decided by the last coding of the last line and the order the lines
  458. // arrived in is significant.
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  462. // The split can fall anywhere in the list.
  463. EXPECT_TRUE(
  464. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  465. EXPECT_FALSE(
  466. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  467. // A trailing line naming no coding leaves the list ending in nothing, so it
  468. // must not inherit the chunked from the line before it.
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  470. }
  471. // Forward declaration: in split builds split.py strips `inline` and moves the
  472. // definition into httplib.cc, so detail::base64_encode is not visible from the
  473. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  474. // in both header-only and split builds.
  475. namespace httplib {
  476. namespace detail {
  477. std::string base64_encode(const std::string &in);
  478. } // namespace detail
  479. } // namespace httplib
  480. TEST(Base64EncodeTest, KnownAnswers) {
  481. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  482. // where the accumulator's top bit is already set before the next shift.
  483. EXPECT_EQ("", detail::base64_encode(""));
  484. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  485. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  486. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  487. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  488. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  489. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  490. // High bytes keep the top bit set across several rounds.
  491. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  492. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  493. }
  494. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  495. string unescapedCharacters = "-_.!~*'()";
  496. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  497. }
  498. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  499. string reservedCharacters = ";,/?:@&=+$";
  500. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  501. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  502. }
  503. TEST(ClientQueryOrder, PreserveOrder) {
  504. // This test reproduces Issue #2259: client may reorder query parameters
  505. // when sending a GET request. The expected behavior is that the client
  506. // preserves the original query string order when the caller supplied it
  507. // as part of the path.
  508. Server svr;
  509. svr.Get("/", [&](const Request &req, Response &res) {
  510. // Echo back the raw target so the test can assert ordering
  511. res.set_content(req.target, "text/plain");
  512. });
  513. std::thread t{[&] { svr.listen(HOST, PORT); }};
  514. auto se = detail::scope_exit([&] {
  515. svr.stop();
  516. t.join();
  517. ASSERT_FALSE(svr.is_running());
  518. });
  519. svr.wait_until_ready();
  520. Client cli(HOST, PORT);
  521. ASSERT_TRUE(cli.is_valid());
  522. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  523. auto res = cli.Get(original);
  524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  525. // Expect the echoed target to exactly match the original path (order
  526. // preserved)
  527. EXPECT_EQ(res->body, original);
  528. }
  529. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  530. string chineseCharacters = U8("中国語");
  531. string russianCharacters = U8("дом");
  532. string brazilianCharacters = U8("óculos");
  533. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  534. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  535. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  536. "%D0%B4%D0%BE%D0%BC");
  537. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  538. }
  539. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  540. string unescapedCharacters = "-_.!~*'()";
  541. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  542. }
  543. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  544. string reservedCharacters = ";,/?:@&=+$";
  545. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  546. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  547. }
  548. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  549. string chineseCharacters = U8("中国語");
  550. string russianCharacters = U8("дом");
  551. string brazilianCharacters = U8("óculos");
  552. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  553. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  554. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  555. "%D0%B4%D0%BE%D0%BC");
  556. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  557. }
  558. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  559. // Issue #2082 use case: encoding path component with ampersand
  560. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  561. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  562. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  563. }
  564. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  565. string unescapedCharacters = "-_.!~*'()";
  566. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  567. }
  568. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  569. string reservedCharacters = ";,/?:@&=+$#";
  570. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  571. }
  572. TEST(EncodeUriTest, TestUTF8Characters) {
  573. string chineseCharacters = U8("中国語");
  574. string russianCharacters = U8("дом");
  575. string brazilianCharacters = U8("óculos");
  576. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  577. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  578. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  579. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  580. }
  581. TEST(EncodeUriTest, TestCompleteUri) {
  582. string uri =
  583. "https://example.com/path/to/resource?query=value&param=test#fragment";
  584. EXPECT_EQ(
  585. httplib::encode_uri(uri),
  586. "https://example.com/path/to/resource?query=value&param=test#fragment");
  587. }
  588. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  589. string uri =
  590. "https://example.com/path with spaces/file name.html?q=hello world";
  591. EXPECT_EQ(httplib::encode_uri(uri),
  592. "https://example.com/path%20with%20spaces/"
  593. "file%20name.html?q=hello%20world");
  594. }
  595. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  596. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  597. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  598. }
  599. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  600. string unescapedCharacters = "-_.!~*'()";
  601. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  602. }
  603. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  604. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  605. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  606. string encodedBrazilian = "%C3%B3culos";
  607. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  608. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  610. }
  611. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  612. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  613. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  614. "Piri Tommy Villiers - on & on");
  615. }
  616. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  617. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  618. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  619. }
  620. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  621. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  622. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  623. }
  624. TEST(DecodeUriTest, TestUTF8Characters) {
  625. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  626. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  627. string encodedBrazilian = "%C3%B3culos";
  628. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  629. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  630. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  631. }
  632. TEST(DecodeUriTest, TestCompleteUri) {
  633. string encodedUri = "https://example.com/path%20with%20spaces/"
  634. "file%20name.html?q=hello%20world";
  635. EXPECT_EQ(
  636. httplib::decode_uri(encodedUri),
  637. "https://example.com/path with spaces/file name.html?q=hello world");
  638. }
  639. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  640. string original =
  641. "https://example.com/path with spaces/file name.html?q=hello world";
  642. string encoded = httplib::encode_uri(original);
  643. string decoded = httplib::decode_uri(encoded);
  644. EXPECT_EQ(decoded, original);
  645. }
  646. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  647. // decode_uri is the inverse of encode_uri: an escaped reserved character
  648. // stays encoded so it is not promoted into a real delimiter, while
  649. // non-reserved escapes still decode (like JS decodeURI).
  650. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  651. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  652. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  653. "%3F%3A%40%26%3D%2B%24%2C%3B");
  654. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  655. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  656. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  657. "http://example.com/a%2Fb");
  658. // decode_uri_component still decodes the reserved character.
  659. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  660. }
  661. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  662. string original = "Piri Tommy Villiers - on & on";
  663. string encoded = httplib::encode_uri_component(original);
  664. string decoded = httplib::decode_uri_component(encoded);
  665. EXPECT_EQ(decoded, original);
  666. }
  667. TEST(TrimTests, TrimStringTests) {
  668. EXPECT_EQ("abc", detail::trim_copy("abc"));
  669. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  670. EXPECT_TRUE(detail::trim_copy("").empty());
  671. }
  672. TEST(AsciiTest, LocaleIndependentClassification) {
  673. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  674. // which consult the global C locale: std::isalnum(0xC5) can return true
  675. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  676. // helpers must classify every byte by the ASCII grammar alone.
  677. for (int i = 0; i < 256; i++) {
  678. auto c = static_cast<char>(i);
  679. auto is_digit = i >= '0' && i <= '9';
  680. auto is_upper = i >= 'A' && i <= 'Z';
  681. auto is_lower = i >= 'a' && i <= 'z';
  682. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  683. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  684. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  685. << "byte " << i;
  686. }
  687. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  688. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  689. // Non-ASCII bytes must be percent-encoded, never passed through as
  690. // alphanumeric.
  691. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  692. }
  693. TEST(FromCharsTest, Double) {
  694. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  695. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  696. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  697. auto parse = [](const std::string &s, double &v) {
  698. return detail::from_chars(s.data(), s.data() + s.size(), v);
  699. };
  700. double v = -1.0;
  701. // Representative quality values.
  702. EXPECT_EQ(parse("0", v).ec, std::errc{});
  703. EXPECT_DOUBLE_EQ(v, 0.0);
  704. EXPECT_EQ(parse("1", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 1.0);
  706. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 0.8);
  708. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.001);
  710. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 1.0);
  712. // A missing integer or fractional part is tolerated.
  713. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 0.5);
  715. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 5.0);
  717. // Values outside [0, 1] still parse; the caller range-checks them.
  718. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 123.456);
  720. // Stops at the first byte that is not part of the number and reports where.
  721. std::string trailing = "0.9, text/html";
  722. auto r = parse(trailing, v);
  723. EXPECT_EQ(r.ec, std::errc{});
  724. EXPECT_DOUBLE_EQ(v, 0.9);
  725. EXPECT_EQ(*r.ptr, ',');
  726. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  727. // outright, and an 'e'/'E' simply ends the number.
  728. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  729. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  730. std::string exp_input = "1.5e3";
  731. r = parse(exp_input, v);
  732. EXPECT_EQ(r.ec, std::errc{});
  733. EXPECT_DOUBLE_EQ(v, 1.5);
  734. EXPECT_EQ(*r.ptr, 'e');
  735. // Invalid inputs.
  736. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  737. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  741. // Pathological but well-formed inputs must stay bounded (no overflow, no
  742. // out-of-bounds table access) and stay within [0, 1] for the caller.
  743. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  744. std::errc{});
  745. EXPECT_DOUBLE_EQ(v, 0.0);
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  747. std::errc{});
  748. EXPECT_GE(v, 0.0);
  749. EXPECT_LE(v, 1.0);
  750. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  751. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  752. }
  753. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  754. // Simple case without quality values
  755. std::vector<std::string> result1;
  756. EXPECT_TRUE(detail::parse_accept_header(
  757. "text/html,application/json,text/plain", result1));
  758. EXPECT_EQ(result1.size(), 3U);
  759. EXPECT_EQ(result1[0], "text/html");
  760. EXPECT_EQ(result1[1], "application/json");
  761. EXPECT_EQ(result1[2], "text/plain");
  762. // With quality values
  763. std::vector<std::string> result2;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  766. EXPECT_EQ(result2.size(), 3U);
  767. EXPECT_EQ(result2[0], "application/json"); // highest q value
  768. EXPECT_EQ(result2[1], "text/html");
  769. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  770. }
  771. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  772. // Mixed with and without quality values
  773. std::vector<std::string> result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  776. EXPECT_EQ(result.size(), 3U);
  777. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  778. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  779. EXPECT_EQ(result[2], "application/json"); // q=0.5
  780. }
  781. TEST(ParseAcceptHeaderTest, EdgeCases) {
  782. // Empty header
  783. std::vector<std::string> empty_result;
  784. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  785. EXPECT_TRUE(empty_result.empty());
  786. // Single type
  787. std::vector<std::string> single_result;
  788. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  789. EXPECT_EQ(single_result.size(), 1U);
  790. EXPECT_EQ(single_result[0], "application/json");
  791. // Wildcard types
  792. std::vector<std::string> wildcard_result;
  793. EXPECT_TRUE(detail::parse_accept_header(
  794. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  795. EXPECT_EQ(wildcard_result.size(), 3U);
  796. EXPECT_EQ(wildcard_result[0], "application/json");
  797. EXPECT_EQ(wildcard_result[1], "text/*");
  798. EXPECT_EQ(wildcard_result[2], "*/*");
  799. }
  800. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  801. // Common browser Accept header
  802. std::vector<std::string> browser_result;
  803. EXPECT_TRUE(
  804. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  805. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  806. browser_result));
  807. EXPECT_EQ(browser_result.size(), 6U);
  808. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  809. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  813. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  814. // API client header
  815. std::vector<std::string> api_result;
  816. EXPECT_TRUE(detail::parse_accept_header(
  817. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  818. api_result));
  819. EXPECT_EQ(api_result.size(), 3U);
  820. EXPECT_EQ(api_result[0], "application/json");
  821. EXPECT_EQ(api_result[1], "application/xml");
  822. EXPECT_EQ(api_result[2], "text/plain");
  823. }
  824. TEST(ParseAcceptHeaderTest, SpecialCases) {
  825. // Quality value with 3 decimal places
  826. std::vector<std::string> decimal_result;
  827. EXPECT_TRUE(detail::parse_accept_header(
  828. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  829. EXPECT_EQ(decimal_result.size(), 2U);
  830. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  831. EXPECT_EQ(decimal_result[1], "text/html");
  832. // Zero quality (should still be included but with lowest priority)
  833. std::vector<std::string> zero_q_result;
  834. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  835. zero_q_result));
  836. EXPECT_EQ(zero_q_result.size(), 2U);
  837. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  838. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  839. // No spaces around commas
  840. std::vector<std::string> no_space_result;
  841. EXPECT_TRUE(detail::parse_accept_header(
  842. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  843. no_space_result));
  844. EXPECT_EQ(no_space_result.size(), 3U);
  845. EXPECT_EQ(no_space_result[0], "text/html");
  846. EXPECT_EQ(no_space_result[1], "application/json");
  847. EXPECT_EQ(no_space_result[2], "text/plain");
  848. }
  849. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  850. // Quality values always use '.' as the decimal separator, so parsing must
  851. // not depend on the process locale. An embedding application may have
  852. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  853. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  854. std::string saved = cur ? cur : "C";
  855. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  856. "fr_FR.UTF-8"};
  857. bool switched = false;
  858. for (const auto loc : comma_locales) {
  859. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  860. std::localeconv()->decimal_point[0] == ',') {
  861. switched = true;
  862. break;
  863. }
  864. }
  865. if (!switched) {
  866. std::setlocale(LC_NUMERIC, saved.c_str());
  867. GTEST_SKIP() << "no comma-decimal locale available on this host";
  868. }
  869. // The higher-weighted type appears later in the list, so a correct parse
  870. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  871. // sensitive parse reads both weights as 0 and leaves the original order.
  872. std::vector<std::string> result;
  873. EXPECT_TRUE(detail::parse_accept_header(
  874. "application/json;q=0.1,text/html;q=0.9", result));
  875. ASSERT_EQ(result.size(), 2U);
  876. EXPECT_EQ(result[0], "text/html");
  877. EXPECT_EQ(result[1], "application/json");
  878. std::setlocale(LC_NUMERIC, saved.c_str());
  879. }
  880. TEST(ParseAcceptHeaderTest, InvalidCases) {
  881. std::vector<std::string> result;
  882. // Invalid quality value (> 1.0)
  883. EXPECT_FALSE(
  884. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  885. // Invalid quality value (< 0.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  888. // Invalid quality value (not a number)
  889. EXPECT_FALSE(detail::parse_accept_header(
  890. "text/html;q=invalid,application/json", result));
  891. // A valid numeric prefix does not make the entire quality value valid.
  892. EXPECT_FALSE(detail::parse_accept_header(
  893. "text/html;q=0.5junk,application/json", result));
  894. // Empty quality value
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("text/html;q=,application/json", result));
  897. // Invalid media type format (no slash and not wildcard)
  898. EXPECT_FALSE(
  899. detail::parse_accept_header("invalidtype,application/json", result));
  900. // Valid cases should still work
  901. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  902. EXPECT_EQ(result.size(), 1U);
  903. EXPECT_EQ(result[0], "*/*");
  904. EXPECT_TRUE(detail::parse_accept_header("*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "*");
  907. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  908. EXPECT_EQ(result.size(), 1U);
  909. EXPECT_EQ(result[0], "text/*");
  910. }
  911. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  912. // elements, so a leading, trailing or doubled comma is a legal Accept value
  913. // and must not be answered with 400 Bad Request.
  914. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  915. struct {
  916. const char *value;
  917. std::vector<std::string> expected;
  918. } cases[] = {
  919. {",application/json", {"application/json"}},
  920. {"text/html,", {"text/html"}},
  921. {"text/html,,*/*", {"text/html", "*/*"}},
  922. // An empty element may be spelled with whitespace in it
  923. {"text/html, , application/json", {"text/html", "application/json"}},
  924. // Nothing but empty elements is an empty list, which means the same
  925. // thing as no Accept header at all
  926. {",,,", {}},
  927. // Quality values still apply across ignored empty elements
  928. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  929. };
  930. for (const auto &c : cases) {
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  933. << "value: " << c.value;
  934. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  935. }
  936. // An invalid entry is still rejected when empty elements surround it
  937. std::vector<std::string> result;
  938. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  939. }
  940. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  941. Server svr;
  942. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  943. EXPECT_EQ(req.accept_content_types.size(), 3U);
  944. EXPECT_EQ(req.accept_content_types[0], "application/json");
  945. EXPECT_EQ(req.accept_content_types[1], "text/html");
  946. EXPECT_EQ(req.accept_content_types[2], "*/*");
  947. res.set_content("ok", "text/plain");
  948. });
  949. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  950. EXPECT_TRUE(false);
  951. res.set_content("bad request", "text/plain");
  952. });
  953. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  954. auto se = detail::scope_exit([&] {
  955. svr.stop();
  956. listen_thread.join();
  957. ASSERT_FALSE(svr.is_running());
  958. });
  959. svr.wait_until_ready();
  960. Client cli("localhost", PORT);
  961. {
  962. auto res = cli.Get(
  963. "/accept_ok",
  964. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  966. EXPECT_EQ(StatusCode::OK_200, res->status);
  967. }
  968. {
  969. auto res = cli.Get("/accept_bad_request",
  970. Headers{{"Accept", "text/html;q=abc,application/json"}});
  971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  972. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  973. }
  974. }
  975. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  976. Server svr;
  977. svr.Get("/", [](const Request & /*req*/, Response &res) {
  978. res.set_content("ok", "text/plain");
  979. });
  980. std::atomic<int> start_count{0};
  981. std::atomic<bool> running_when_called{false};
  982. svr.set_start_handler([&]() {
  983. running_when_called = svr.is_running();
  984. start_count++;
  985. });
  986. auto port = svr.bind_to_any_port(HOST);
  987. std::thread t([&]() { svr.listen_after_bind(); });
  988. auto se = detail::scope_exit([&] {
  989. svr.stop();
  990. t.join();
  991. ASSERT_FALSE(svr.is_running());
  992. });
  993. svr.wait_until_ready();
  994. // A successful request proves the accept loop is running, which the start
  995. // handler precedes; so by now the handler must have run exactly once.
  996. Client cli(HOST, port);
  997. cli.set_connection_timeout(std::chrono::seconds(5));
  998. auto res = cli.Get("/");
  999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1000. EXPECT_EQ(StatusCode::OK_200, res->status);
  1001. EXPECT_EQ(1, start_count.load());
  1002. EXPECT_TRUE(running_when_called.load());
  1003. }
  1004. TEST(DivideTest, DivideStringTests) {
  1005. auto divide = [](const std::string &str, char d) {
  1006. std::string lhs;
  1007. std::string rhs;
  1008. detail::divide(str, d,
  1009. [&](const char *lhs_data, std::size_t lhs_size,
  1010. const char *rhs_data, std::size_t rhs_size) {
  1011. lhs.assign(lhs_data, lhs_size);
  1012. rhs.assign(rhs_data, rhs_size);
  1013. });
  1014. return std::make_pair(std::move(lhs), std::move(rhs));
  1015. };
  1016. {
  1017. const auto res = divide("", '=');
  1018. EXPECT_EQ(res.first, "");
  1019. EXPECT_EQ(res.second, "");
  1020. }
  1021. {
  1022. const auto res = divide("=", '=');
  1023. EXPECT_EQ(res.first, "");
  1024. EXPECT_EQ(res.second, "");
  1025. }
  1026. {
  1027. const auto res = divide(" ", '=');
  1028. EXPECT_EQ(res.first, " ");
  1029. EXPECT_EQ(res.second, "");
  1030. }
  1031. {
  1032. const auto res = divide("a", '=');
  1033. EXPECT_EQ(res.first, "a");
  1034. EXPECT_EQ(res.second, "");
  1035. }
  1036. {
  1037. const auto res = divide("a=", '=');
  1038. EXPECT_EQ(res.first, "a");
  1039. EXPECT_EQ(res.second, "");
  1040. }
  1041. {
  1042. const auto res = divide("=b", '=');
  1043. EXPECT_EQ(res.first, "");
  1044. EXPECT_EQ(res.second, "b");
  1045. }
  1046. {
  1047. const auto res = divide("a=b", '=');
  1048. EXPECT_EQ(res.first, "a");
  1049. EXPECT_EQ(res.second, "b");
  1050. }
  1051. {
  1052. const auto res = divide("a=b=", '=');
  1053. EXPECT_EQ(res.first, "a");
  1054. EXPECT_EQ(res.second, "b=");
  1055. }
  1056. {
  1057. const auto res = divide("a=b=c", '=');
  1058. EXPECT_EQ(res.first, "a");
  1059. EXPECT_EQ(res.second, "b=c");
  1060. }
  1061. }
  1062. TEST(SplitTest, ParseQueryString) {
  1063. string s = "key1=val1&key2=val2&key3=val3";
  1064. Params dic;
  1065. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1066. [&](const char *b, const char *e) {
  1067. string key, val;
  1068. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1069. if (key.empty()) {
  1070. key.assign(b2, e2);
  1071. } else {
  1072. val.assign(b2, e2);
  1073. }
  1074. });
  1075. dic.emplace(key, val);
  1076. });
  1077. EXPECT_EQ("val1", dic.find("key1")->second);
  1078. EXPECT_EQ("val2", dic.find("key2")->second);
  1079. EXPECT_EQ("val3", dic.find("key3")->second);
  1080. }
  1081. TEST(SplitTest, ParseInvalidQueryTests) {
  1082. {
  1083. string s = " ";
  1084. Params dict;
  1085. detail::parse_query_text(s, dict);
  1086. EXPECT_TRUE(dict.empty());
  1087. }
  1088. {
  1089. string s = " = =";
  1090. Params dict;
  1091. detail::parse_query_text(s, dict);
  1092. EXPECT_TRUE(dict.empty());
  1093. }
  1094. }
  1095. TEST(ParseQueryTest, ParseQueryString) {
  1096. {
  1097. std::string s = "key1=val1&key2=val2&key3=val3";
  1098. Params dic;
  1099. detail::parse_query_text(s, dic);
  1100. EXPECT_EQ("val1", dic.find("key1")->second);
  1101. EXPECT_EQ("val2", dic.find("key2")->second);
  1102. EXPECT_EQ("val3", dic.find("key3")->second);
  1103. }
  1104. {
  1105. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1106. Params dic;
  1107. detail::parse_query_text(s, dic);
  1108. EXPECT_EQ("", dic.find("key1")->second);
  1109. EXPECT_EQ("val1", dic.find("key2")->second);
  1110. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1111. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1112. }
  1113. }
  1114. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1115. Params dic;
  1116. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1117. dic.emplace("key1", "val1");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1119. dic.emplace("key2", "val2");
  1120. dic.emplace("key3", "val3");
  1121. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1122. }
  1123. // Joins every entry of a Headers or Params into "key=value " so a whole
  1124. // traversal can be compared in one assertion. Both are instantiations of the
  1125. // same insertion-ordered container, so one helper serves both.
  1126. template <typename Map> static std::string entries_to_string(const Map &m) {
  1127. std::string s;
  1128. for (const auto &entry : m) {
  1129. s += entry.first + "=" + entry.second + " ";
  1130. }
  1131. return s;
  1132. }
  1133. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1134. // Params used to be a std::multimap, which sorted by name and handed the
  1135. // caller's query back alphabetised. A client signing its query string could
  1136. // not reproduce the order it asked for.
  1137. Params dic;
  1138. dic.emplace("zulu", "1");
  1139. dic.emplace("alpha", "2");
  1140. dic.emplace("mike", "3");
  1141. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1142. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1143. }
  1144. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1145. Params dic;
  1146. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1147. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1148. }
  1149. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1150. Request req;
  1151. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1152. req.params);
  1153. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1154. EXPECT_EQ("first", req.get_param_value("tag"));
  1155. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1156. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1157. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1158. EXPECT_EQ("", req.get_param_value("tag", 3));
  1159. }
  1160. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1161. // Params shares its container with Headers, which matches field names
  1162. // case-insensitively. Parameter names must not pick that up.
  1163. Params dic;
  1164. dic.emplace("Key", "upper");
  1165. dic.emplace("key", "lower");
  1166. EXPECT_EQ(2U, dic.size());
  1167. EXPECT_EQ(1U, dic.count("Key"));
  1168. EXPECT_EQ(1U, dic.count("key"));
  1169. EXPECT_EQ("upper", dic.find("Key")->second);
  1170. EXPECT_EQ("lower", dic.find("key")->second);
  1171. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1172. }
  1173. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1174. Server svr;
  1175. std::string order;
  1176. svr.Get("/order", [&](const Request &req, Response &res) {
  1177. order = entries_to_string(req.params);
  1178. res.set_content("ok", "text/plain");
  1179. });
  1180. auto port = svr.bind_to_any_port(HOST);
  1181. thread t = thread([&] { svr.listen_after_bind(); });
  1182. auto se = detail::scope_exit([&] {
  1183. svr.stop();
  1184. t.join();
  1185. ASSERT_FALSE(svr.is_running());
  1186. });
  1187. svr.wait_until_ready();
  1188. Client cli(HOST, port);
  1189. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1190. ASSERT_TRUE(res);
  1191. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1192. }
  1193. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1194. Server svr;
  1195. std::string field_order, file_order;
  1196. svr.Post("/order", [&](const Request &req, Response &res) {
  1197. for (const auto &field : req.form.fields) {
  1198. field_order += field.first + "=" + field.second.content + " ";
  1199. }
  1200. for (const auto &file : req.form.files) {
  1201. file_order += file.first + "=" + file.second.filename + " ";
  1202. }
  1203. res.set_content("ok", "text/plain");
  1204. });
  1205. auto port = svr.bind_to_any_port(HOST);
  1206. thread t = thread([&] { svr.listen_after_bind(); });
  1207. auto se = detail::scope_exit([&] {
  1208. svr.stop();
  1209. t.join();
  1210. ASSERT_FALSE(svr.is_running());
  1211. });
  1212. svr.wait_until_ready();
  1213. UploadFormDataItems items = {
  1214. {"zulu", "1", "", ""},
  1215. {"alpha", "2", "", ""},
  1216. {"mike", "3", "", ""},
  1217. {"zebra", "z", "z.txt", "text/plain"},
  1218. {"apple", "a", "a.txt", "text/plain"},
  1219. };
  1220. Client cli(HOST, port);
  1221. auto res = cli.Post("/order", items);
  1222. ASSERT_TRUE(res);
  1223. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1224. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1225. }
  1226. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1227. Server svr;
  1228. std::vector<std::string> values;
  1229. std::string first, second, out_of_range, order;
  1230. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1231. values = req.form.get_fields("tag");
  1232. first = req.form.get_field("tag", 0);
  1233. second = req.form.get_field("tag", 1);
  1234. out_of_range = req.form.get_field("tag", 2);
  1235. for (const auto &field : req.form.fields) {
  1236. order += field.first + "=" + field.second.content + " ";
  1237. }
  1238. res.set_content("ok", "text/plain");
  1239. });
  1240. auto port = svr.bind_to_any_port(HOST);
  1241. thread t = thread([&] { svr.listen_after_bind(); });
  1242. auto se = detail::scope_exit([&] {
  1243. svr.stop();
  1244. t.join();
  1245. ASSERT_FALSE(svr.is_running());
  1246. });
  1247. svr.wait_until_ready();
  1248. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1249. // not adjacent in the container.
  1250. UploadFormDataItems items = {
  1251. {"tag", "first", "", ""},
  1252. {"other", "x", "", ""},
  1253. {"tag", "second", "", ""},
  1254. };
  1255. Client cli(HOST, port);
  1256. auto res = cli.Post("/repeated", items);
  1257. ASSERT_TRUE(res);
  1258. ASSERT_EQ(2U, values.size());
  1259. EXPECT_EQ("first", values[0]);
  1260. EXPECT_EQ("second", values[1]);
  1261. EXPECT_EQ("first", first);
  1262. EXPECT_EQ("second", second);
  1263. // std::multimap already kept entries sharing a name in insertion order, so
  1264. // everything above passes without this change too. The whole traversal is
  1265. // what tells the two apart: sorting by name would hoist "other" to the front
  1266. // and the two "tag" parts would end up adjacent.
  1267. EXPECT_EQ("tag=first other=x tag=second ", order);
  1268. // Advancing past the last entry of a name used to run off the container;
  1269. // the container's saturating increment makes it return the default instead.
  1270. EXPECT_EQ("", out_of_range);
  1271. }
  1272. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1273. // Server::read_content() keeps a FormFields::iterator alive across the
  1274. // content callbacks that fill the part it points at. The container is
  1275. // vector-backed, so a later emplace can reallocate and invalidate an older
  1276. // iterator; 64 parts grow the vector through seven reallocations, which
  1277. // checks that every part's content still lands in its own entry.
  1278. const size_t part_count = 64;
  1279. // One formula for both the parts sent and the values expected back, so the
  1280. // two cannot drift apart.
  1281. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1282. auto content_of = [](size_t i) {
  1283. return std::string(64, static_cast<char>('a' + (i % 26)));
  1284. };
  1285. Server svr;
  1286. std::vector<std::pair<std::string, std::string>> received;
  1287. svr.Post("/many", [&](const Request &req, Response &res) {
  1288. for (const auto &field : req.form.fields) {
  1289. received.emplace_back(field.first, field.second.content);
  1290. }
  1291. res.set_content("ok", "text/plain");
  1292. });
  1293. auto port = svr.bind_to_any_port(HOST);
  1294. thread t = thread([&] { svr.listen_after_bind(); });
  1295. auto se = detail::scope_exit([&] {
  1296. svr.stop();
  1297. t.join();
  1298. ASSERT_FALSE(svr.is_running());
  1299. });
  1300. svr.wait_until_ready();
  1301. UploadFormDataItems items;
  1302. for (size_t i = 0; i < part_count; i++) {
  1303. items.push_back({name_of(i), content_of(i), "", ""});
  1304. }
  1305. Client cli(HOST, port);
  1306. auto res = cli.Post("/many", items);
  1307. ASSERT_TRUE(res);
  1308. ASSERT_EQ(part_count, received.size());
  1309. for (size_t i = 0; i < part_count; i++) {
  1310. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1311. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1312. }
  1313. }
  1314. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1315. string content_type = "multipart/form-data; boundary=something";
  1316. string boundary;
  1317. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1318. EXPECT_TRUE(ret);
  1319. EXPECT_EQ(boundary, "something");
  1320. }
  1321. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1322. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1323. string boundary;
  1324. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1325. EXPECT_TRUE(ret);
  1326. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1327. }
  1328. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1329. string content_type =
  1330. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1331. string boundary;
  1332. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1333. EXPECT_TRUE(ret);
  1334. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1335. }
  1336. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1337. string content_type =
  1338. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1339. string boundary;
  1340. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1341. EXPECT_TRUE(ret);
  1342. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1343. }
  1344. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1345. const string boundary(70, 'a');
  1346. string content_type = "multipart/form-data; boundary=" + boundary;
  1347. string parsed;
  1348. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1349. EXPECT_TRUE(ret);
  1350. EXPECT_EQ(parsed, boundary);
  1351. }
  1352. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1353. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1354. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1355. string parsed;
  1356. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1357. EXPECT_FALSE(ret);
  1358. }
  1359. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1360. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1361. // is 72 characters on the wire and still valid.
  1362. const string boundary(70, 'a');
  1363. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1364. string parsed;
  1365. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1366. EXPECT_EQ(parsed, boundary);
  1367. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1368. parsed.clear();
  1369. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1370. }
  1371. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1372. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1373. // The parameter parser must not treat that '=' as the key/value separator.
  1374. string content_type =
  1375. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1376. "charset=UTF-8";
  1377. string parsed;
  1378. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1379. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1380. }
  1381. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1382. // A ';' inside the quoted-string is part of the value, not a parameter
  1383. // separator, so it must not truncate the boundary.
  1384. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1385. string parsed;
  1386. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1387. EXPECT_EQ(parsed, "a;b");
  1388. }
  1389. TEST(ParseDispositionParamsTest, QuotedValues) {
  1390. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1391. // ';' and '=' are ordinary characters inside one.
  1392. struct {
  1393. const char *value;
  1394. std::vector<std::pair<const char *, const char *>> expected;
  1395. } cases[] = {
  1396. {"name=\"file1\"; filename=\"a.txt\"",
  1397. {{"name", "file1"}, {"filename", "a.txt"}}},
  1398. // Whitespace around '=' and ';' is still trimmed
  1399. {"name=\"file2\" ;filename = \"a.html\"",
  1400. {{"name", "file2"}, {"filename", "a.html"}}},
  1401. // '=' inside the value used to leave only the text after the last one
  1402. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1403. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1404. {"name=\"x=y\"", {{"name", "x=y"}}},
  1405. // ';' inside the value used to truncate the pair and leave a bogus one
  1406. {"name=\"file3\"; filename=\"a;b.txt\"",
  1407. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1408. // An unquoted value keeps working, and so does filename*
  1409. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1410. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1411. // A parameter with no key is dropped rather than turned into one whose
  1412. // key is the value
  1413. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1414. };
  1415. for (const auto &c : cases) {
  1416. Params params;
  1417. detail::parse_disposition_params(c.value, params);
  1418. for (const auto &kv : c.expected) {
  1419. auto it = params.find(kv.first);
  1420. ASSERT_NE(it, params.end())
  1421. << "value: " << c.value << ", key: " << kv.first;
  1422. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1423. }
  1424. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1425. }
  1426. }
  1427. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1428. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1429. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1430. Server svr;
  1431. std::string field_value, file_name, file_filename;
  1432. bool has_field = false, has_file = false;
  1433. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1434. has_field = req.form.has_field("x=y");
  1435. field_value = req.form.get_field("x=y");
  1436. has_file = req.form.has_file("file1");
  1437. const auto &file = req.form.get_file("file1");
  1438. file_name = file.name;
  1439. file_filename = file.filename;
  1440. res.set_content("ok", "text/plain");
  1441. });
  1442. auto port = svr.bind_to_any_port(HOST);
  1443. thread t = thread([&] { svr.listen_after_bind(); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. t.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. UploadFormDataItems items = {
  1451. {"x=y", "field-value", "", ""},
  1452. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1453. };
  1454. Client cli(HOST, port);
  1455. auto res = cli.Post("/quoted", items);
  1456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1457. ASSERT_EQ(StatusCode::OK_200, res->status);
  1458. EXPECT_TRUE(has_field);
  1459. EXPECT_EQ("field-value", field_value);
  1460. EXPECT_TRUE(has_file);
  1461. EXPECT_EQ("file1", file_name);
  1462. EXPECT_EQ("a;b=report.pdf", file_filename);
  1463. }
  1464. TEST(GetHeaderValueTest, DefaultValue) {
  1465. Headers headers = {{"Dummy", "Dummy"}};
  1466. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1467. EXPECT_STREQ("text/plain", val);
  1468. }
  1469. TEST(GetHeaderValueTest, DefaultValueInt) {
  1470. Headers headers = {{"Dummy", "Dummy"}};
  1471. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1472. EXPECT_EQ(100ull, val);
  1473. }
  1474. TEST(GetHeaderValueTest, RegularValue) {
  1475. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1476. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1477. EXPECT_STREQ("text/html", val);
  1478. }
  1479. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1480. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1481. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1482. EXPECT_STREQ("text/html", val);
  1483. }
  1484. TEST(GetHeaderValueTest, SetContent) {
  1485. Response res;
  1486. res.set_content("html", "text/html");
  1487. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1488. res.set_content("text", "text/plain");
  1489. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1490. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1491. }
  1492. TEST(GetHeaderValueTest, RegularValueInt) {
  1493. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1494. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1495. EXPECT_EQ(100ull, val);
  1496. }
  1497. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1498. Headers headers = {{"Content-Length", "x"}};
  1499. auto is_invalid_value = false;
  1500. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1501. is_invalid_value);
  1502. EXPECT_EQ(0ull, val);
  1503. EXPECT_TRUE(is_invalid_value);
  1504. }
  1505. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1506. // An all-digit value that overflows size_t must be reported as invalid, not
  1507. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1508. // a large length to a small one on 32-bit builds, leaving the framing length
  1509. // wrong while is_invalid_value stayed false.
  1510. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1511. auto is_invalid_value = false;
  1512. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1513. is_invalid_value);
  1514. EXPECT_TRUE(is_invalid_value);
  1515. // A well-formed length is unaffected.
  1516. Headers ok = {{"Content-Length", "1234"}};
  1517. is_invalid_value = false;
  1518. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1519. is_invalid_value);
  1520. EXPECT_EQ(1234ull, val);
  1521. EXPECT_FALSE(is_invalid_value);
  1522. }
  1523. TEST(GetHeaderValueTest, Range) {
  1524. {
  1525. Headers headers = {make_range_header({{1, -1}})};
  1526. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1527. EXPECT_STREQ("bytes=1-", val);
  1528. }
  1529. {
  1530. Headers headers = {make_range_header({{-1, 1}})};
  1531. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1532. EXPECT_STREQ("bytes=-1", val);
  1533. }
  1534. {
  1535. Headers headers = {make_range_header({{1, 10}})};
  1536. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1537. EXPECT_STREQ("bytes=1-10", val);
  1538. }
  1539. {
  1540. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1541. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1542. EXPECT_STREQ("bytes=1-10, 100-", val);
  1543. }
  1544. {
  1545. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1546. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1547. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1548. }
  1549. {
  1550. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1551. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1552. EXPECT_STREQ("bytes=0-0, -1", val);
  1553. }
  1554. }
  1555. TEST(BearerTokenAuthTest, SchemeValidation) {
  1556. // A value shorter than "Bearer " must not throw from the fixed-length
  1557. // substr, and a non-Bearer scheme must not be reported as a token.
  1558. struct {
  1559. const char *value;
  1560. const char *expected;
  1561. } cases[] = {
  1562. {"x", ""},
  1563. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1564. {"Bearer abc123", "abc123"},
  1565. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1566. };
  1567. for (const auto &c : cases) {
  1568. Request req;
  1569. req.set_header("Authorization", c.value);
  1570. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1571. }
  1572. }
  1573. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1574. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1575. // to depend on the standard library (libstdc++ handed back duplicates in
  1576. // reverse insertion order, libc++ in insertion order).
  1577. Request req;
  1578. req.set_header("Accept-Encoding", "gzip");
  1579. req.set_header("Accept-Encoding", "deflate");
  1580. req.set_header("Accept-Encoding", "br");
  1581. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1582. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1583. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1584. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1585. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1586. }
  1587. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1588. Request req;
  1589. req.set_header("X-Test", "only");
  1590. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1591. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1592. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1593. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1594. }
  1595. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1596. Headers headers;
  1597. headers.emplace("Host", "example.com");
  1598. headers.emplace("Accept-Encoding", "gzip");
  1599. headers.emplace("User-Agent", "test");
  1600. headers.emplace("Accept-Encoding", "deflate");
  1601. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1602. "Accept-Encoding=deflate ",
  1603. entries_to_string(headers));
  1604. }
  1605. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1606. Headers headers = {{"Content-Type", "text/html"},
  1607. {"CONTENT-TYPE", "text/xml"}};
  1608. EXPECT_EQ(2U, headers.count("content-type"));
  1609. auto it = headers.find("content-type");
  1610. ASSERT_TRUE(it != headers.end());
  1611. EXPECT_EQ("text/html", it->second);
  1612. }
  1613. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1614. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1615. // drop only those fields and leave everything positioned between them.
  1616. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1617. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1618. auto rng = headers.equal_range("a");
  1619. headers.erase(rng.first, rng.second);
  1620. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1621. }
  1622. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1623. Headers headers = {
  1624. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1625. EXPECT_EQ(3U, headers.erase("A"));
  1626. EXPECT_EQ(0U, headers.count("A"));
  1627. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1628. }
  1629. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1630. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1631. headers.emplace_front("Host", "example.com");
  1632. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1633. entries_to_string(headers));
  1634. }
  1635. TEST(ParseHeaderValueTest, Range) {
  1636. {
  1637. Ranges ranges;
  1638. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1639. EXPECT_TRUE(ret);
  1640. EXPECT_EQ(1u, ranges.size());
  1641. EXPECT_EQ(1u, ranges[0].first);
  1642. EXPECT_EQ(-1, ranges[0].second);
  1643. }
  1644. {
  1645. Ranges ranges;
  1646. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1647. EXPECT_TRUE(ret);
  1648. EXPECT_EQ(1u, ranges.size());
  1649. EXPECT_EQ(-1, ranges[0].first);
  1650. EXPECT_EQ(1u, ranges[0].second);
  1651. }
  1652. {
  1653. Ranges ranges;
  1654. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1655. EXPECT_TRUE(ret);
  1656. EXPECT_EQ(1u, ranges.size());
  1657. EXPECT_EQ(1u, ranges[0].first);
  1658. EXPECT_EQ(10u, ranges[0].second);
  1659. }
  1660. {
  1661. Ranges ranges;
  1662. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1663. EXPECT_FALSE(ret);
  1664. }
  1665. {
  1666. Ranges ranges;
  1667. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1668. EXPECT_TRUE(ret);
  1669. EXPECT_EQ(2u, ranges.size());
  1670. EXPECT_EQ(1u, ranges[0].first);
  1671. EXPECT_EQ(10u, ranges[0].second);
  1672. EXPECT_EQ(100u, ranges[1].first);
  1673. EXPECT_EQ(-1, ranges[1].second);
  1674. }
  1675. {
  1676. Ranges ranges;
  1677. auto ret =
  1678. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1679. EXPECT_TRUE(ret);
  1680. EXPECT_EQ(3u, ranges.size());
  1681. EXPECT_EQ(1u, ranges[0].first);
  1682. EXPECT_EQ(10u, ranges[0].second);
  1683. EXPECT_EQ(100u, ranges[1].first);
  1684. EXPECT_EQ(200u, ranges[1].second);
  1685. EXPECT_EQ(300u, ranges[2].first);
  1686. EXPECT_EQ(400u, ranges[2].second);
  1687. }
  1688. {
  1689. Ranges ranges;
  1690. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1691. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1700. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1701. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1702. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1703. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1704. EXPECT_FALSE(
  1705. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1706. EXPECT_TRUE(ranges.empty());
  1707. }
  1708. {
  1709. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1710. // remainder of the representation, so it stays accepted.
  1711. Ranges ranges;
  1712. auto ret =
  1713. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1714. EXPECT_TRUE(ret);
  1715. ASSERT_EQ(1u, ranges.size());
  1716. EXPECT_EQ(0, ranges[0].first);
  1717. EXPECT_EQ(-1, ranges[0].second);
  1718. }
  1719. }
  1720. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1721. Request req;
  1722. req.set_header("Accept-Encoding", "gzip");
  1723. Response res;
  1724. res.set_header("Content-Type", "text/plain");
  1725. auto ret = detail::encoding_type(req, res);
  1726. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1727. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1728. #else
  1729. EXPECT_TRUE(ret == detail::EncodingType::None);
  1730. #endif
  1731. }
  1732. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1733. Request req;
  1734. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1735. Response res;
  1736. res.set_header("Content-Type", "text/plain");
  1737. auto ret = detail::encoding_type(req, res);
  1738. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1739. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1740. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1741. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1742. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1743. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1744. #else
  1745. EXPECT_TRUE(ret == detail::EncodingType::None);
  1746. #endif
  1747. }
  1748. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1749. Request req;
  1750. req.set_header("Accept-Encoding",
  1751. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1752. Response res;
  1753. res.set_header("Content-Type", "text/plain");
  1754. auto ret = detail::encoding_type(req, res);
  1755. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1756. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1757. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1758. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1759. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1760. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1761. #else
  1762. EXPECT_TRUE(ret == detail::EncodingType::None);
  1763. #endif
  1764. }
  1765. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1766. // All supported encodings rejected with q=0 should return None
  1767. Request req;
  1768. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1769. Response res;
  1770. res.set_header("Content-Type", "text/plain");
  1771. auto ret = detail::encoding_type(req, res);
  1772. EXPECT_TRUE(ret == detail::EncodingType::None);
  1773. }
  1774. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1775. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1776. Request req;
  1777. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1778. Response res;
  1779. res.set_header("Content-Type", "text/plain");
  1780. auto ret = detail::encoding_type(req, res);
  1781. EXPECT_TRUE(ret == detail::EncodingType::None);
  1782. }
  1783. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1784. Request req;
  1785. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1786. Response res;
  1787. res.set_header("Content-Type", "text/plain");
  1788. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1789. }
  1790. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1791. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1792. Request req;
  1793. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1794. Response res;
  1795. res.set_header("Content-Type", "text/plain");
  1796. auto ret = detail::encoding_type(req, res);
  1797. EXPECT_TRUE(ret == detail::EncodingType::None);
  1798. }
  1799. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1800. // RFC 7231: Accept-Encoding values are case-insensitive
  1801. Request req;
  1802. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1803. Response res;
  1804. res.set_header("Content-Type", "text/plain");
  1805. auto ret = detail::encoding_type(req, res);
  1806. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1807. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1808. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1809. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1810. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1811. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1812. #else
  1813. EXPECT_TRUE(ret == detail::EncodingType::None);
  1814. #endif
  1815. }
  1816. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1817. // q value should determine priority, not hardcoded order
  1818. Request req;
  1819. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1820. Response res;
  1821. res.set_header("Content-Type", "text/plain");
  1822. auto ret = detail::encoding_type(req, res);
  1823. // gzip has highest q=1.0, so it should be selected even though
  1824. // br and zstd are also supported
  1825. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1826. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1827. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1828. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1829. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1830. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1831. #else
  1832. EXPECT_TRUE(ret == detail::EncodingType::None);
  1833. #endif
  1834. }
  1835. TEST(BufferStreamTest, read) {
  1836. detail::BufferStream strm1;
  1837. Stream &strm = strm1;
  1838. EXPECT_EQ(5, strm.write("hello"));
  1839. char buf[512];
  1840. EXPECT_EQ(2, strm.read(buf, 2));
  1841. EXPECT_EQ('h', buf[0]);
  1842. EXPECT_EQ('e', buf[1]);
  1843. EXPECT_EQ(2, strm.read(buf, 2));
  1844. EXPECT_EQ('l', buf[0]);
  1845. EXPECT_EQ('l', buf[1]);
  1846. EXPECT_EQ(1, strm.read(buf, 1));
  1847. EXPECT_EQ('o', buf[0]);
  1848. EXPECT_EQ(0, strm.read(buf, 1));
  1849. }
  1850. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1851. auto host = "www.httpwatch.com";
  1852. auto ip = hosted_at(host);
  1853. EXPECT_EQ("23.96.13.243", ip);
  1854. std::vector<std::string> addrs;
  1855. hosted_at(host, addrs);
  1856. EXPECT_EQ(1u, addrs.size());
  1857. }
  1858. #if 0 // It depends on each test environment...
  1859. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1860. auto host = "www.youtube.com";
  1861. std::vector<std::string> addrs;
  1862. hosted_at(host, addrs);
  1863. EXPECT_EQ(20u, addrs.size());
  1864. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1865. EXPECT_TRUE(it != addrs.end());
  1866. }
  1867. #endif
  1868. class ChunkedEncodingTest : public ::testing::Test {
  1869. protected:
  1870. ChunkedEncodingTest()
  1871. : cli_(HOST, PORT)
  1872. #ifdef CPPHTTPLIB_SSL_ENABLED
  1873. ,
  1874. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1875. #endif
  1876. {
  1877. cli_.set_connection_timeout(2);
  1878. #ifdef CPPHTTPLIB_SSL_ENABLED
  1879. cli_.enable_server_certificate_verification(false);
  1880. #endif
  1881. }
  1882. virtual void SetUp() {
  1883. read_file("./image.jpg", image_data_);
  1884. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1885. res.set_content("Hello World!", "text/plain");
  1886. });
  1887. svr_.Get(
  1888. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1889. res.set_chunked_content_provider(
  1890. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1891. size_t remaining = image_data_.size() - offset;
  1892. if (remaining == 0) {
  1893. sink.done();
  1894. } else {
  1895. constexpr size_t CHUNK_SIZE = 1024;
  1896. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1897. sink.write(&image_data_[offset], send_size);
  1898. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1899. }
  1900. return true;
  1901. });
  1902. });
  1903. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1904. svr_.wait_until_ready();
  1905. }
  1906. virtual void TearDown() {
  1907. svr_.stop();
  1908. if (!request_threads_.empty()) {
  1909. std::this_thread::sleep_for(std::chrono::seconds(1));
  1910. for (auto &t : request_threads_) {
  1911. t.join();
  1912. }
  1913. }
  1914. t_.join();
  1915. }
  1916. #ifdef CPPHTTPLIB_SSL_ENABLED
  1917. SSLClient cli_;
  1918. SSLServer svr_;
  1919. #else
  1920. Client cli_;
  1921. Server svr_;
  1922. #endif
  1923. thread t_;
  1924. std::vector<thread> request_threads_;
  1925. std::string image_data_;
  1926. };
  1927. TEST_F(ChunkedEncodingTest, NormalGet) {
  1928. auto res = cli_.Get("/chunked");
  1929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1930. std::string out;
  1931. read_file("./image.jpg", out);
  1932. EXPECT_EQ(StatusCode::OK_200, res->status);
  1933. EXPECT_EQ(out, res->body);
  1934. }
  1935. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1936. std::string body;
  1937. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1938. body.append(data, data_length);
  1939. return true;
  1940. });
  1941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1942. std::string out;
  1943. read_file("./image.jpg", out);
  1944. EXPECT_EQ(StatusCode::OK_200, res->status);
  1945. EXPECT_EQ(out, body);
  1946. }
  1947. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1948. std::string body;
  1949. auto res = cli_.Get(
  1950. "/chunked",
  1951. [&](const Response &response) {
  1952. EXPECT_EQ(StatusCode::OK_200, response.status);
  1953. return true;
  1954. },
  1955. [&](const char *data, size_t data_length) {
  1956. body.append(data, data_length);
  1957. return true;
  1958. });
  1959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1960. std::string out;
  1961. read_file("./image.jpg", out);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. EXPECT_EQ(out, body);
  1964. }
  1965. TEST(RangeTest, FromHTTPBin_Online) {
  1966. auto host = "httpbingo.org";
  1967. auto path = std::string{"/range/32"};
  1968. #ifdef CPPHTTPLIB_SSL_ENABLED
  1969. auto port = 443;
  1970. SSLClient cli(host, port);
  1971. #else
  1972. auto port = 80;
  1973. Client cli(host, port);
  1974. #endif
  1975. cli.set_connection_timeout(5);
  1976. {
  1977. auto res = cli.Get(path);
  1978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1979. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1980. EXPECT_EQ(StatusCode::OK_200, res->status);
  1981. }
  1982. {
  1983. Headers headers = {make_range_header({{1, -1}})};
  1984. auto res = cli.Get(path, headers);
  1985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1986. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1987. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1988. }
  1989. {
  1990. Headers headers = {make_range_header({{1, 10}})};
  1991. auto res = cli.Get(path, headers);
  1992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1993. EXPECT_EQ("bcdefghijk", res->body);
  1994. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1995. }
  1996. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1997. // entire resource, while the original httpbin returned 200. Both are
  1998. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1999. {
  2000. Headers headers = {make_range_header({{0, 31}})};
  2001. auto res = cli.Get(path, headers);
  2002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2003. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2004. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2005. res->status == StatusCode::PartialContent_206);
  2006. }
  2007. {
  2008. Headers headers = {make_range_header({{0, -1}})};
  2009. auto res = cli.Get(path, headers);
  2010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2011. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2012. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2013. res->status == StatusCode::PartialContent_206);
  2014. }
  2015. // go-httpbin returns 206 with clamped range for over-range requests,
  2016. // while the original httpbin returned 416. Both behaviors are observed
  2017. // in real servers, so we only verify the request succeeds.
  2018. {
  2019. Headers headers = {make_range_header({{0, 32}})};
  2020. auto res = cli.Get(path, headers);
  2021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2022. }
  2023. }
  2024. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2025. auto host = "unresolvableaddress.local";
  2026. auto path = std::string{"/"};
  2027. #ifdef CPPHTTPLIB_SSL_ENABLED
  2028. auto port = 443;
  2029. SSLClient cli(host, port);
  2030. #else
  2031. auto port = 80;
  2032. Client cli(host, port);
  2033. #endif
  2034. cli.set_connection_timeout(1);
  2035. {
  2036. auto res = cli.Get(path);
  2037. ASSERT_FALSE(res);
  2038. }
  2039. std::this_thread::sleep_for(std::chrono::seconds(8));
  2040. }
  2041. #if defined(__linux__) && defined(__GLIBC__) && \
  2042. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2043. // Forward declaration: in split builds split.py strips `inline` and moves the
  2044. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2045. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2046. // against the symbol in both header-only and split builds.
  2047. namespace httplib {
  2048. namespace detail {
  2049. int getaddrinfo_with_timeout(const char *node, const char *service,
  2050. const struct addrinfo *hints,
  2051. struct addrinfo **res, time_t timeout_sec);
  2052. } // namespace detail
  2053. } // namespace httplib
  2054. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2055. //
  2056. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2057. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2058. // gai_suspend() call hits the connection timeout the function calls
  2059. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2060. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2061. // still alive and still references the now-destroyed stack frame.
  2062. //
  2063. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2064. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2065. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2066. // and runs them in a container.
  2067. namespace {
  2068. bool should_run_issue_2431_tests() {
  2069. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2070. return v && *v && std::string(v) != "0";
  2071. }
  2072. std::string unique_unresolvable_host(int n) {
  2073. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2074. // glibc still asks the configured nameserver — which is exactly the path
  2075. // we want to exercise. A unique label per call avoids the resolver cache.
  2076. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2077. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2078. std::to_string(n) + ".invalid";
  2079. }
  2080. } // namespace
  2081. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2082. if (!should_run_issue_2431_tests()) {
  2083. GTEST_SKIP()
  2084. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2085. }
  2086. for (int i = 0; i < 8; ++i) {
  2087. struct addrinfo hints;
  2088. memset(&hints, 0, sizeof(hints));
  2089. hints.ai_family = AF_UNSPEC;
  2090. hints.ai_socktype = SOCK_STREAM;
  2091. auto host = unique_unresolvable_host(i);
  2092. struct addrinfo *result = nullptr;
  2093. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2094. &result, /*timeout_sec=*/1);
  2095. if (rc == 0 && result) { freeaddrinfo(result); }
  2096. }
  2097. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2098. // stack region they still believe holds their gaicb.
  2099. std::this_thread::sleep_for(std::chrono::seconds(3));
  2100. }
  2101. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2102. if (!should_run_issue_2431_tests()) {
  2103. GTEST_SKIP()
  2104. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2105. }
  2106. std::atomic<bool> stop{false};
  2107. std::vector<std::thread> threads;
  2108. for (int t = 0; t < 8; ++t) {
  2109. threads.emplace_back([t, &stop] {
  2110. int i = 0;
  2111. while (!stop.load(std::memory_order_relaxed)) {
  2112. struct addrinfo hints;
  2113. memset(&hints, 0, sizeof(hints));
  2114. hints.ai_family = AF_UNSPEC;
  2115. hints.ai_socktype = SOCK_STREAM;
  2116. auto host = unique_unresolvable_host(t * 100000 + i++);
  2117. struct addrinfo *result = nullptr;
  2118. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2119. &result, /*timeout_sec=*/1);
  2120. if (rc == 0 && result) { freeaddrinfo(result); }
  2121. }
  2122. });
  2123. }
  2124. std::this_thread::sleep_for(std::chrono::seconds(8));
  2125. stop.store(true, std::memory_order_relaxed);
  2126. for (auto &th : threads) {
  2127. th.join();
  2128. }
  2129. std::this_thread::sleep_for(std::chrono::seconds(3));
  2130. }
  2131. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2132. if (!should_run_issue_2431_tests()) {
  2133. GTEST_SKIP()
  2134. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2135. }
  2136. std::atomic<bool> stop{false};
  2137. std::vector<std::thread> threads;
  2138. for (int t = 0; t < 8; ++t) {
  2139. threads.emplace_back([t, &stop] {
  2140. int i = 0;
  2141. while (!stop.load(std::memory_order_relaxed)) {
  2142. auto host = unique_unresolvable_host(t * 100000 + i++);
  2143. Client cli(host, 80);
  2144. cli.set_connection_timeout(1, 0);
  2145. cli.set_read_timeout(1, 0);
  2146. cli.set_write_timeout(1, 0);
  2147. (void)cli.Get("/");
  2148. }
  2149. });
  2150. }
  2151. std::this_thread::sleep_for(std::chrono::seconds(8));
  2152. stop.store(true, std::memory_order_relaxed);
  2153. for (auto &th : threads) {
  2154. th.join();
  2155. }
  2156. std::this_thread::sleep_for(std::chrono::seconds(3));
  2157. }
  2158. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2159. TEST(ConnectionErrorTest, InvalidHost) {
  2160. auto host = "-abcde.com";
  2161. #ifdef CPPHTTPLIB_SSL_ENABLED
  2162. auto port = 443;
  2163. SSLClient cli(host, port);
  2164. #else
  2165. auto port = 80;
  2166. Client cli(host, port);
  2167. #endif
  2168. cli.set_connection_timeout(std::chrono::seconds(2));
  2169. auto res = cli.Get("/");
  2170. ASSERT_TRUE(!res);
  2171. EXPECT_EQ(Error::Connection, res.error());
  2172. }
  2173. TEST(ConnectionErrorTest, InvalidHost2) {
  2174. auto host = "httpcan.org/";
  2175. #ifdef CPPHTTPLIB_SSL_ENABLED
  2176. SSLClient cli(host);
  2177. #else
  2178. Client cli(host);
  2179. #endif
  2180. cli.set_connection_timeout(std::chrono::seconds(2));
  2181. auto res = cli.Get("/");
  2182. ASSERT_TRUE(!res);
  2183. EXPECT_EQ(Error::Connection, res.error());
  2184. }
  2185. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2186. auto host = "httpcan.org/";
  2187. #ifdef CPPHTTPLIB_SSL_ENABLED
  2188. SSLClient cli(host);
  2189. #else
  2190. Client cli(host);
  2191. #endif
  2192. cli.set_connection_timeout(std::chrono::seconds(2));
  2193. auto res = cli.Get("/");
  2194. ASSERT_TRUE(!res);
  2195. stringstream s;
  2196. s << "error code: " << res.error();
  2197. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2198. }
  2199. TEST(ConnectionErrorTest, InvalidPort) {
  2200. auto host = "localhost";
  2201. auto port = 44380;
  2202. #ifdef CPPHTTPLIB_SSL_ENABLED
  2203. SSLClient cli(host, port);
  2204. #else
  2205. Client cli(host, port);
  2206. #endif
  2207. cli.set_connection_timeout(std::chrono::seconds(2));
  2208. auto res = cli.Get("/");
  2209. ASSERT_TRUE(!res);
  2210. EXPECT_TRUE(Error::Connection == res.error() ||
  2211. Error::ConnectionTimeout == res.error());
  2212. }
  2213. TEST(ConnectionErrorTest, Timeout_Online) {
  2214. auto host = "google.com";
  2215. #ifdef CPPHTTPLIB_SSL_ENABLED
  2216. auto port = 44380;
  2217. SSLClient cli(host, port);
  2218. #else
  2219. auto port = 8080;
  2220. Client cli(host, port);
  2221. #endif
  2222. cli.set_connection_timeout(std::chrono::seconds(2));
  2223. // only probe one address type so that the error reason
  2224. // correlates to the timed-out IPv4, not the unsupported
  2225. // IPv6 connection attempt
  2226. cli.set_address_family(AF_INET);
  2227. auto res = cli.Get("/");
  2228. ASSERT_TRUE(!res);
  2229. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2230. }
  2231. TEST(CancelTest, NoCancel_Online) {
  2232. auto host = "httpbingo.org";
  2233. auto path = std::string{"/range/32"};
  2234. #ifdef CPPHTTPLIB_SSL_ENABLED
  2235. auto port = 443;
  2236. SSLClient cli(host, port);
  2237. #else
  2238. auto port = 80;
  2239. Client cli(host, port);
  2240. #endif
  2241. cli.set_connection_timeout(std::chrono::seconds(5));
  2242. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2244. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2245. EXPECT_EQ(StatusCode::OK_200, res->status);
  2246. }
  2247. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2248. // Use /bytes with a large payload so that the DownloadProgress callback
  2249. // (which only fires for Content-Length responses) is invoked before the
  2250. // entire body is received, giving cancellation a chance to fire.
  2251. auto host = "httpbingo.org";
  2252. auto path = std::string{"/bytes/524288"};
  2253. #ifdef CPPHTTPLIB_SSL_ENABLED
  2254. auto port = 443;
  2255. SSLClient cli(host, port);
  2256. #else
  2257. auto port = 80;
  2258. Client cli(host, port);
  2259. #endif
  2260. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2261. cli.set_connection_timeout(std::chrono::seconds(5));
  2262. ASSERT_TRUE(!res);
  2263. EXPECT_EQ(Error::Canceled, res.error());
  2264. }
  2265. TEST(CancelTest, WithCancelLargePayload_Online) {
  2266. auto host = "httpbingo.org";
  2267. auto path = std::string{"/bytes/524288"};
  2268. #ifdef CPPHTTPLIB_SSL_ENABLED
  2269. auto port = 443;
  2270. SSLClient cli(host, port);
  2271. #else
  2272. auto port = 80;
  2273. Client cli(host, port);
  2274. #endif
  2275. cli.set_connection_timeout(std::chrono::seconds(5));
  2276. uint32_t count = 0;
  2277. auto res =
  2278. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2279. ASSERT_TRUE(!res);
  2280. EXPECT_EQ(Error::Canceled, res.error());
  2281. }
  2282. TEST(CancelTest, NoCancelPost) {
  2283. Server svr;
  2284. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2285. res.set_content("Hello World!", "text/plain");
  2286. });
  2287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2288. auto se = detail::scope_exit([&] {
  2289. svr.stop();
  2290. thread.join();
  2291. ASSERT_FALSE(svr.is_running());
  2292. });
  2293. svr.wait_until_ready();
  2294. Client cli(HOST, PORT);
  2295. cli.set_connection_timeout(std::chrono::seconds(5));
  2296. auto res =
  2297. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2298. "application/json", [](uint64_t, uint64_t) { return true; });
  2299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2300. EXPECT_EQ("Hello World!", res->body);
  2301. EXPECT_EQ(StatusCode::OK_200, res->status);
  2302. }
  2303. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2304. Server svr;
  2305. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2306. res.set_content("Hello World!", "text/plain");
  2307. });
  2308. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2309. auto se = detail::scope_exit([&] {
  2310. svr.stop();
  2311. thread.join();
  2312. ASSERT_FALSE(svr.is_running());
  2313. });
  2314. svr.wait_until_ready();
  2315. Client cli(HOST, PORT);
  2316. cli.set_connection_timeout(std::chrono::seconds(5));
  2317. auto res =
  2318. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2319. "application/json", [](uint64_t, uint64_t) { return false; });
  2320. ASSERT_TRUE(!res);
  2321. EXPECT_EQ(Error::Canceled, res.error());
  2322. }
  2323. TEST(CancelTest, WithCancelLargePayloadPost) {
  2324. Server svr;
  2325. svr.set_payload_max_length(200 * 1024 * 1024);
  2326. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2327. res.set_content(LARGE_DATA, "text/plain");
  2328. });
  2329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2330. auto se = detail::scope_exit([&] {
  2331. svr.stop();
  2332. thread.join();
  2333. ASSERT_FALSE(svr.is_running());
  2334. });
  2335. svr.wait_until_ready();
  2336. Client cli(HOST, PORT);
  2337. cli.set_payload_max_length(200 * 1024 * 1024);
  2338. cli.set_connection_timeout(std::chrono::seconds(5));
  2339. auto res =
  2340. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2341. "application/json", [](uint64_t, uint64_t) { return false; });
  2342. ASSERT_TRUE(!res);
  2343. EXPECT_EQ(Error::Canceled, res.error());
  2344. }
  2345. TEST(CancelTest, NoCancelPut) {
  2346. Server svr;
  2347. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2348. res.set_content("Hello World!", "text/plain");
  2349. });
  2350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2351. auto se = detail::scope_exit([&] {
  2352. svr.stop();
  2353. thread.join();
  2354. ASSERT_FALSE(svr.is_running());
  2355. });
  2356. svr.wait_until_ready();
  2357. Client cli(HOST, PORT);
  2358. cli.set_connection_timeout(std::chrono::seconds(5));
  2359. auto res =
  2360. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2361. "application/json", [](uint64_t, uint64_t) { return true; });
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. EXPECT_EQ("Hello World!", res->body);
  2364. EXPECT_EQ(StatusCode::OK_200, res->status);
  2365. }
  2366. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2367. Server svr;
  2368. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2369. res.set_content("Hello World!", "text/plain");
  2370. });
  2371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2372. auto se = detail::scope_exit([&] {
  2373. svr.stop();
  2374. thread.join();
  2375. ASSERT_FALSE(svr.is_running());
  2376. });
  2377. svr.wait_until_ready();
  2378. Client cli(HOST, PORT);
  2379. cli.set_connection_timeout(std::chrono::seconds(5));
  2380. auto res =
  2381. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2382. "application/json", [](uint64_t, uint64_t) { return false; });
  2383. ASSERT_TRUE(!res);
  2384. EXPECT_EQ(Error::Canceled, res.error());
  2385. }
  2386. TEST(CancelTest, WithCancelLargePayloadPut) {
  2387. Server svr;
  2388. svr.set_payload_max_length(200 * 1024 * 1024);
  2389. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2390. res.set_content(LARGE_DATA, "text/plain");
  2391. });
  2392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2393. auto se = detail::scope_exit([&] {
  2394. svr.stop();
  2395. thread.join();
  2396. ASSERT_FALSE(svr.is_running());
  2397. });
  2398. svr.wait_until_ready();
  2399. Client cli(HOST, PORT);
  2400. cli.set_payload_max_length(200 * 1024 * 1024);
  2401. cli.set_connection_timeout(std::chrono::seconds(5));
  2402. auto res =
  2403. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2404. "application/json", [](uint64_t, uint64_t) { return false; });
  2405. ASSERT_TRUE(!res);
  2406. EXPECT_EQ(Error::Canceled, res.error());
  2407. }
  2408. TEST(CancelTest, NoCancelPatch) {
  2409. Server svr;
  2410. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2411. res.set_content("Hello World!", "text/plain");
  2412. });
  2413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2414. auto se = detail::scope_exit([&] {
  2415. svr.stop();
  2416. thread.join();
  2417. ASSERT_FALSE(svr.is_running());
  2418. });
  2419. svr.wait_until_ready();
  2420. Client cli(HOST, PORT);
  2421. cli.set_connection_timeout(std::chrono::seconds(5));
  2422. auto res =
  2423. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2424. "application/json", [](uint64_t, uint64_t) { return true; });
  2425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2426. EXPECT_EQ("Hello World!", res->body);
  2427. EXPECT_EQ(StatusCode::OK_200, res->status);
  2428. }
  2429. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2430. Server svr;
  2431. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2432. res.set_content("Hello World!", "text/plain");
  2433. });
  2434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2435. auto se = detail::scope_exit([&] {
  2436. svr.stop();
  2437. thread.join();
  2438. ASSERT_FALSE(svr.is_running());
  2439. });
  2440. svr.wait_until_ready();
  2441. Client cli(HOST, PORT);
  2442. cli.set_connection_timeout(std::chrono::seconds(5));
  2443. auto res =
  2444. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2445. "application/json", [](uint64_t, uint64_t) { return false; });
  2446. ASSERT_TRUE(!res);
  2447. EXPECT_EQ(Error::Canceled, res.error());
  2448. }
  2449. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2450. Server svr;
  2451. svr.set_payload_max_length(200 * 1024 * 1024);
  2452. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2453. res.set_content(LARGE_DATA, "text/plain");
  2454. });
  2455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2456. auto se = detail::scope_exit([&] {
  2457. svr.stop();
  2458. thread.join();
  2459. ASSERT_FALSE(svr.is_running());
  2460. });
  2461. svr.wait_until_ready();
  2462. Client cli(HOST, PORT);
  2463. cli.set_payload_max_length(200 * 1024 * 1024);
  2464. cli.set_connection_timeout(std::chrono::seconds(5));
  2465. auto res =
  2466. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2467. "application/json", [](uint64_t, uint64_t) { return false; });
  2468. ASSERT_TRUE(!res);
  2469. EXPECT_EQ(Error::Canceled, res.error());
  2470. }
  2471. TEST(CancelTest, NoCancelDelete) {
  2472. Server svr;
  2473. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2474. res.set_content("Hello World!", "text/plain");
  2475. });
  2476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2477. auto se = detail::scope_exit([&] {
  2478. svr.stop();
  2479. thread.join();
  2480. ASSERT_FALSE(svr.is_running());
  2481. });
  2482. svr.wait_until_ready();
  2483. Client cli(HOST, PORT);
  2484. cli.set_connection_timeout(std::chrono::seconds(5));
  2485. auto res =
  2486. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2487. "application/json", [](uint64_t, uint64_t) { return true; });
  2488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2489. EXPECT_EQ("Hello World!", res->body);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. }
  2492. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2493. Server svr;
  2494. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2495. res.set_content("Hello World!", "text/plain");
  2496. });
  2497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2498. auto se = detail::scope_exit([&] {
  2499. svr.stop();
  2500. thread.join();
  2501. ASSERT_FALSE(svr.is_running());
  2502. });
  2503. svr.wait_until_ready();
  2504. Client cli(HOST, PORT);
  2505. cli.set_connection_timeout(std::chrono::seconds(5));
  2506. auto res =
  2507. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2508. "application/json", [](uint64_t, uint64_t) { return false; });
  2509. ASSERT_TRUE(!res);
  2510. EXPECT_EQ(Error::Canceled, res.error());
  2511. }
  2512. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2513. Server svr;
  2514. svr.set_payload_max_length(200 * 1024 * 1024);
  2515. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2516. res.set_content(LARGE_DATA, "text/plain");
  2517. });
  2518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2519. auto se = detail::scope_exit([&] {
  2520. svr.stop();
  2521. thread.join();
  2522. ASSERT_FALSE(svr.is_running());
  2523. });
  2524. svr.wait_until_ready();
  2525. Client cli(HOST, PORT);
  2526. cli.set_payload_max_length(200 * 1024 * 1024);
  2527. cli.set_connection_timeout(std::chrono::seconds(5));
  2528. auto res =
  2529. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2530. "application/json", [](uint64_t, uint64_t) { return false; });
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_EQ(Error::Canceled, res.error());
  2533. }
  2534. static std::string remove_whitespace(const std::string &input) {
  2535. std::string output;
  2536. output.reserve(input.size());
  2537. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2538. [](unsigned char c) { return !std::isspace(c); });
  2539. return output;
  2540. }
  2541. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2542. auto host = "httpbingo.org";
  2543. auto path = std::string{"/basic-auth/hello/world"};
  2544. #ifdef CPPHTTPLIB_SSL_ENABLED
  2545. auto port = 443;
  2546. SSLClient cli(host, port);
  2547. #else
  2548. auto port = 80;
  2549. Client cli(host, port);
  2550. #endif
  2551. {
  2552. auto res = cli.Get(path);
  2553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2554. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2555. }
  2556. {
  2557. auto res = cli.Get(
  2558. path, Headers{make_basic_authentication_header("hello", "world")});
  2559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2560. auto body = remove_whitespace(res->body);
  2561. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2562. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2563. EXPECT_EQ(StatusCode::OK_200, res->status);
  2564. }
  2565. {
  2566. cli.set_basic_auth("hello", "world");
  2567. auto res = cli.Get(path);
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. auto body = remove_whitespace(res->body);
  2570. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2571. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2572. EXPECT_EQ(StatusCode::OK_200, res->status);
  2573. }
  2574. {
  2575. cli.set_basic_auth("hello", "bad");
  2576. auto res = cli.Get(path);
  2577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2578. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2579. }
  2580. {
  2581. cli.set_basic_auth("bad", "world");
  2582. auto res = cli.Get(path);
  2583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2584. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2585. }
  2586. }
  2587. #ifdef CPPHTTPLIB_SSL_ENABLED
  2588. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2589. auto host = "httpbingo.org";
  2590. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2591. auto paths = std::vector<std::string>{
  2592. "/digest-auth/auth/hello/world/MD5",
  2593. "/digest-auth/auth/hello/world/SHA-256",
  2594. };
  2595. auto port = 443;
  2596. SSLClient cli(host, port);
  2597. {
  2598. auto res = cli.Get(unauth_path);
  2599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2600. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2601. }
  2602. {
  2603. cli.set_digest_auth("hello", "world");
  2604. for (const auto &path : paths) {
  2605. auto res = cli.Get(path.c_str());
  2606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2607. auto body = remove_whitespace(res->body);
  2608. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2609. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. }
  2612. cli.set_digest_auth("hello", "bad");
  2613. for (const auto &path : paths) {
  2614. auto res = cli.Get(path.c_str());
  2615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2616. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2617. }
  2618. }
  2619. }
  2620. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2621. // comma-separated list of challenges, and each challenge may itself carry a
  2622. // comma-separated auth-param list, so a server can legally offer Basic
  2623. // before Digest, either as two field lines or packed into one. Runs one 401
  2624. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2625. // value() joins them in receipt order) and checks that the retry carries a
  2626. // well-formed Digest Authorization header naming expected_realm.
  2627. static void
  2628. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2629. const std::string &expected_realm) {
  2630. std::atomic<int> hits{0};
  2631. Server svr;
  2632. svr.Get("/x", [&](const Request &req, Response &res) {
  2633. if (++hits == 1) {
  2634. res.status = StatusCode::Unauthorized_401;
  2635. for (const auto &challenge : challenges) {
  2636. res.set_header("WWW-Authenticate", challenge);
  2637. }
  2638. } else {
  2639. auto authorization = req.get_header_value("Authorization");
  2640. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2641. EXPECT_NE(std::string::npos,
  2642. authorization.find("realm=\"" + expected_realm + "\""));
  2643. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2644. res.set_content("ok", "text/plain");
  2645. }
  2646. });
  2647. auto port = svr.bind_to_any_port(HOST);
  2648. std::thread t([&]() { svr.listen_after_bind(); });
  2649. auto se = detail::scope_exit([&] {
  2650. svr.stop();
  2651. t.join();
  2652. });
  2653. svr.wait_until_ready();
  2654. Client cli(HOST, port);
  2655. cli.set_digest_auth("hello", "world");
  2656. auto res = cli.Get("/x");
  2657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2658. EXPECT_EQ(2, hits.load());
  2659. }
  2660. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2661. static const char *kDigestChallenge =
  2662. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2663. "algorithm=MD5";
  2664. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2665. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2666. "testrealm");
  2667. }
  2668. // Same challenge list with the schemes in the opposite order, to make sure
  2669. // the fix above didn't just special-case "Basic first".
  2670. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2671. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2672. "testrealm");
  2673. }
  2674. // A comma inside a quoted auth-param value must not be mistaken for the
  2675. // separator between two challenges (or two auth-params).
  2676. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2677. run_digest_challenge_list_test(
  2678. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2679. "algorithm=MD5"},
  2680. "test,realm");
  2681. }
  2682. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2683. // make_digest_authentication_header() dereferences both unconditionally, so
  2684. // a server sending a challenge missing either one must not be treated as
  2685. // usable -- doing so used to crash the client with std::out_of_range.
  2686. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2687. Server svr;
  2688. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2689. res.status = StatusCode::Unauthorized_401;
  2690. res.set_header("WWW-Authenticate", challenge);
  2691. });
  2692. auto port = svr.bind_to_any_port(HOST);
  2693. std::thread t([&]() { svr.listen_after_bind(); });
  2694. auto se = detail::scope_exit([&] {
  2695. svr.stop();
  2696. t.join();
  2697. });
  2698. svr.wait_until_ready();
  2699. Client cli(HOST, port);
  2700. cli.set_digest_auth("hello", "world");
  2701. auto res = cli.Get("/x");
  2702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2703. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2704. }
  2705. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2706. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2707. }
  2708. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2709. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2710. }
  2711. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2712. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2713. }
  2714. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2715. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2716. // when storing the values, so the header builder has to re-escape them (and
  2717. // keep algorithm a bare token); otherwise the value breaks out of its
  2718. // quoted-string and injects extra auth-params into the client's Authorization.
  2719. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2720. std::atomic<int> hits{0};
  2721. std::string authorization;
  2722. Server svr;
  2723. svr.Get("/x", [&](const Request &req, Response &res) {
  2724. if (++hits == 1) {
  2725. res.status = StatusCode::Unauthorized_401;
  2726. // On the wire the quotes embedded in the values are backslash-escaped.
  2727. res.set_header("WWW-Authenticate",
  2728. "Digest realm=\"testrealm\", "
  2729. "nonce=\"n\\\"; injected=\\\"x\", "
  2730. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2731. } else {
  2732. authorization = req.get_header_value("Authorization");
  2733. res.set_content("ok", "text/plain");
  2734. }
  2735. });
  2736. auto port = svr.bind_to_any_port(HOST);
  2737. std::thread t([&]() { svr.listen_after_bind(); });
  2738. auto se = detail::scope_exit([&] {
  2739. svr.stop();
  2740. t.join();
  2741. });
  2742. svr.wait_until_ready();
  2743. Client cli(HOST, port);
  2744. cli.set_digest_auth("hello", "world");
  2745. auto res = cli.Get("/x");
  2746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2747. EXPECT_EQ(2, hits.load());
  2748. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2749. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2750. // inside its quoted-string rather than starting an "injected" auth-param.
  2751. EXPECT_NE(std::string::npos,
  2752. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2753. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2754. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2755. }
  2756. #endif
  2757. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2758. auto host = "google.com";
  2759. auto another_host = "example.com";
  2760. auto wrong_ip = "0.0.0.0";
  2761. #ifdef CPPHTTPLIB_SSL_ENABLED
  2762. SSLClient cli(host);
  2763. #else
  2764. Client cli(host);
  2765. #endif
  2766. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2767. auto res = cli.Get("/");
  2768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2769. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2770. }
  2771. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2772. auto host = "google.com";
  2773. auto wrong_ip = "0.0.0.0";
  2774. #ifdef CPPHTTPLIB_SSL_ENABLED
  2775. SSLClient cli(host);
  2776. #else
  2777. Client cli(host);
  2778. #endif
  2779. cli.set_hostname_addr_map({{host, wrong_ip}});
  2780. auto res = cli.Get("/");
  2781. ASSERT_TRUE(!res);
  2782. EXPECT_EQ(Error::Connection, res.error());
  2783. }
  2784. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2785. // A mapped value that is not an IP literal must be resolved. "localhost"
  2786. // resolves from the hosts file, so this test needs no external DNS.
  2787. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2788. auto host = "target.invalid";
  2789. Server svr;
  2790. std::string received_host;
  2791. svr.Get("/hi", [&](const Request &req, Response &res) {
  2792. received_host = req.get_header_value("Host");
  2793. res.set_content("Hello World!", "text/plain");
  2794. });
  2795. auto port = svr.bind_to_any_port(HOST);
  2796. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2797. auto se = detail::scope_exit([&] {
  2798. svr.stop();
  2799. thread.join();
  2800. ASSERT_FALSE(svr.is_running());
  2801. });
  2802. svr.wait_until_ready();
  2803. Client cli(host, port);
  2804. cli.set_hostname_addr_map({{host, HOST}});
  2805. auto res = cli.Get("/hi");
  2806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2807. EXPECT_EQ(StatusCode::OK_200, res->status);
  2808. // The mapping only redirects the connection; the identity stays host_.
  2809. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2810. }
  2811. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2812. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2813. auto host = "target.invalid";
  2814. Server svr;
  2815. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2816. res.set_content("Hello World!", "text/plain");
  2817. });
  2818. auto port = svr.bind_to_any_port("127.0.0.1");
  2819. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2820. auto se = detail::scope_exit([&] {
  2821. svr.stop();
  2822. thread.join();
  2823. ASSERT_FALSE(svr.is_running());
  2824. });
  2825. svr.wait_until_ready();
  2826. Client cli(host, port);
  2827. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2828. auto res = cli.Get("/hi");
  2829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2830. EXPECT_EQ(StatusCode::OK_200, res->status);
  2831. }
  2832. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2833. // An empty mapped value must leave host_ as the connection target. Without
  2834. // that guard the empty value would become the host argument, getaddrinfo
  2835. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2836. // loopback - silently connecting somewhere the caller never asked for.
  2837. // The server listens on loopback, so such a fallback would succeed and is
  2838. // therefore observable as a failure of this test.
  2839. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2840. Server svr;
  2841. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2842. res.set_content("Hello World!", "text/plain");
  2843. });
  2844. auto port = svr.bind_to_any_port(HOST);
  2845. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2846. auto se = detail::scope_exit([&] {
  2847. svr.stop();
  2848. thread.join();
  2849. ASSERT_FALSE(svr.is_running());
  2850. });
  2851. svr.wait_until_ready();
  2852. Client cli(blackhole, port);
  2853. cli.set_hostname_addr_map({{blackhole, ""}});
  2854. cli.set_connection_timeout(1);
  2855. auto res = cli.Get("/hi");
  2856. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2857. }
  2858. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2859. auto host = "httpbingo.org";
  2860. auto path = std::string{"/absolute-redirect/3"};
  2861. #ifdef CPPHTTPLIB_SSL_ENABLED
  2862. SSLClient cli(host);
  2863. #else
  2864. Client cli(host);
  2865. #endif
  2866. cli.set_follow_location(true);
  2867. auto res = cli.Get(path);
  2868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2869. EXPECT_EQ(StatusCode::OK_200, res->status);
  2870. }
  2871. TEST(RedirectTest, Redirect_Online) {
  2872. auto host = "httpbingo.org";
  2873. auto path = std::string{"/redirect/3"};
  2874. #ifdef CPPHTTPLIB_SSL_ENABLED
  2875. SSLClient cli(host);
  2876. #else
  2877. Client cli(host);
  2878. #endif
  2879. cli.set_follow_location(true);
  2880. auto res = cli.Get(path);
  2881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2882. EXPECT_EQ(StatusCode::OK_200, res->status);
  2883. }
  2884. TEST(RelativeRedirectTest, Redirect_Online) {
  2885. auto host = "httpbingo.org";
  2886. auto path = std::string{"/relative-redirect/3"};
  2887. #ifdef CPPHTTPLIB_SSL_ENABLED
  2888. SSLClient cli(host);
  2889. #else
  2890. Client cli(host);
  2891. #endif
  2892. cli.set_follow_location(true);
  2893. auto res = cli.Get(path);
  2894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2895. EXPECT_EQ(StatusCode::OK_200, res->status);
  2896. }
  2897. TEST(TooManyRedirectTest, Redirect_Online) {
  2898. auto host = "httpbingo.org";
  2899. auto path = std::string{"/redirect/21"};
  2900. #ifdef CPPHTTPLIB_SSL_ENABLED
  2901. SSLClient cli(host);
  2902. #else
  2903. Client cli(host);
  2904. #endif
  2905. cli.set_follow_location(true);
  2906. auto res = cli.Get(path);
  2907. ASSERT_TRUE(!res);
  2908. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2909. }
  2910. #ifdef CPPHTTPLIB_SSL_ENABLED
  2911. TEST(YahooRedirectTest, Redirect_Online) {
  2912. Client cli("yahoo.com");
  2913. auto res = cli.Get("/");
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2916. cli.set_follow_location(true);
  2917. res = cli.Get("/");
  2918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2919. EXPECT_EQ(StatusCode::OK_200, res->status);
  2920. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2921. }
  2922. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2923. #define REDIR_HOST "httpbingo.org"
  2924. #define REDIR_PATH "/redirect-to"
  2925. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2926. SSLClient cli(REDIR_HOST);
  2927. cli.set_follow_location(true);
  2928. auto res =
  2929. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2931. EXPECT_EQ(StatusCode::OK_200, res->status);
  2932. }
  2933. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2934. SSLClient cli(REDIR_HOST);
  2935. cli.set_follow_location(true);
  2936. Params params;
  2937. params.emplace("url", "http://example.com");
  2938. params.emplace("status_code", "302");
  2939. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2941. EXPECT_EQ(StatusCode::OK_200, res->status);
  2942. }
  2943. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2944. SSLClient cli(REDIR_HOST);
  2945. cli.set_follow_location(true);
  2946. Params params;
  2947. params.emplace("url", "http://example.com");
  2948. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2950. EXPECT_EQ(StatusCode::OK_200, res->status);
  2951. }
  2952. TEST(UrlWithSpace, Redirect_Online) {
  2953. SSLClient cli("edge.forgecdn.net");
  2954. cli.set_follow_location(true);
  2955. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2957. EXPECT_EQ(StatusCode::OK_200, res->status);
  2958. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2959. }
  2960. #endif
  2961. #if !defined(_WIN32) && !defined(_WIN64)
  2962. TEST(ReceiveSignals, Signal) {
  2963. auto setupSignalHandlers = []() {
  2964. struct sigaction act;
  2965. sigemptyset(&act.sa_mask);
  2966. act.sa_flags = SA_SIGINFO;
  2967. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2968. switch (sig) {
  2969. case SIGINT:
  2970. default: break;
  2971. }
  2972. };
  2973. ::sigaction(SIGINT, &act, nullptr);
  2974. };
  2975. Server svr;
  2976. int port = 0;
  2977. auto thread = std::thread([&]() {
  2978. setupSignalHandlers();
  2979. port = svr.bind_to_any_port(HOST);
  2980. svr.listen_after_bind();
  2981. });
  2982. auto se = detail::scope_exit([&] {
  2983. svr.stop();
  2984. thread.join();
  2985. ASSERT_FALSE(svr.is_running());
  2986. });
  2987. svr.wait_until_ready();
  2988. ASSERT_TRUE(svr.is_running());
  2989. pthread_kill(thread.native_handle(), SIGINT);
  2990. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2991. ASSERT_TRUE(svr.is_running());
  2992. }
  2993. #endif
  2994. TEST(RedirectToDifferentPort, Redirect) {
  2995. Server svr1;
  2996. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2997. res.set_content("Hello World!", "text/plain");
  2998. });
  2999. int svr1_port = 0;
  3000. auto thread1 = std::thread([&]() {
  3001. svr1_port = svr1.bind_to_any_port(HOST);
  3002. svr1.listen_after_bind();
  3003. });
  3004. Server svr2;
  3005. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3006. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3007. });
  3008. int svr2_port = 0;
  3009. auto thread2 = std::thread([&]() {
  3010. svr2_port = svr2.bind_to_any_port(HOST);
  3011. svr2.listen_after_bind();
  3012. });
  3013. auto se = detail::scope_exit([&] {
  3014. svr2.stop();
  3015. thread2.join();
  3016. svr1.stop();
  3017. thread1.join();
  3018. ASSERT_FALSE(svr2.is_running());
  3019. ASSERT_FALSE(svr1.is_running());
  3020. });
  3021. svr1.wait_until_ready();
  3022. svr2.wait_until_ready();
  3023. Client cli("localhost", svr2_port);
  3024. cli.set_follow_location(true);
  3025. auto res = cli.Get("/2");
  3026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3027. EXPECT_EQ(StatusCode::OK_200, res->status);
  3028. EXPECT_EQ("Hello World!", res->body);
  3029. }
  3030. static void
  3031. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3032. Server svr1;
  3033. std::string captured_authorization;
  3034. svr1.Get("/target", [&](const Request &req, Response &res) {
  3035. captured_authorization = req.get_header_value("Authorization");
  3036. res.set_content("OK", "text/plain");
  3037. });
  3038. int svr1_port = 0;
  3039. auto thread1 = std::thread([&]() {
  3040. svr1_port = svr1.bind_to_any_port(HOST);
  3041. svr1.listen_after_bind();
  3042. });
  3043. Server svr2;
  3044. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3045. res.set_redirect(
  3046. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3047. });
  3048. int svr2_port = 0;
  3049. auto thread2 = std::thread([&]() {
  3050. svr2_port = svr2.bind_to_any_port(HOST);
  3051. svr2.listen_after_bind();
  3052. });
  3053. auto se = detail::scope_exit([&] {
  3054. svr2.stop();
  3055. thread2.join();
  3056. svr1.stop();
  3057. thread1.join();
  3058. ASSERT_FALSE(svr2.is_running());
  3059. ASSERT_FALSE(svr1.is_running());
  3060. });
  3061. svr1.wait_until_ready();
  3062. svr2.wait_until_ready();
  3063. Client cli("localhost", svr2_port);
  3064. cli.set_follow_location(true);
  3065. set_auth(cli);
  3066. auto res = cli.Get("/redir");
  3067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3068. EXPECT_EQ(StatusCode::OK_200, res->status);
  3069. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3070. EXPECT_TRUE(captured_authorization.empty());
  3071. }
  3072. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3073. TestDoNotForwardCredentialsOnRedirect(
  3074. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3075. }
  3076. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3077. TestDoNotForwardCredentialsOnRedirect(
  3078. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3079. }
  3080. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3081. Server svr1;
  3082. std::string captured_cookie;
  3083. bool target_hit = false;
  3084. svr1.Get("/target", [&](const Request &req, Response &res) {
  3085. captured_cookie = req.get_header_value("Cookie");
  3086. target_hit = true;
  3087. res.set_content("OK", "text/plain");
  3088. });
  3089. int svr1_port = 0;
  3090. auto thread1 = std::thread([&]() {
  3091. svr1_port = svr1.bind_to_any_port(HOST);
  3092. svr1.listen_after_bind();
  3093. });
  3094. Server svr2;
  3095. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3096. res.set_redirect(
  3097. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3098. });
  3099. int svr2_port = 0;
  3100. auto thread2 = std::thread([&]() {
  3101. svr2_port = svr2.bind_to_any_port(HOST);
  3102. svr2.listen_after_bind();
  3103. });
  3104. auto se = detail::scope_exit([&] {
  3105. svr2.stop();
  3106. thread2.join();
  3107. svr1.stop();
  3108. thread1.join();
  3109. ASSERT_FALSE(svr2.is_running());
  3110. ASSERT_FALSE(svr1.is_running());
  3111. });
  3112. svr1.wait_until_ready();
  3113. svr2.wait_until_ready();
  3114. Client cli("localhost", svr2_port);
  3115. cli.set_follow_location(true);
  3116. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3117. auto res = cli.Get("/redir", headers);
  3118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3119. EXPECT_EQ(StatusCode::OK_200, res->status);
  3120. EXPECT_TRUE(target_hit);
  3121. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3122. EXPECT_TRUE(captured_cookie.empty());
  3123. }
  3124. TEST(RedirectToSamePort, ForwardCookie) {
  3125. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3126. // header so that ordinary session flows keep working.
  3127. Server svr;
  3128. std::string captured_cookie;
  3129. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3130. res.set_redirect("/target", 302);
  3131. });
  3132. svr.Get("/target", [&](const Request &req, Response &res) {
  3133. captured_cookie = req.get_header_value("Cookie");
  3134. res.set_content("OK", "text/plain");
  3135. });
  3136. auto port = svr.bind_to_any_port(HOST);
  3137. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3138. auto se = detail::scope_exit([&] {
  3139. svr.stop();
  3140. thread.join();
  3141. ASSERT_FALSE(svr.is_running());
  3142. });
  3143. svr.wait_until_ready();
  3144. Client cli(HOST, port);
  3145. cli.set_follow_location(true);
  3146. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3147. auto res = cli.Get("/redir", headers);
  3148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3149. EXPECT_EQ(StatusCode::OK_200, res->status);
  3150. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3151. }
  3152. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3153. Server svr;
  3154. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3155. // Port number that overflows int — should not crash
  3156. res.set_redirect("http://localhost:99999999999999999999/target");
  3157. });
  3158. auto port = svr.bind_to_any_port(HOST);
  3159. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3160. auto se = detail::scope_exit([&] {
  3161. svr.stop();
  3162. thread.join();
  3163. ASSERT_FALSE(svr.is_running());
  3164. });
  3165. svr.wait_until_ready();
  3166. Client cli(HOST, port);
  3167. cli.set_follow_location(true);
  3168. auto res = cli.Get("/redir");
  3169. // Should fail gracefully, not crash (no valid response due to bad port)
  3170. EXPECT_FALSE(res);
  3171. }
  3172. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3173. Server svr;
  3174. auto port = svr.bind_to_any_port(HOST);
  3175. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3176. // The server's own port followed by junk must not be followed
  3177. res.set_redirect("http://" + std::string(HOST) + ":" +
  3178. std::to_string(port) + "junk/target");
  3179. });
  3180. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3181. res.set_content("target", "text/plain");
  3182. });
  3183. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3184. auto se = detail::scope_exit([&] {
  3185. svr.stop();
  3186. thread.join();
  3187. ASSERT_FALSE(svr.is_running());
  3188. });
  3189. svr.wait_until_ready();
  3190. Client cli(HOST, port);
  3191. cli.set_follow_location(true);
  3192. auto res = cli.Get("/redir");
  3193. EXPECT_FALSE(res);
  3194. }
  3195. TEST(RedirectFromPageWithContent, Redirect) {
  3196. Server svr;
  3197. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3198. res.set_content("___", "text/plain");
  3199. res.set_redirect("/2");
  3200. });
  3201. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3202. res.set_content("Hello World!", "text/plain");
  3203. });
  3204. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3205. auto se = detail::scope_exit([&] {
  3206. svr.stop();
  3207. th.join();
  3208. ASSERT_FALSE(svr.is_running());
  3209. });
  3210. svr.wait_until_ready();
  3211. {
  3212. Client cli("localhost", PORT);
  3213. cli.set_follow_location(true);
  3214. std::string body;
  3215. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3216. body.append(data, data_length);
  3217. return true;
  3218. });
  3219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3220. EXPECT_EQ(StatusCode::OK_200, res->status);
  3221. EXPECT_EQ("Hello World!", body);
  3222. }
  3223. {
  3224. Client cli("localhost", PORT);
  3225. std::string body;
  3226. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3227. body.append(data, data_length);
  3228. return true;
  3229. });
  3230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3231. EXPECT_EQ(StatusCode::Found_302, res->status);
  3232. EXPECT_EQ("___", body);
  3233. }
  3234. }
  3235. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3236. Server svr;
  3237. auto port_str = std::to_string(PORT);
  3238. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3239. auto expected_host = "[::1]:" + port_str;
  3240. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3241. res.set_content("___", "text/plain");
  3242. // res.set_redirect("/2");
  3243. res.set_redirect(redirect_url);
  3244. });
  3245. svr.Get("/2", [&](const Request &req, Response &res) {
  3246. auto host_header = req.headers.find("Host");
  3247. ASSERT_TRUE(host_header != req.headers.end());
  3248. EXPECT_EQ(expected_host, host_header->second);
  3249. res.set_content("Hello World!", "text/plain");
  3250. });
  3251. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3252. auto se = detail::scope_exit([&] {
  3253. svr.stop();
  3254. th.join();
  3255. ASSERT_FALSE(svr.is_running());
  3256. });
  3257. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3258. // actually starts anything, so the condition !svr.is_running() will
  3259. // always remain true, and the loop never stops.
  3260. // This basically counts how many milliseconds have passed since the
  3261. // call to svr.listen(), and if after 5 seconds nothing started yet
  3262. // aborts the test.
  3263. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3264. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3265. ASSERT_LT(milliseconds, 5000U);
  3266. }
  3267. {
  3268. Client cli("::1", PORT);
  3269. cli.set_follow_location(true);
  3270. std::string body;
  3271. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3272. body.append(data, data_length);
  3273. return true;
  3274. });
  3275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3276. EXPECT_EQ(StatusCode::OK_200, res->status);
  3277. EXPECT_EQ("Hello World!", body);
  3278. }
  3279. {
  3280. Client cli("::1", PORT);
  3281. std::string body;
  3282. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3283. body.append(data, data_length);
  3284. return true;
  3285. });
  3286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3287. EXPECT_EQ(StatusCode::Found_302, res->status);
  3288. EXPECT_EQ("___", body);
  3289. }
  3290. }
  3291. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3292. Server svr;
  3293. svr.Get("/foo", [](const Request &req, Response &res) {
  3294. auto a = req.params.find("a");
  3295. if (a != req.params.end()) {
  3296. res.set_content((*a).second, "text/plain");
  3297. res.status = StatusCode::OK_200;
  3298. } else {
  3299. res.status = StatusCode::BadRequest_400;
  3300. }
  3301. });
  3302. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3303. auto se = detail::scope_exit([&] {
  3304. svr.stop();
  3305. thread.join();
  3306. ASSERT_FALSE(svr.is_running());
  3307. });
  3308. svr.wait_until_ready();
  3309. {
  3310. Client cli(HOST, PORT);
  3311. cli.set_path_encode(false);
  3312. auto res = cli.Get("/foo?a=explicitly+encoded");
  3313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3314. EXPECT_EQ(StatusCode::OK_200, res->status);
  3315. // This expects it back with a space, as the `+` won't have been
  3316. // url-encoded, and server-side the params get decoded turning `+`
  3317. // into spaces.
  3318. EXPECT_EQ("explicitly encoded", res->body);
  3319. }
  3320. }
  3321. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3322. // When path encoding is disabled the client must transmit the supplied
  3323. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3324. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3325. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3326. // than a space (0x20). Assert on the raw wire target to catch this.
  3327. Server svr;
  3328. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3329. svr.Get("/foo", [&](const Request &req, Response &res) {
  3330. EXPECT_EQ(expected_target, req.target);
  3331. res.status = StatusCode::OK_200;
  3332. });
  3333. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3334. auto se = detail::scope_exit([&] {
  3335. svr.stop();
  3336. thread.join();
  3337. ASSERT_FALSE(svr.is_running());
  3338. });
  3339. svr.wait_until_ready();
  3340. {
  3341. Client cli(HOST, PORT);
  3342. cli.set_path_encode(false);
  3343. auto res = cli.Get(expected_target.c_str());
  3344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3345. EXPECT_EQ(StatusCode::OK_200, res->status);
  3346. }
  3347. }
  3348. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3349. // `open_stream()` used to skip the path encoding that the buffered send
  3350. // path applies, so the same `path` produced different bytes in the request
  3351. // line depending on which API was used. Assert the two agree.
  3352. Server svr;
  3353. std::string target;
  3354. svr.Get(".*", [&](const Request &req, Response &res) {
  3355. target = req.target;
  3356. res.status = StatusCode::OK_200;
  3357. });
  3358. auto port = svr.bind_to_any_port(HOST);
  3359. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3360. auto se = detail::scope_exit([&] {
  3361. svr.stop();
  3362. thread.join();
  3363. ASSERT_FALSE(svr.is_running());
  3364. });
  3365. svr.wait_until_ready();
  3366. struct {
  3367. const char *path;
  3368. const char *expected;
  3369. } cases[] = {
  3370. {"/a b?x=1", "/a%20b?x=1"},
  3371. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3372. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3373. };
  3374. for (const auto &c : cases) {
  3375. Client cli(HOST, port);
  3376. target.clear();
  3377. auto res = cli.Get(c.path);
  3378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3379. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3380. auto buffered_target = target;
  3381. target.clear();
  3382. auto handle = cli.open_stream("GET", c.path);
  3383. EXPECT_TRUE(handle.is_valid())
  3384. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3385. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3386. }
  3387. }
  3388. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3389. // The `set_path_encode(false)` contract — transmit the supplied target
  3390. // verbatim — must hold for the streaming API too.
  3391. Server svr;
  3392. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3393. std::string target;
  3394. svr.Get("/foo", [&](const Request &req, Response &res) {
  3395. target = req.target;
  3396. res.status = StatusCode::OK_200;
  3397. });
  3398. auto port = svr.bind_to_any_port(HOST);
  3399. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3400. auto se = detail::scope_exit([&] {
  3401. svr.stop();
  3402. thread.join();
  3403. ASSERT_FALSE(svr.is_running());
  3404. });
  3405. svr.wait_until_ready();
  3406. {
  3407. Client cli(HOST, port);
  3408. cli.set_path_encode(false);
  3409. auto handle = cli.open_stream("GET", expected_target);
  3410. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3411. EXPECT_EQ(expected_target, target);
  3412. }
  3413. }
  3414. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3415. // With path encoding enabled a CR/LF in the target is percent-encoded
  3416. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3417. // write_request_line still backstops `set_path_encode(false)`, which is
  3418. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3419. Server svr;
  3420. // Captured before routing: the decoded path contains a newline, which a
  3421. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3422. std::string target;
  3423. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3424. target = req.target;
  3425. res.status = StatusCode::OK_200;
  3426. return Server::HandlerResponse::Handled;
  3427. });
  3428. auto port = svr.bind_to_any_port(HOST);
  3429. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3430. auto se = detail::scope_exit([&] {
  3431. svr.stop();
  3432. thread.join();
  3433. ASSERT_FALSE(svr.is_running());
  3434. });
  3435. svr.wait_until_ready();
  3436. {
  3437. Client cli(HOST, port);
  3438. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3439. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3440. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3441. }
  3442. }
  3443. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3444. // Every control character is percent-encoded, not just CR/LF, so the target
  3445. // passes the request-target check in write_request_line.
  3446. Server svr;
  3447. std::string target;
  3448. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3449. target = req.target;
  3450. res.status = StatusCode::OK_200;
  3451. return Server::HandlerResponse::Handled;
  3452. });
  3453. auto port = svr.bind_to_any_port(HOST);
  3454. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3455. auto se = detail::scope_exit([&] {
  3456. svr.stop();
  3457. thread.join();
  3458. ASSERT_FALSE(svr.is_running());
  3459. });
  3460. svr.wait_until_ready();
  3461. {
  3462. Client cli(HOST, port);
  3463. auto res = cli.Get("/a\tb\x1b\x7f");
  3464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3465. EXPECT_EQ("/a%09b%1B%7F", target);
  3466. }
  3467. }
  3468. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3469. // Nothing may reach the wire: a raw CR/LF target would split the request
  3470. // line and inject headers.
  3471. Server svr;
  3472. // Pre-routing so that "not called" means nothing reached the server at all,
  3473. // rather than merely failing to match a handler pattern.
  3474. auto handler_called = false;
  3475. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3476. handler_called = true;
  3477. res.status = StatusCode::OK_200;
  3478. return Server::HandlerResponse::Handled;
  3479. });
  3480. auto port = svr.bind_to_any_port(HOST);
  3481. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3482. auto se = detail::scope_exit([&] {
  3483. svr.stop();
  3484. thread.join();
  3485. ASSERT_FALSE(svr.is_running());
  3486. });
  3487. svr.wait_until_ready();
  3488. {
  3489. Client cli(HOST, port);
  3490. cli.set_path_encode(false);
  3491. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3492. EXPECT_FALSE(handle.is_valid());
  3493. EXPECT_EQ(Error::Write, handle.error);
  3494. EXPECT_FALSE(handler_called);
  3495. }
  3496. }
  3497. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3498. // Which of the two branches runs is decided by whether the query component
  3499. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3500. // an empty query and must still fall back to building one from
  3501. // `req.params`, while a non-empty query must win over `req.params`.
  3502. Server svr;
  3503. std::string target;
  3504. svr.Get("/foo", [&](const Request &req, Response &res) {
  3505. target = req.target;
  3506. res.status = StatusCode::OK_200;
  3507. });
  3508. auto port = svr.bind_to_any_port(HOST);
  3509. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3510. auto se = detail::scope_exit([&] {
  3511. svr.stop();
  3512. thread.join();
  3513. ASSERT_FALSE(svr.is_running());
  3514. });
  3515. svr.wait_until_ready();
  3516. {
  3517. // Trailing `?` -> empty query component -> `req.params` is used.
  3518. Client cli(HOST, port);
  3519. Request req;
  3520. req.method = "GET";
  3521. req.path = "/foo?";
  3522. req.params.emplace("a", "1");
  3523. target.clear();
  3524. auto res = cli.send(req);
  3525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3526. EXPECT_EQ("/foo?a=1", target);
  3527. }
  3528. {
  3529. // Non-empty query in `req.path` -> `req.params` is not appended.
  3530. Client cli(HOST, port);
  3531. Request req;
  3532. req.method = "GET";
  3533. req.path = "/foo?b=2";
  3534. req.params.emplace("a", "1");
  3535. target.clear();
  3536. auto res = cli.send(req);
  3537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3538. EXPECT_EQ("/foo?b=2", target);
  3539. }
  3540. }
  3541. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3542. Server svr;
  3543. svr.Get("/", [](const Request &req, Response &) {
  3544. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3545. });
  3546. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3547. auto se = detail::scope_exit([&] {
  3548. svr.stop();
  3549. thread.join();
  3550. ASSERT_FALSE(svr.is_running());
  3551. });
  3552. svr.wait_until_ready();
  3553. {
  3554. Client cli(HOST, PORT);
  3555. cli.set_path_encode(false);
  3556. auto res = cli.Get("/?something=%0A");
  3557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3558. EXPECT_EQ(StatusCode::OK_200, res->status);
  3559. }
  3560. }
  3561. TEST(BindServerTest, BindDualStack) {
  3562. Server svr;
  3563. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3564. res.set_content("Hello World!", "text/plain");
  3565. });
  3566. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3567. auto se = detail::scope_exit([&] {
  3568. svr.stop();
  3569. thread.join();
  3570. ASSERT_FALSE(svr.is_running());
  3571. });
  3572. svr.wait_until_ready();
  3573. {
  3574. Client cli("127.0.0.1", PORT);
  3575. auto res = cli.Get("/1");
  3576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3577. EXPECT_EQ(StatusCode::OK_200, res->status);
  3578. EXPECT_EQ("Hello World!", res->body);
  3579. }
  3580. {
  3581. Client cli("::1", PORT);
  3582. auto res = cli.Get("/1");
  3583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3584. EXPECT_EQ(StatusCode::OK_200, res->status);
  3585. EXPECT_EQ("Hello World!", res->body);
  3586. }
  3587. }
  3588. TEST(BindServerTest, BindAndListenSeparately) {
  3589. Server svr;
  3590. int port = svr.bind_to_any_port("0.0.0.0");
  3591. ASSERT_TRUE(svr.is_valid());
  3592. ASSERT_TRUE(port > 0);
  3593. svr.stop();
  3594. }
  3595. // Reports whether anything is still listening on a loopback port. A plain
  3596. // connect() is used instead of a Client request because a socket left bound by
  3597. // mistake accepts the connection into its backlog and never answers, which
  3598. // would hang the test instead of failing it.
  3599. static bool is_loopback_port_accepting(int port) {
  3600. sockaddr_in addr{};
  3601. addr.sin_family = AF_INET;
  3602. addr.sin_port = htons(static_cast<uint16_t>(port));
  3603. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3604. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3605. EXPECT_NE(sock, INVALID_SOCKET);
  3606. if (sock == INVALID_SOCKET) { return false; }
  3607. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3608. static_cast<socklen_t>(sizeof(addr)));
  3609. detail::close_socket(sock);
  3610. return ret == 0;
  3611. }
  3612. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3613. Server svr;
  3614. auto port = svr.bind_to_any_port("127.0.0.1");
  3615. ASSERT_TRUE(port > 0);
  3616. svr.stop();
  3617. // bind_to_any_port() already called listen(2), so until stop() closed the
  3618. // descriptor the port kept accepting connections into the backlog. ASSERT
  3619. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3620. // below blocks forever in the accept loop.
  3621. ASSERT_FALSE(is_loopback_port_accepting(port));
  3622. // Nothing is left to accept on, so listen_after_bind() must report failure
  3623. // instead of returning success without ever serving.
  3624. EXPECT_FALSE(svr.listen_after_bind());
  3625. // The failed listen marks the server decommissioned, so a waiter returns
  3626. // instead of spinning forever.
  3627. svr.wait_until_ready();
  3628. }
  3629. #ifdef CPPHTTPLIB_SSL_ENABLED
  3630. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3631. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3632. CLIENT_CA_CERT_DIR);
  3633. int port = svr.bind_to_any_port("0.0.0.0");
  3634. ASSERT_TRUE(svr.is_valid());
  3635. ASSERT_TRUE(port > 0);
  3636. svr.stop();
  3637. }
  3638. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3639. // or a rejected CustomRoute() registration would not stop the server binding.
  3640. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3642. CLIENT_CA_CERT_DIR);
  3643. ASSERT_TRUE(svr.is_valid());
  3644. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3645. EXPECT_FALSE(svr.is_valid());
  3646. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3647. }
  3648. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3649. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3650. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3651. int port = svr.bind_to_any_port("0.0.0.0");
  3652. ASSERT_TRUE(svr.is_valid());
  3653. ASSERT_TRUE(port > 0);
  3654. svr.stop();
  3655. }
  3656. TEST(BindServerTest, UpdateCertsPem) {
  3657. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3658. int port = svr.bind_to_any_port("0.0.0.0");
  3659. ASSERT_TRUE(svr.is_valid());
  3660. ASSERT_TRUE(port > 0);
  3661. // Read PEM files
  3662. std::string cert_pem, key_pem, ca_pem;
  3663. read_file(SERVER_CERT_FILE, cert_pem);
  3664. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3665. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3666. // Update server certificates using PEM API
  3667. ASSERT_TRUE(
  3668. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3669. ASSERT_TRUE(svr.is_valid());
  3670. svr.stop();
  3671. }
  3672. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3673. // Start server with client CA (enables client auth)
  3674. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3675. ASSERT_TRUE(svr.is_valid());
  3676. bool handler_called = false;
  3677. svr.Get("/test", [&](const Request &req, Response &res) {
  3678. handler_called = true;
  3679. // Verify client certificate is present
  3680. auto cert = req.peer_cert();
  3681. EXPECT_TRUE(static_cast<bool>(cert));
  3682. res.set_content("ok", "text/plain");
  3683. });
  3684. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3685. auto se = detail::scope_exit([&] {
  3686. svr.stop();
  3687. t.join();
  3688. ASSERT_FALSE(svr.is_running());
  3689. });
  3690. svr.wait_until_ready();
  3691. // Read PEM files
  3692. std::string cert_pem, key_pem, ca_pem;
  3693. read_file(SERVER_CERT_FILE, cert_pem);
  3694. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3695. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3696. // Update server certificates and client CA using PEM API while server running
  3697. ASSERT_TRUE(
  3698. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3699. // Connect with client certificate
  3700. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3701. cli.enable_server_certificate_verification(false);
  3702. cli.set_connection_timeout(30);
  3703. auto res = cli.Get("/test");
  3704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3705. ASSERT_EQ(StatusCode::OK_200, res->status);
  3706. ASSERT_TRUE(handler_called);
  3707. EXPECT_EQ("ok", res->body);
  3708. }
  3709. #endif
  3710. TEST(ErrorHandlerTest, ContentLength) {
  3711. Server svr;
  3712. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3713. res.status = StatusCode::OK_200;
  3714. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3715. "text/html"); // <= Content-Length still 13
  3716. });
  3717. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3718. res.set_content("Hello World!\n", "text/plain");
  3719. res.status = 524;
  3720. });
  3721. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3722. auto se = detail::scope_exit([&] {
  3723. svr.stop();
  3724. thread.join();
  3725. ASSERT_FALSE(svr.is_running());
  3726. });
  3727. svr.wait_until_ready();
  3728. {
  3729. Client cli(HOST, PORT);
  3730. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3732. EXPECT_EQ(StatusCode::OK_200, res->status);
  3733. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3734. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3735. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3736. }
  3737. }
  3738. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3739. TEST(ExceptionTest, WithoutExceptionHandler) {
  3740. Server svr;
  3741. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3742. throw std::runtime_error("exception...");
  3743. });
  3744. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3745. throw std::runtime_error("exception\r\n...");
  3746. });
  3747. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3748. auto se = detail::scope_exit([&] {
  3749. svr.stop();
  3750. listen_thread.join();
  3751. ASSERT_FALSE(svr.is_running());
  3752. });
  3753. svr.wait_until_ready();
  3754. Client cli("localhost", PORT);
  3755. {
  3756. auto res = cli.Get("/exception");
  3757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3758. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3759. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3760. }
  3761. {
  3762. auto res = cli.Get("/unknown");
  3763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3764. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3765. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3766. }
  3767. }
  3768. TEST(ExceptionTest, WithExceptionHandler) {
  3769. Server svr;
  3770. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3771. std::exception_ptr ep) {
  3772. EXPECT_FALSE(ep == nullptr);
  3773. try {
  3774. std::rethrow_exception(ep);
  3775. } catch (std::exception &e) {
  3776. EXPECT_EQ("abc", std::string(e.what()));
  3777. } catch (...) {}
  3778. res.status = StatusCode::InternalServerError_500;
  3779. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3780. "text/html"); // <= Content-Length still 13 at this point
  3781. });
  3782. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3783. res.set_content("Hello World!\n", "text/plain");
  3784. throw std::runtime_error("abc");
  3785. });
  3786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3787. auto se = detail::scope_exit([&] {
  3788. svr.stop();
  3789. thread.join();
  3790. ASSERT_FALSE(svr.is_running());
  3791. });
  3792. svr.wait_until_ready();
  3793. for (size_t i = 0; i < 10; i++) {
  3794. Client cli(HOST, PORT);
  3795. for (size_t j = 0; j < 100; j++) {
  3796. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3798. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3799. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3800. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3801. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3802. }
  3803. cli.set_keep_alive(true);
  3804. for (size_t j = 0; j < 100; j++) {
  3805. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3807. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3808. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3809. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3810. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3811. }
  3812. }
  3813. }
  3814. TEST(ExceptionTest, AndErrorHandler) {
  3815. Server svr;
  3816. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3817. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3818. });
  3819. svr.set_exception_handler(
  3820. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3821. EXPECT_FALSE(ep == nullptr);
  3822. try {
  3823. std::rethrow_exception(ep);
  3824. } catch (std::exception &e) {
  3825. res.set_content(e.what(), "text/html");
  3826. } catch (...) {}
  3827. res.status = StatusCode::InternalServerError_500;
  3828. });
  3829. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3830. throw std::runtime_error("EXCEPTION");
  3831. });
  3832. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3833. res.set_content("ERROR", "text/html");
  3834. res.status = StatusCode::InternalServerError_500;
  3835. });
  3836. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3837. auto se = detail::scope_exit([&] {
  3838. svr.stop();
  3839. thread.join();
  3840. ASSERT_FALSE(svr.is_running());
  3841. });
  3842. svr.wait_until_ready();
  3843. Client cli(HOST, PORT);
  3844. {
  3845. auto res = cli.Get("/exception");
  3846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3847. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3848. EXPECT_EQ("EXCEPTION", res->body);
  3849. }
  3850. {
  3851. auto res = cli.Get("/error");
  3852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3853. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3854. EXPECT_EQ("ERROR", res->body);
  3855. }
  3856. {
  3857. auto res = cli.Get("/invalid");
  3858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3860. EXPECT_EQ("NOT_FOUND", res->body);
  3861. }
  3862. }
  3863. #endif
  3864. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3865. // process_request() wraps only routing() in a try/catch, so an exception from
  3866. // any other user callback used to unwind into the task queue - which does not
  3867. // catch - and terminate the process. Each test below runs the server on a
  3868. // single worker thread: a guard that catches the exception but still loses the
  3869. // thread would otherwise be hidden by a spare worker serving the follow-up
  3870. // request. Note that a regression here aborts the whole test binary rather
  3871. // than failing one test.
  3872. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3873. Server svr;
  3874. svr.new_task_queue = [] { return new ThreadPool(1); };
  3875. std::atomic<int> reported{0};
  3876. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3877. if (err == Error::UserCallbackException) { reported++; }
  3878. });
  3879. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3880. res.set_content_provider(
  3881. 1024, "text/plain",
  3882. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3883. sink.write("hello", 5);
  3884. throw std::runtime_error("from the content provider");
  3885. });
  3886. });
  3887. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3888. res.set_content("ok", "text/plain");
  3889. });
  3890. auto port = svr.bind_to_any_port(HOST);
  3891. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3892. auto se = detail::scope_exit([&] {
  3893. svr.stop();
  3894. listen_thread.join();
  3895. ASSERT_FALSE(svr.is_running());
  3896. });
  3897. svr.wait_until_ready();
  3898. {
  3899. Client cli(HOST, port);
  3900. cli.set_read_timeout(5, 0);
  3901. EXPECT_FALSE(cli.Get("/throw"));
  3902. }
  3903. EXPECT_TRUE(svr.is_running());
  3904. EXPECT_EQ(1, reported.load());
  3905. // A request on a fresh connection is still served.
  3906. {
  3907. Client cli(HOST, port);
  3908. auto res = cli.Get("/ok");
  3909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3910. EXPECT_EQ(StatusCode::OK_200, res->status);
  3911. EXPECT_EQ("ok", res->body);
  3912. }
  3913. }
  3914. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3915. Server svr;
  3916. svr.new_task_queue = [] { return new ThreadPool(1); };
  3917. std::atomic<bool> should_throw{true};
  3918. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3919. res.set_content("hi", "text/plain");
  3920. });
  3921. svr.set_post_routing_handler(
  3922. [&](const Request & /*req*/, Response & /*res*/) {
  3923. if (should_throw) {
  3924. throw std::runtime_error("from the post-routing handler");
  3925. }
  3926. });
  3927. auto port = svr.bind_to_any_port(HOST);
  3928. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3929. auto se = detail::scope_exit([&] {
  3930. svr.stop();
  3931. listen_thread.join();
  3932. ASSERT_FALSE(svr.is_running());
  3933. });
  3934. svr.wait_until_ready();
  3935. {
  3936. Client cli(HOST, port);
  3937. cli.set_read_timeout(5, 0);
  3938. EXPECT_FALSE(cli.Get("/hi"));
  3939. }
  3940. EXPECT_TRUE(svr.is_running());
  3941. should_throw = false;
  3942. {
  3943. Client cli(HOST, port);
  3944. auto res = cli.Get("/hi");
  3945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3946. EXPECT_EQ(StatusCode::OK_200, res->status);
  3947. EXPECT_EQ("hi", res->body);
  3948. }
  3949. }
  3950. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3951. // The guard reports the caught exception through the error logger, which is
  3952. // a user callback too. A logger that throws has to be contained as well, or
  3953. // the process would terminate from inside the catch.
  3954. Server svr;
  3955. svr.new_task_queue = [] { return new ThreadPool(1); };
  3956. std::atomic<int> reported{0};
  3957. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3958. if (err == Error::UserCallbackException) {
  3959. reported++;
  3960. throw std::runtime_error("from the error logger");
  3961. }
  3962. });
  3963. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3964. res.set_content_provider(
  3965. 1024, "text/plain",
  3966. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3967. sink.write("hello", 5);
  3968. throw std::runtime_error("from the content provider");
  3969. });
  3970. });
  3971. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3972. res.set_content("ok", "text/plain");
  3973. });
  3974. auto port = svr.bind_to_any_port(HOST);
  3975. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3976. auto se = detail::scope_exit([&] {
  3977. svr.stop();
  3978. listen_thread.join();
  3979. ASSERT_FALSE(svr.is_running());
  3980. });
  3981. svr.wait_until_ready();
  3982. {
  3983. Client cli(HOST, port);
  3984. cli.set_read_timeout(5, 0);
  3985. EXPECT_FALSE(cli.Get("/throw"));
  3986. }
  3987. EXPECT_TRUE(svr.is_running());
  3988. EXPECT_EQ(1, reported.load());
  3989. {
  3990. Client cli(HOST, port);
  3991. auto res = cli.Get("/ok");
  3992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3993. EXPECT_EQ(StatusCode::OK_200, res->status);
  3994. EXPECT_EQ("ok", res->body);
  3995. }
  3996. }
  3997. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3998. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3999. // so the exception unwinds through the ws::WebSocket object on its way to
  4000. // the guard. None of the HTTP cases above cross that.
  4001. Server svr;
  4002. svr.new_task_queue = [] { return new ThreadPool(1); };
  4003. std::atomic<int> reported{0};
  4004. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4005. if (err == Error::UserCallbackException) { reported++; }
  4006. });
  4007. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4008. throw std::runtime_error("from the WebSocket handler");
  4009. });
  4010. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4011. res.set_content("ok", "text/plain");
  4012. });
  4013. auto port = svr.bind_to_any_port(HOST);
  4014. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4015. auto se = detail::scope_exit([&] {
  4016. svr.stop();
  4017. listen_thread.join();
  4018. ASSERT_FALSE(svr.is_running());
  4019. });
  4020. svr.wait_until_ready();
  4021. {
  4022. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4023. "/ws");
  4024. auto res = client.connect();
  4025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4026. // The server dropped the connection instead of dying.
  4027. std::string msg;
  4028. EXPECT_FALSE(client.read(msg));
  4029. client.close();
  4030. }
  4031. EXPECT_TRUE(svr.is_running());
  4032. EXPECT_EQ(1, reported.load());
  4033. {
  4034. Client cli(HOST, port);
  4035. auto res = cli.Get("/ok");
  4036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4037. EXPECT_EQ(StatusCode::OK_200, res->status);
  4038. EXPECT_EQ("ok", res->body);
  4039. }
  4040. }
  4041. #ifdef CPPHTTPLIB_SSL_ENABLED
  4042. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4043. // SSLServer::process_and_close_socket() is a separate overload with its own
  4044. // guard, so it is exercised on its own.
  4045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4046. ASSERT_TRUE(svr.is_valid());
  4047. svr.new_task_queue = [] { return new ThreadPool(1); };
  4048. std::atomic<int> reported{0};
  4049. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4050. if (err == Error::UserCallbackException) { reported++; }
  4051. });
  4052. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4053. res.set_content_provider(
  4054. 1024, "text/plain",
  4055. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4056. sink.write("hello", 5);
  4057. throw std::runtime_error("from the content provider");
  4058. });
  4059. });
  4060. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4061. res.set_content("ok", "text/plain");
  4062. });
  4063. auto port = svr.bind_to_any_port(HOST);
  4064. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4065. auto se = detail::scope_exit([&] {
  4066. svr.stop();
  4067. listen_thread.join();
  4068. ASSERT_FALSE(svr.is_running());
  4069. });
  4070. svr.wait_until_ready();
  4071. {
  4072. SSLClient cli(HOST, port);
  4073. cli.enable_server_certificate_verification(false);
  4074. cli.set_read_timeout(5, 0);
  4075. EXPECT_FALSE(cli.Get("/throw"));
  4076. }
  4077. EXPECT_TRUE(svr.is_running());
  4078. EXPECT_EQ(1, reported.load());
  4079. {
  4080. SSLClient cli(HOST, port);
  4081. cli.enable_server_certificate_verification(false);
  4082. auto res = cli.Get("/ok");
  4083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4084. EXPECT_EQ(StatusCode::OK_200, res->status);
  4085. EXPECT_EQ("ok", res->body);
  4086. }
  4087. }
  4088. #endif
  4089. #endif
  4090. TEST(NoContentTest, ContentLength) {
  4091. Server svr;
  4092. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4093. res.status = StatusCode::NoContent_204;
  4094. });
  4095. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4096. auto se = detail::scope_exit([&] {
  4097. svr.stop();
  4098. thread.join();
  4099. ASSERT_FALSE(svr.is_running());
  4100. });
  4101. svr.wait_until_ready();
  4102. {
  4103. Client cli(HOST, PORT);
  4104. auto res = cli.Get("/hi");
  4105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4106. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4107. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4108. }
  4109. }
  4110. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4111. #ifdef CPPHTTPLIB_SSL_ENABLED
  4112. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4113. ASSERT_TRUE(svr.is_valid());
  4114. #else
  4115. Server svr;
  4116. #endif
  4117. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4118. if (req.path == "/routing_handler") {
  4119. res.set_header("PRE_ROUTING", "on");
  4120. res.set_content("Routing Handler", "text/plain");
  4121. return httplib::Server::HandlerResponse::Handled;
  4122. }
  4123. return httplib::Server::HandlerResponse::Unhandled;
  4124. });
  4125. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4126. res.set_content("Error", "text/html");
  4127. });
  4128. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4129. if (req.path == "/routing_handler") {
  4130. res.set_header("POST_ROUTING", "on");
  4131. }
  4132. });
  4133. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4134. res.set_content("Hello World!\n", "text/plain");
  4135. });
  4136. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4137. auto se = detail::scope_exit([&] {
  4138. svr.stop();
  4139. thread.join();
  4140. ASSERT_FALSE(svr.is_running());
  4141. });
  4142. svr.wait_until_ready();
  4143. {
  4144. #ifdef CPPHTTPLIB_SSL_ENABLED
  4145. SSLClient cli(HOST, PORT);
  4146. cli.enable_server_certificate_verification(false);
  4147. #else
  4148. Client cli(HOST, PORT);
  4149. #endif
  4150. auto res = cli.Get("/routing_handler");
  4151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4152. EXPECT_EQ(StatusCode::OK_200, res->status);
  4153. EXPECT_EQ("Routing Handler", res->body);
  4154. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4155. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4156. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4157. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4158. }
  4159. {
  4160. #ifdef CPPHTTPLIB_SSL_ENABLED
  4161. SSLClient cli(HOST, PORT);
  4162. cli.enable_server_certificate_verification(false);
  4163. #else
  4164. Client cli(HOST, PORT);
  4165. #endif
  4166. auto res = cli.Get("/hi");
  4167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4168. EXPECT_EQ(StatusCode::OK_200, res->status);
  4169. EXPECT_EQ("Hello World!\n", res->body);
  4170. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4171. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4172. }
  4173. {
  4174. #ifdef CPPHTTPLIB_SSL_ENABLED
  4175. SSLClient cli(HOST, PORT);
  4176. cli.enable_server_certificate_verification(false);
  4177. #else
  4178. Client cli(HOST, PORT);
  4179. #endif
  4180. auto res = cli.Get("/aaa");
  4181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4182. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4183. EXPECT_EQ("Error", res->body);
  4184. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4185. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4186. }
  4187. }
  4188. TEST(RequestHandlerTest, PreRequestHandler) {
  4189. auto route_path = "/user/:user";
  4190. Server svr;
  4191. svr.Get("/hi", [](const Request &, Response &res) {
  4192. res.set_content("hi", "text/plain");
  4193. });
  4194. svr.Get(route_path, [](const Request &req, Response &res) {
  4195. res.set_content(req.path_params.at("user"), "text/plain");
  4196. });
  4197. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4198. if (req.matched_route == route_path) {
  4199. auto user = req.path_params.at("user");
  4200. if (user != "john") {
  4201. res.status = StatusCode::Forbidden_403;
  4202. res.set_content("error", "text/html");
  4203. return Server::HandlerResponse::Handled;
  4204. }
  4205. }
  4206. return Server::HandlerResponse::Unhandled;
  4207. });
  4208. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4209. auto se = detail::scope_exit([&] {
  4210. svr.stop();
  4211. thread.join();
  4212. ASSERT_FALSE(svr.is_running());
  4213. });
  4214. svr.wait_until_ready();
  4215. Client cli(HOST, PORT);
  4216. {
  4217. auto res = cli.Get("/hi");
  4218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4219. EXPECT_EQ(StatusCode::OK_200, res->status);
  4220. EXPECT_EQ("hi", res->body);
  4221. }
  4222. {
  4223. auto res = cli.Get("/user/john");
  4224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4225. EXPECT_EQ(StatusCode::OK_200, res->status);
  4226. EXPECT_EQ("john", res->body);
  4227. }
  4228. {
  4229. auto res = cli.Get("/user/invalid-user");
  4230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4231. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4232. EXPECT_EQ("error", res->body);
  4233. }
  4234. }
  4235. // The pre-request handler must run before the request body is read, so a
  4236. // rejected request never forces the server to buffer a (potentially large)
  4237. // body. Here the posted body is larger than the payload limit: if the body
  4238. // were read first the server would answer 413, but because the pre-request
  4239. // handler runs first it answers 403 and the body is never read.
  4240. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4241. Server svr;
  4242. svr.set_payload_max_length(8);
  4243. auto handler_ran = false;
  4244. svr.Post("/reject", [&](const Request &req, Response &res) {
  4245. handler_ran = true;
  4246. res.set_content(req.body, "text/plain");
  4247. });
  4248. svr.Post("/accept", [](const Request &req, Response &res) {
  4249. res.set_content(req.body, "text/plain");
  4250. });
  4251. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4252. if (req.matched_route == "/reject") {
  4253. res.status = StatusCode::Forbidden_403;
  4254. res.set_content("denied", "text/plain");
  4255. return Server::HandlerResponse::Handled;
  4256. }
  4257. return Server::HandlerResponse::Unhandled;
  4258. });
  4259. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4260. auto se = detail::scope_exit([&] {
  4261. svr.stop();
  4262. thread.join();
  4263. ASSERT_FALSE(svr.is_running());
  4264. });
  4265. svr.wait_until_ready();
  4266. Client cli(HOST, PORT);
  4267. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4268. // rejects with 403 before the body is read, so 413 is never reached.
  4269. {
  4270. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4272. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4273. EXPECT_EQ("denied", res->body);
  4274. EXPECT_FALSE(handler_ran);
  4275. }
  4276. // An approved route still reads the body and enforces the payload limit.
  4277. {
  4278. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4280. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4281. }
  4282. }
  4283. TEST(UserDataTest, BasicOperations) {
  4284. httplib::UserData ud;
  4285. // Initially empty
  4286. EXPECT_FALSE(ud.has("key"));
  4287. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4288. // set and get
  4289. ud.set("key", 42);
  4290. EXPECT_TRUE(ud.has("key"));
  4291. auto *p = ud.get<int>("key");
  4292. ASSERT_NE(nullptr, p);
  4293. EXPECT_EQ(42, *p);
  4294. // Type mismatch → nullptr
  4295. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4296. // Overwrite with different type
  4297. ud.set("key", std::string("hello"));
  4298. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4299. auto *s = ud.get<std::string>("key");
  4300. ASSERT_NE(nullptr, s);
  4301. EXPECT_EQ("hello", *s);
  4302. // erase
  4303. ud.erase("key");
  4304. EXPECT_FALSE(ud.has("key"));
  4305. // clear
  4306. ud.set("a", 1);
  4307. ud.set("b", 2);
  4308. ud.clear();
  4309. EXPECT_FALSE(ud.has("a"));
  4310. EXPECT_FALSE(ud.has("b"));
  4311. }
  4312. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4313. struct AuthCtx {
  4314. std::string user_id;
  4315. };
  4316. Server svr;
  4317. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4318. res.user_data.set("auth", AuthCtx{"alice"});
  4319. return Server::HandlerResponse::Unhandled;
  4320. });
  4321. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4322. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4323. ASSERT_NE(nullptr, ctx);
  4324. res.set_content("Hello " + ctx->user_id, "text/plain");
  4325. });
  4326. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4327. auto se = detail::scope_exit([&] {
  4328. svr.stop();
  4329. thread.join();
  4330. ASSERT_FALSE(svr.is_running());
  4331. });
  4332. svr.wait_until_ready();
  4333. Client cli(HOST, PORT);
  4334. auto res = cli.Get("/me");
  4335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4336. EXPECT_EQ(StatusCode::OK_200, res->status);
  4337. EXPECT_EQ("Hello alice", res->body);
  4338. }
  4339. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4340. struct RoleCtx {
  4341. std::string role;
  4342. };
  4343. Server svr;
  4344. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4345. res.user_data.set("role", RoleCtx{"admin"});
  4346. return Server::HandlerResponse::Unhandled;
  4347. });
  4348. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4349. auto *ctx = res.user_data.get<RoleCtx>("role");
  4350. ASSERT_NE(nullptr, ctx);
  4351. res.set_content(ctx->role, "text/plain");
  4352. });
  4353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4354. auto se = detail::scope_exit([&] {
  4355. svr.stop();
  4356. thread.join();
  4357. ASSERT_FALSE(svr.is_running());
  4358. });
  4359. svr.wait_until_ready();
  4360. Client cli(HOST, PORT);
  4361. auto res = cli.Get("/role");
  4362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4363. EXPECT_EQ(StatusCode::OK_200, res->status);
  4364. EXPECT_EQ("admin", res->body);
  4365. }
  4366. TEST(InvalidFormatTest, StatusCode) {
  4367. Server svr;
  4368. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4369. res.set_content("Hello World!\n", "text/plain");
  4370. res.status = 9999; // Status should be a three-digit code...
  4371. });
  4372. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4373. auto se = detail::scope_exit([&] {
  4374. svr.stop();
  4375. thread.join();
  4376. ASSERT_FALSE(svr.is_running());
  4377. });
  4378. svr.wait_until_ready();
  4379. {
  4380. Client cli(HOST, PORT);
  4381. auto res = cli.Get("/hi");
  4382. ASSERT_FALSE(res);
  4383. }
  4384. }
  4385. TEST(URLFragmentTest, WithFragment) {
  4386. Server svr;
  4387. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4388. EXPECT_TRUE(req.target == "/hi");
  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. {
  4398. Client cli(HOST, PORT);
  4399. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4400. EXPECT_TRUE(res);
  4401. EXPECT_EQ(StatusCode::OK_200, res->status);
  4402. res = cli.Get("/hi%23key1=val1=key2=val2");
  4403. EXPECT_TRUE(res);
  4404. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4405. }
  4406. }
  4407. TEST(HeaderWriter, SetHeaderWriter) {
  4408. Server svr;
  4409. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4410. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4411. return detail::write_headers(strm, hdrs);
  4412. });
  4413. svr.Get("/hi", [](const Request &req, Response &res) {
  4414. auto it = req.headers.find("CustomClientHeader");
  4415. EXPECT_TRUE(it != req.headers.end());
  4416. EXPECT_EQ(it->second, "CustomClientValue");
  4417. res.set_content("Hello World!\n", "text/plain");
  4418. });
  4419. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4420. auto se = detail::scope_exit([&] {
  4421. svr.stop();
  4422. thread.join();
  4423. ASSERT_FALSE(svr.is_running());
  4424. });
  4425. svr.wait_until_ready();
  4426. {
  4427. Client cli(HOST, PORT);
  4428. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4429. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4430. return detail::write_headers(strm, hdrs);
  4431. });
  4432. auto res = cli.Get("/hi");
  4433. EXPECT_TRUE(res);
  4434. EXPECT_EQ(StatusCode::OK_200, res->status);
  4435. auto it = res->headers.find("CustomServerHeader");
  4436. EXPECT_TRUE(it != res->headers.end());
  4437. EXPECT_EQ(it->second, "CustomServerValue");
  4438. }
  4439. }
  4440. class ServerTest : public ::testing::Test {
  4441. protected:
  4442. ServerTest()
  4443. : cli_(HOST, PORT)
  4444. #ifdef CPPHTTPLIB_SSL_ENABLED
  4445. ,
  4446. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4447. #endif
  4448. {
  4449. #ifdef CPPHTTPLIB_SSL_ENABLED
  4450. cli_.enable_server_certificate_verification(false);
  4451. #endif
  4452. // Allow LARGE_DATA (100MB) responses
  4453. cli_.set_payload_max_length(200 * 1024 * 1024);
  4454. }
  4455. virtual void SetUp() {
  4456. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4457. svr_.set_payload_max_length(200 * 1024 * 1024);
  4458. svr_.set_mount_point("/", "./www");
  4459. svr_.set_mount_point("/mount", "./www2");
  4460. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4461. svr_.Get("/hi",
  4462. [&](const Request & /*req*/, Response &res) {
  4463. res.set_content("Hello World!", "text/plain");
  4464. })
  4465. .Get("/file_content",
  4466. [&](const Request & /*req*/, Response &res) {
  4467. res.set_file_content("./www/dir/test.html");
  4468. })
  4469. .Get("/file_content_with_content_type",
  4470. [&](const Request & /*req*/, Response &res) {
  4471. res.set_file_content("./www/file", "text/plain");
  4472. })
  4473. .Get("/invalid_file_content",
  4474. [&](const Request & /*req*/, Response &res) {
  4475. res.set_file_content("./www/dir/invalid_file_path");
  4476. })
  4477. .Get("/http_response_splitting",
  4478. [&](const Request & /*req*/, Response &res) {
  4479. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4480. EXPECT_EQ(0U, res.headers.size());
  4481. EXPECT_FALSE(res.has_header("a"));
  4482. res.set_header("a", "1\nSet-Cookie: a=1");
  4483. EXPECT_EQ(0U, res.headers.size());
  4484. EXPECT_FALSE(res.has_header("a"));
  4485. res.set_header("a", "1\rSet-Cookie: a=1");
  4486. EXPECT_EQ(0U, res.headers.size());
  4487. EXPECT_FALSE(res.has_header("a"));
  4488. res.set_header("a\r\nb", "0");
  4489. EXPECT_EQ(0U, res.headers.size());
  4490. EXPECT_FALSE(res.has_header("a"));
  4491. res.set_header("a\rb", "0");
  4492. EXPECT_EQ(0U, res.headers.size());
  4493. EXPECT_FALSE(res.has_header("a"));
  4494. res.set_header("a\nb", "0");
  4495. EXPECT_EQ(0U, res.headers.size());
  4496. EXPECT_FALSE(res.has_header("a"));
  4497. res.set_redirect("1\r\nSet-Cookie: a=1");
  4498. EXPECT_EQ(0U, res.headers.size());
  4499. EXPECT_FALSE(res.has_header("Location"));
  4500. })
  4501. .Get("/slow",
  4502. [&](const Request & /*req*/, Response &res) {
  4503. std::this_thread::sleep_for(std::chrono::seconds(4));
  4504. res.set_content("slow", "text/plain");
  4505. })
  4506. #if 0
  4507. .Post("/slowpost",
  4508. [&](const Request & /*req*/, Response &res) {
  4509. std::this_thread::sleep_for(std::chrono::seconds(2));
  4510. res.set_content("slow", "text/plain");
  4511. })
  4512. #endif
  4513. .Get("/remote_addr",
  4514. [&](const Request &req, Response &res) {
  4515. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4516. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4517. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4518. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4519. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4520. #endif
  4521. res.set_content(req.remote_addr, "text/plain");
  4522. })
  4523. .Get("/local_addr",
  4524. [&](const Request &req, Response &res) {
  4525. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4526. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4527. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4528. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4529. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4530. #endif
  4531. auto local_addr = req.local_addr;
  4532. auto local_port = std::to_string(req.local_port);
  4533. res.set_content(local_addr.append(":").append(local_port),
  4534. "text/plain");
  4535. })
  4536. .Get("/endwith%",
  4537. [&](const Request & /*req*/, Response &res) {
  4538. res.set_content("Hello World!", "text/plain");
  4539. })
  4540. .Get("/a\\+\\+b",
  4541. [&](const Request &req, Response &res) {
  4542. ASSERT_TRUE(req.has_param("a +b"));
  4543. auto val = req.get_param_value("a +b");
  4544. res.set_content(val, "text/plain");
  4545. })
  4546. .Get("/", [&](const Request & /*req*/,
  4547. Response &res) { res.set_redirect("/hi"); })
  4548. .Post("/1",
  4549. [](const Request & /*req*/, Response &res) {
  4550. res.set_redirect("/2", StatusCode::SeeOther_303);
  4551. })
  4552. .Get("/2",
  4553. [](const Request & /*req*/, Response &res) {
  4554. res.set_content("redirected.", "text/plain");
  4555. res.status = StatusCode::OK_200;
  4556. })
  4557. .Post("/person",
  4558. [&](const Request &req, Response &res) {
  4559. if (req.has_param("name") && req.has_param("note")) {
  4560. persons_[req.get_param_value("name")] =
  4561. req.get_param_value("note");
  4562. } else {
  4563. res.status = StatusCode::BadRequest_400;
  4564. }
  4565. })
  4566. .Put("/person",
  4567. [&](const Request &req, Response &res) {
  4568. if (req.has_param("name") && req.has_param("note")) {
  4569. persons_[req.get_param_value("name")] =
  4570. req.get_param_value("note");
  4571. } else {
  4572. res.status = StatusCode::BadRequest_400;
  4573. }
  4574. })
  4575. .Get("/person/(.*)",
  4576. [&](const Request &req, Response &res) {
  4577. string name = req.matches[1];
  4578. if (persons_.find(name) != persons_.end()) {
  4579. auto note = persons_[name];
  4580. res.set_content(note, "text/plain");
  4581. } else {
  4582. res.status = StatusCode::NotFound_404;
  4583. }
  4584. })
  4585. .Delete("/person",
  4586. [&](const Request &req, Response &res) {
  4587. if (req.has_param("name")) {
  4588. string name = req.get_param_value("name");
  4589. if (persons_.find(name) != persons_.end()) {
  4590. persons_.erase(name);
  4591. res.set_content("DELETED", "text/plain");
  4592. } else {
  4593. res.status = StatusCode::NotFound_404;
  4594. }
  4595. } else {
  4596. res.status = StatusCode::BadRequest_400;
  4597. }
  4598. })
  4599. .Post("/x-www-form-urlencoded-json",
  4600. [&](const Request &req, Response &res) {
  4601. auto json = req.get_param_value("json");
  4602. ASSERT_EQ(JSON_DATA, json);
  4603. res.set_content(json, "appliation/json");
  4604. res.status = StatusCode::OK_200;
  4605. })
  4606. .Get("/streamed-chunked",
  4607. [&](const Request & /*req*/, Response &res) {
  4608. res.set_chunked_content_provider(
  4609. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4610. sink.os << "123";
  4611. sink.os << "456";
  4612. sink.os << "789";
  4613. sink.done();
  4614. return true;
  4615. });
  4616. })
  4617. .Get("/streamed-chunked-with-prohibited-trailer",
  4618. [&](const Request & /*req*/, Response &res) {
  4619. auto i = new int(0);
  4620. // Declare both a prohibited trailer (Content-Length) and an
  4621. // allowed one
  4622. res.set_header("Trailer", "Content-Length, X-Allowed");
  4623. res.set_chunked_content_provider(
  4624. "text/plain",
  4625. [i](size_t /*offset*/, DataSink &sink) {
  4626. switch (*i) {
  4627. case 0: sink.os << "123"; break;
  4628. case 1: sink.os << "456"; break;
  4629. case 2: sink.os << "789"; break;
  4630. case 3: {
  4631. sink.done_with_trailer(
  4632. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4633. } break;
  4634. }
  4635. (*i)++;
  4636. return true;
  4637. },
  4638. [i](bool success) {
  4639. EXPECT_TRUE(success);
  4640. delete i;
  4641. });
  4642. })
  4643. .Get("/streamed-chunked2",
  4644. [&](const Request & /*req*/, Response &res) {
  4645. auto i = new int(0);
  4646. res.set_chunked_content_provider(
  4647. "text/plain",
  4648. [i](size_t /*offset*/, DataSink &sink) {
  4649. switch (*i) {
  4650. case 0: sink.os << "123"; break;
  4651. case 1: sink.os << "456"; break;
  4652. case 2: sink.os << "789"; break;
  4653. case 3: sink.done(); break;
  4654. }
  4655. (*i)++;
  4656. return true;
  4657. },
  4658. [i](bool success) {
  4659. EXPECT_TRUE(success);
  4660. delete i;
  4661. });
  4662. })
  4663. .Get("/streamed-chunked-with-trailer",
  4664. [&](const Request & /*req*/, Response &res) {
  4665. auto i = new int(0);
  4666. res.set_header("Trailer", "Dummy1, Dummy2");
  4667. res.set_chunked_content_provider(
  4668. "text/plain",
  4669. [i](size_t /*offset*/, DataSink &sink) {
  4670. switch (*i) {
  4671. case 0: sink.os << "123"; break;
  4672. case 1: sink.os << "456"; break;
  4673. case 2: sink.os << "789"; break;
  4674. case 3: {
  4675. sink.done_with_trailer(
  4676. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4677. } break;
  4678. }
  4679. (*i)++;
  4680. return true;
  4681. },
  4682. [i](bool success) {
  4683. EXPECT_TRUE(success);
  4684. delete i;
  4685. });
  4686. })
  4687. .Get("/streamed",
  4688. [&](const Request & /*req*/, Response &res) {
  4689. res.set_content_provider(
  4690. 6, "text/plain",
  4691. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4692. sink.os << (offset < 3 ? "a" : "b");
  4693. return true;
  4694. });
  4695. })
  4696. .Get("/streamed-without-length",
  4697. [&](const Request & /*req*/, Response &res) {
  4698. auto data = new std::string("abcdefg");
  4699. res.set_content_provider(
  4700. "text/plain",
  4701. [data](size_t offset, DataSink &sink) {
  4702. if (offset < data->size()) {
  4703. sink.os << data->substr(offset);
  4704. }
  4705. sink.done();
  4706. return true;
  4707. },
  4708. [data](bool success) {
  4709. EXPECT_TRUE(success);
  4710. delete data;
  4711. });
  4712. })
  4713. .Get("/streamed-with-range",
  4714. [&](const Request &req, Response &res) {
  4715. auto data = new std::string("abcdefg");
  4716. // An explicit status keeps the server from picking the 206 it
  4717. // would otherwise choose for a ranged request, so the response
  4718. // is not a partial representation.
  4719. auto status = req.get_param_value("status");
  4720. if (status == "200") {
  4721. res.status = StatusCode::OK_200;
  4722. } else if (status == "403") {
  4723. res.status = StatusCode::Forbidden_403;
  4724. }
  4725. res.set_content_provider(
  4726. data->size(), "text/plain",
  4727. [data](size_t offset, size_t length, DataSink &sink) {
  4728. size_t DATA_CHUNK_SIZE = 4;
  4729. const auto &d = *data;
  4730. auto out_len =
  4731. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4732. auto ret =
  4733. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4734. EXPECT_TRUE(ret);
  4735. return true;
  4736. },
  4737. [data, &req](bool success) {
  4738. EXPECT_EQ(success, !req.has_param("error"));
  4739. delete data;
  4740. });
  4741. })
  4742. .Get("/streamed-cancel",
  4743. [&](const Request & /*req*/, Response &res) {
  4744. res.set_content_provider(
  4745. size_t(-1), "text/plain",
  4746. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4747. sink.os << "data_chunk";
  4748. return true;
  4749. });
  4750. })
  4751. .Get("/regex-with-delimiter",
  4752. [&](const Request &req, Response & /*res*/) {
  4753. ASSERT_TRUE(req.has_param("key"));
  4754. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4755. })
  4756. .Get("/with-range",
  4757. [&](const Request & /*req*/, Response &res) {
  4758. res.set_content("abcdefg", "text/plain");
  4759. })
  4760. .Get("/test-start-time",
  4761. [&](const Request &req, Response & /*res*/) {
  4762. EXPECT_NE(req.start_time_,
  4763. std::chrono::steady_clock::time_point::min());
  4764. })
  4765. .Get("/with-range-customized-response",
  4766. [&](const Request & /*req*/, Response &res) {
  4767. res.status = StatusCode::BadRequest_400;
  4768. res.set_content(JSON_DATA, "application/json");
  4769. })
  4770. .Post("/chunked",
  4771. [&](const Request &req, Response & /*res*/) {
  4772. EXPECT_EQ(req.body, "dechunked post body");
  4773. })
  4774. .Post("/large-chunked",
  4775. [&](const Request &req, Response & /*res*/) {
  4776. std::string expected(6 * 30 * 1024u, 'a');
  4777. EXPECT_EQ(req.body, expected);
  4778. })
  4779. .Post("/multipart",
  4780. [&](const Request &req, Response & /*res*/) {
  4781. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4782. req.form.get_field_count("text2") +
  4783. req.form.get_field_count("file3") +
  4784. req.form.get_field_count("file4"));
  4785. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4786. req.form.get_file_count("file2"));
  4787. ASSERT_TRUE(!req.form.has_file("???"));
  4788. ASSERT_TRUE(!req.form.has_field("???"));
  4789. ASSERT_TRUE(req.body.empty());
  4790. {
  4791. const auto &text = req.form.get_field("text1");
  4792. EXPECT_EQ("text default", text);
  4793. }
  4794. {
  4795. const auto &text = req.form.get_field("text2");
  4796. EXPECT_EQ("aωb", text);
  4797. }
  4798. {
  4799. const auto &file = req.form.get_file("file1");
  4800. EXPECT_EQ("hello.txt", file.filename);
  4801. EXPECT_EQ("text/plain", file.content_type);
  4802. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4803. }
  4804. {
  4805. const auto &file = req.form.get_file("file2");
  4806. EXPECT_EQ("world.json", file.filename);
  4807. EXPECT_EQ("application/json", file.content_type);
  4808. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4809. }
  4810. {
  4811. const auto &text = req.form.get_field("file3");
  4812. EXPECT_EQ(0u, text.size());
  4813. }
  4814. {
  4815. const auto &text = req.form.get_field("file4");
  4816. EXPECT_EQ(0u, text.size());
  4817. }
  4818. })
  4819. .Post("/multipart/multi_file_values",
  4820. [&](const Request &req, Response & /*res*/) {
  4821. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4822. req.form.get_field_count("multi_text1"));
  4823. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4824. ASSERT_TRUE(!req.form.has_file("???"));
  4825. ASSERT_TRUE(!req.form.has_field("???"));
  4826. ASSERT_TRUE(req.body.empty());
  4827. {
  4828. const auto &text = req.form.get_field("text");
  4829. EXPECT_EQ("default text", text);
  4830. }
  4831. {
  4832. const auto &text1_values = req.form.get_fields("multi_text1");
  4833. EXPECT_EQ(2u, text1_values.size());
  4834. EXPECT_EQ("aaaaa", text1_values[0]);
  4835. EXPECT_EQ("bbbbb", text1_values[1]);
  4836. }
  4837. {
  4838. const auto &file1_values = req.form.get_files("multi_file1");
  4839. EXPECT_EQ(2u, file1_values.size());
  4840. auto file1 = file1_values[0];
  4841. EXPECT_EQ(file1.filename, "hello.txt");
  4842. EXPECT_EQ(file1.content_type, "text/plain");
  4843. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4844. auto file2 = file1_values[1];
  4845. EXPECT_EQ(file2.filename, "world.json");
  4846. EXPECT_EQ(file2.content_type, "application/json");
  4847. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4848. }
  4849. })
  4850. .Post("/empty",
  4851. [&](const Request &req, Response &res) {
  4852. EXPECT_EQ(req.body, "");
  4853. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4854. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4855. res.set_content("empty", "text/plain");
  4856. })
  4857. .Post("/empty-no-content-type",
  4858. [&](const Request &req, Response &res) {
  4859. EXPECT_EQ(req.body, "");
  4860. EXPECT_FALSE(req.has_header("Content-Type"));
  4861. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4862. res.set_content("empty-no-content-type", "text/plain");
  4863. })
  4864. .Post("/path-only",
  4865. [&](const Request &req, Response &res) {
  4866. EXPECT_EQ(req.body, "");
  4867. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4868. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4869. res.set_content("path-only", "text/plain");
  4870. })
  4871. .Post("/path-headers-only",
  4872. [&](const Request &req, Response &res) {
  4873. EXPECT_EQ(req.body, "");
  4874. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4875. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4876. EXPECT_EQ("world", req.get_header_value("hello"));
  4877. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4878. res.set_content("path-headers-only", "text/plain");
  4879. })
  4880. .Post("/post-large",
  4881. [&](const Request &req, Response &res) {
  4882. EXPECT_EQ(req.body, LARGE_DATA);
  4883. res.set_content(req.body, "text/plain");
  4884. })
  4885. .Post("/post-loopback",
  4886. [&](const Request &, Response &res,
  4887. ContentReader const &content_reader) {
  4888. std::string body;
  4889. content_reader([&](const char *data, size_t data_length) {
  4890. body.append(data, data_length);
  4891. return true;
  4892. });
  4893. res.set_content(body, "text/plain");
  4894. })
  4895. .Put("/put-loopback",
  4896. [&](const Request &, Response &res,
  4897. ContentReader const &content_reader) {
  4898. std::string body;
  4899. content_reader([&](const char *data, size_t data_length) {
  4900. body.append(data, data_length);
  4901. return true;
  4902. });
  4903. res.set_content(body, "text/plain");
  4904. })
  4905. .Patch("/patch-loopback",
  4906. [&](const Request &, Response &res,
  4907. ContentReader const &content_reader) {
  4908. std::string body;
  4909. content_reader([&](const char *data, size_t data_length) {
  4910. body.append(data, data_length);
  4911. return true;
  4912. });
  4913. res.set_content(body, "text/plain");
  4914. })
  4915. .Put("/empty-no-content-type",
  4916. [&](const Request &req, Response &res) {
  4917. EXPECT_EQ(req.body, "");
  4918. EXPECT_FALSE(req.has_header("Content-Type"));
  4919. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4920. res.set_content("empty-no-content-type", "text/plain");
  4921. })
  4922. .Put("/put",
  4923. [&](const Request &req, Response &res) {
  4924. EXPECT_EQ(req.body, "PUT");
  4925. res.set_content(req.body, "text/plain");
  4926. })
  4927. .Put("/put-large",
  4928. [&](const Request &req, Response &res) {
  4929. EXPECT_EQ(req.body, LARGE_DATA);
  4930. res.set_content(req.body, "text/plain");
  4931. })
  4932. .Patch("/patch",
  4933. [&](const Request &req, Response &res) {
  4934. EXPECT_EQ(req.body, "PATCH");
  4935. res.set_content(req.body, "text/plain");
  4936. })
  4937. .Delete("/delete",
  4938. [&](const Request & /*req*/, Response &res) {
  4939. res.set_content("DELETE", "text/plain");
  4940. })
  4941. .Delete("/delete-body",
  4942. [&](const Request &req, Response &res) {
  4943. EXPECT_EQ(req.body, "content");
  4944. res.set_content(req.body, "text/plain");
  4945. })
  4946. .Options(R"(\*)",
  4947. [&](const Request & /*req*/, Response &res) {
  4948. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4949. })
  4950. .CustomRoute("PROPFIND", "/dav/:id",
  4951. [&](const Request &req, Response &res) {
  4952. res.set_header("x-body-size",
  4953. std::to_string(req.body.size()));
  4954. res.set_header("x-matched-route", req.matched_route);
  4955. res.set_header("x-dav-id", req.path_params.at("id"));
  4956. res.status = StatusCode::MultiStatus_207;
  4957. res.set_content(req.body, "application/xml");
  4958. })
  4959. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4960. [&](const Request &req, Response &res) {
  4961. res.set_header("x-dav-match", req.matches[1]);
  4962. res.status = StatusCode::MultiStatus_207;
  4963. })
  4964. .CustomRoute("MKCOL", "/dav-mkcol",
  4965. [&](const Request &req, Response &res) {
  4966. EXPECT_TRUE(req.body.empty());
  4967. res.status = StatusCode::Created_201;
  4968. })
  4969. .CustomRoute(
  4970. "REPORT", "/dav-report",
  4971. [&](const Request & /*req*/, Response &res,
  4972. const ContentReader &content_reader) {
  4973. std::string body;
  4974. content_reader([&](const char *data, size_t data_length) {
  4975. body.append(data, data_length);
  4976. return true;
  4977. });
  4978. res.set_header("x-body-size", std::to_string(body.size()));
  4979. res.status = StatusCode::MultiStatus_207;
  4980. res.set_content(body, "application/xml");
  4981. })
  4982. .Get("/request-target",
  4983. [&](const Request &req, Response & /*res*/) {
  4984. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4985. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4986. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4987. })
  4988. .Get("/long-query-value",
  4989. [&](const Request &req, Response & /*res*/) {
  4990. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4991. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4992. })
  4993. .Get("/too-long-query-value",
  4994. [&](const Request &req, Response & /*res*/) {
  4995. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4996. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4997. })
  4998. .Get("/array-param",
  4999. [&](const Request &req, Response & /*res*/) {
  5000. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5001. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5002. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5003. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5004. })
  5005. .Get("/array-param-values",
  5006. [&](const Request &req, Response & /*res*/) {
  5007. auto values = req.get_param_values("array");
  5008. EXPECT_EQ(3u, values.size());
  5009. EXPECT_EQ("value1", values[0]);
  5010. EXPECT_EQ("value2", values[1]);
  5011. EXPECT_EQ("value3", values[2]);
  5012. auto empty = req.get_param_values("nonexistent");
  5013. EXPECT_TRUE(empty.empty());
  5014. })
  5015. .Post("/validate-no-multiple-headers",
  5016. [&](const Request &req, Response & /*res*/) {
  5017. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5018. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5019. })
  5020. .Post("/content_receiver",
  5021. [&](const Request &req, Response &res,
  5022. const ContentReader &content_reader) {
  5023. if (req.is_multipart_form_data()) {
  5024. std::vector<FormData> items;
  5025. content_reader(
  5026. [&](const FormData &file) {
  5027. items.push_back(file);
  5028. return true;
  5029. },
  5030. [&](const char *data, size_t data_length) {
  5031. items.back().content.append(data, data_length);
  5032. return true;
  5033. });
  5034. EXPECT_EQ(5u, items.size());
  5035. {
  5036. const auto &file = get_file_value(items, "text1");
  5037. EXPECT_TRUE(file.filename.empty());
  5038. EXPECT_EQ("text default", file.content);
  5039. }
  5040. {
  5041. const auto &file = get_file_value(items, "text2");
  5042. EXPECT_TRUE(file.filename.empty());
  5043. EXPECT_EQ("aωb", file.content);
  5044. }
  5045. {
  5046. const auto &file = get_file_value(items, "file1");
  5047. EXPECT_EQ("hello.txt", file.filename);
  5048. EXPECT_EQ("text/plain", file.content_type);
  5049. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5050. }
  5051. {
  5052. const auto &file = get_file_value(items, "file2");
  5053. EXPECT_EQ("world.json", file.filename);
  5054. EXPECT_EQ("application/json", file.content_type);
  5055. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5056. }
  5057. {
  5058. const auto &file = get_file_value(items, "file3");
  5059. EXPECT_TRUE(file.filename.empty());
  5060. EXPECT_EQ("application/octet-stream", file.content_type);
  5061. EXPECT_EQ(0u, file.content.size());
  5062. }
  5063. } else {
  5064. std::string body;
  5065. content_reader([&](const char *data, size_t data_length) {
  5066. EXPECT_EQ(7U, data_length);
  5067. body.append(data, data_length);
  5068. return true;
  5069. });
  5070. EXPECT_EQ(body, "content");
  5071. res.set_content(body, "text/plain");
  5072. }
  5073. })
  5074. .Put("/content_receiver",
  5075. [&](const Request & /*req*/, Response &res,
  5076. const ContentReader &content_reader) {
  5077. std::string body;
  5078. content_reader([&](const char *data, size_t data_length) {
  5079. body.append(data, data_length);
  5080. return true;
  5081. });
  5082. EXPECT_EQ(body, "content");
  5083. res.set_content(body, "text/plain");
  5084. })
  5085. .Patch("/content_receiver",
  5086. [&](const Request & /*req*/, Response &res,
  5087. const ContentReader &content_reader) {
  5088. std::string body;
  5089. content_reader([&](const char *data, size_t data_length) {
  5090. body.append(data, data_length);
  5091. return true;
  5092. });
  5093. EXPECT_EQ(body, "content");
  5094. res.set_content(body, "text/plain");
  5095. })
  5096. .Post("/query-string-and-body",
  5097. [&](const Request &req, Response & /*res*/) {
  5098. ASSERT_TRUE(req.has_param("key"));
  5099. EXPECT_EQ(req.get_param_value("key"), "value");
  5100. EXPECT_EQ(req.body, "content");
  5101. })
  5102. .Get("/last-request",
  5103. [&](const Request &req, Response & /*res*/) {
  5104. EXPECT_EQ("close", req.get_header_value("Connection"));
  5105. })
  5106. .Get(R"(/redirect/(\d+))",
  5107. [&](const Request &req, Response &res) {
  5108. auto num = std::stoi(req.matches[1]) + 1;
  5109. std::string url = "/redirect/" + std::to_string(num);
  5110. res.set_redirect(url);
  5111. })
  5112. .Post("/binary",
  5113. [&](const Request &req, Response &res) {
  5114. EXPECT_EQ(4U, req.body.size());
  5115. EXPECT_EQ("application/octet-stream",
  5116. req.get_header_value("Content-Type"));
  5117. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5118. res.set_content(req.body, "application/octet-stream");
  5119. })
  5120. .Put("/binary",
  5121. [&](const Request &req, Response &res) {
  5122. EXPECT_EQ(4U, req.body.size());
  5123. EXPECT_EQ("application/octet-stream",
  5124. req.get_header_value("Content-Type"));
  5125. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5126. res.set_content(req.body, "application/octet-stream");
  5127. })
  5128. .Patch("/binary",
  5129. [&](const Request &req, Response &res) {
  5130. EXPECT_EQ(4U, req.body.size());
  5131. EXPECT_EQ("application/octet-stream",
  5132. req.get_header_value("Content-Type"));
  5133. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5134. res.set_content(req.body, "application/octet-stream");
  5135. })
  5136. .Delete("/binary",
  5137. [&](const Request &req, Response &res) {
  5138. EXPECT_EQ(4U, req.body.size());
  5139. EXPECT_EQ("application/octet-stream",
  5140. req.get_header_value("Content-Type"));
  5141. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5142. res.set_content(req.body, "application/octet-stream");
  5143. })
  5144. .Get("/issue1772",
  5145. [&](const Request & /*req*/, Response &res) {
  5146. res.status = 401;
  5147. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5148. })
  5149. .Delete("/issue609",
  5150. [](const httplib::Request &, httplib::Response &res,
  5151. const httplib::ContentReader &) {
  5152. res.set_content("ok", "text/plain");
  5153. })
  5154. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5155. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5156. .Get("/compress",
  5157. [&](const Request & /*req*/, Response &res) {
  5158. res.set_content(
  5159. "12345678901234567890123456789012345678901234567890123456789"
  5160. "01234567890123456789012345678901234567890",
  5161. "text/plain");
  5162. })
  5163. .Get("/compress-with-charset",
  5164. [&](const Request & /*req*/, Response &res) {
  5165. res.set_content(
  5166. "12345678901234567890123456789012345678901234567890123456789"
  5167. "01234567890123456789012345678901234567890",
  5168. "application/json; charset=utf-8");
  5169. })
  5170. .Get("/nocompress",
  5171. [&](const Request & /*req*/, Response &res) {
  5172. res.set_content(
  5173. "12345678901234567890123456789012345678901234567890123456789"
  5174. "01234567890123456789012345678901234567890",
  5175. "application/octet-stream");
  5176. })
  5177. .Post("/compress-multipart",
  5178. [&](const Request &req, Response & /*res*/) {
  5179. EXPECT_EQ(2u, req.form.fields.size());
  5180. ASSERT_TRUE(!req.form.has_field("???"));
  5181. {
  5182. const auto &text = req.form.get_field("key1");
  5183. EXPECT_EQ("test", text);
  5184. }
  5185. {
  5186. const auto &text = req.form.get_field("key2");
  5187. EXPECT_EQ("--abcdefg123", text);
  5188. }
  5189. })
  5190. #endif
  5191. ;
  5192. persons_["john"] = "programmer";
  5193. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5194. svr_.wait_until_ready();
  5195. }
  5196. virtual void TearDown() {
  5197. svr_.stop();
  5198. if (!request_threads_.empty()) {
  5199. std::this_thread::sleep_for(std::chrono::seconds(1));
  5200. for (auto &t : request_threads_) {
  5201. t.join();
  5202. }
  5203. }
  5204. t_.join();
  5205. }
  5206. map<string, string> persons_;
  5207. #ifdef CPPHTTPLIB_SSL_ENABLED
  5208. SSLClient cli_;
  5209. SSLServer svr_;
  5210. #else
  5211. Client cli_;
  5212. Server svr_;
  5213. #endif
  5214. thread t_;
  5215. std::vector<thread> request_threads_;
  5216. };
  5217. TEST_F(ServerTest, GetMethod200) {
  5218. auto res = cli_.Get("/hi");
  5219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5220. EXPECT_EQ("HTTP/1.1", res->version);
  5221. EXPECT_EQ(StatusCode::OK_200, res->status);
  5222. EXPECT_EQ("OK", res->reason);
  5223. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5224. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5225. EXPECT_EQ("Hello World!", res->body);
  5226. }
  5227. TEST_F(ServerTest, GetEmptyFile) {
  5228. auto res = cli_.Get("/empty_file");
  5229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5230. EXPECT_EQ(StatusCode::OK_200, res->status);
  5231. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5232. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5233. EXPECT_EQ("", res->body);
  5234. }
  5235. TEST_F(ServerTest, GetFileContent) {
  5236. auto res = cli_.Get("/file_content");
  5237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5238. EXPECT_EQ(StatusCode::OK_200, res->status);
  5239. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5240. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5241. EXPECT_EQ("test.html", res->body);
  5242. }
  5243. TEST_F(ServerTest, GetFileContentWithRange) {
  5244. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5246. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5247. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5248. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5249. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5250. EXPECT_EQ("est", res->body);
  5251. }
  5252. TEST_F(ServerTest, GetFileContentWithContentType) {
  5253. auto res = cli_.Get("/file_content_with_content_type");
  5254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5255. EXPECT_EQ(StatusCode::OK_200, res->status);
  5256. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5257. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5258. EXPECT_EQ("file\n", res->body);
  5259. }
  5260. TEST_F(ServerTest, GetInvalidFileContent) {
  5261. auto res = cli_.Get("/invalid_file_content");
  5262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5263. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5264. }
  5265. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5266. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5268. EXPECT_EQ("HTTP/1.1", res->version);
  5269. EXPECT_EQ(StatusCode::OK_200, res->status);
  5270. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5271. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5272. EXPECT_EQ("Hello World!", res->body);
  5273. }
  5274. TEST_F(ServerTest, GetMethod302) {
  5275. auto res = cli_.Get("/");
  5276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5277. EXPECT_EQ(StatusCode::Found_302, res->status);
  5278. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5279. }
  5280. TEST_F(ServerTest, GetMethod302Redirect) {
  5281. cli_.set_follow_location(true);
  5282. auto res = cli_.Get("/");
  5283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5284. EXPECT_EQ(StatusCode::OK_200, res->status);
  5285. EXPECT_EQ("Hello World!", res->body);
  5286. EXPECT_EQ("/hi", res->location);
  5287. }
  5288. TEST_F(ServerTest, GetMethod404) {
  5289. auto res = cli_.Get("/invalid");
  5290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5291. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5292. }
  5293. TEST_F(ServerTest, HeadMethod200) {
  5294. auto res = cli_.Head("/hi");
  5295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5298. EXPECT_TRUE(res->body.empty());
  5299. }
  5300. TEST_F(ServerTest, HeadMethod200Static) {
  5301. auto res = cli_.Head("/mount/dir/index.html");
  5302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5305. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5306. EXPECT_TRUE(res->body.empty());
  5307. }
  5308. TEST_F(ServerTest, HeadMethod404) {
  5309. auto res = cli_.Head("/invalid");
  5310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5311. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5312. EXPECT_TRUE(res->body.empty());
  5313. }
  5314. TEST_F(ServerTest, GetMethodPersonJohn) {
  5315. auto res = cli_.Get("/person/john");
  5316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5317. EXPECT_EQ(StatusCode::OK_200, res->status);
  5318. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5319. EXPECT_EQ("programmer", res->body);
  5320. }
  5321. TEST_F(ServerTest, PostMethod1) {
  5322. auto res = cli_.Get("/person/john1");
  5323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5324. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5325. res = cli_.Post("/person", "name=john1&note=coder",
  5326. "application/x-www-form-urlencoded");
  5327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5328. ASSERT_EQ(StatusCode::OK_200, res->status);
  5329. res = cli_.Get("/person/john1");
  5330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5331. ASSERT_EQ(StatusCode::OK_200, res->status);
  5332. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5333. ASSERT_EQ("coder", res->body);
  5334. }
  5335. TEST_F(ServerTest, PostMethod2) {
  5336. auto res = cli_.Get("/person/john2");
  5337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5338. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5339. Params params;
  5340. params.emplace("name", "john2");
  5341. params.emplace("note", "coder");
  5342. res = cli_.Post("/person", params);
  5343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5344. ASSERT_EQ(StatusCode::OK_200, res->status);
  5345. res = cli_.Get("/person/john2");
  5346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5347. ASSERT_EQ(StatusCode::OK_200, res->status);
  5348. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5349. ASSERT_EQ("coder", res->body);
  5350. }
  5351. TEST_F(ServerTest, PutMethod3) {
  5352. auto res = cli_.Get("/person/john3");
  5353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5354. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5355. Params params;
  5356. params.emplace("name", "john3");
  5357. params.emplace("note", "coder");
  5358. res = cli_.Put("/person", params);
  5359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5360. ASSERT_EQ(StatusCode::OK_200, res->status);
  5361. res = cli_.Get("/person/john3");
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. ASSERT_EQ(StatusCode::OK_200, res->status);
  5364. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5365. ASSERT_EQ("coder", res->body);
  5366. }
  5367. TEST_F(ServerTest, DeleteMethod1) {
  5368. auto res = cli_.Get("/person/john4");
  5369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5370. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5371. Params params;
  5372. params.emplace("name", "john4");
  5373. params.emplace("note", "coder");
  5374. res = cli_.Post("/person", params);
  5375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5376. ASSERT_EQ(StatusCode::OK_200, res->status);
  5377. res = cli_.Get("/person/john4");
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. ASSERT_EQ(StatusCode::OK_200, res->status);
  5380. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5381. ASSERT_EQ("coder", res->body);
  5382. Params delete_params;
  5383. delete_params.emplace("name", "john4");
  5384. res = cli_.Delete("/person", delete_params);
  5385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5386. ASSERT_EQ(StatusCode::OK_200, res->status);
  5387. ASSERT_EQ("DELETED", res->body);
  5388. res = cli_.Get("/person/john4");
  5389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5390. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5391. }
  5392. TEST_F(ServerTest, DeleteMethod2) {
  5393. auto res = cli_.Get("/person/john5");
  5394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5395. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5396. Params params;
  5397. params.emplace("name", "john5");
  5398. params.emplace("note", "developer");
  5399. res = cli_.Post("/person", params);
  5400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5401. ASSERT_EQ(StatusCode::OK_200, res->status);
  5402. res = cli_.Get("/person/john5");
  5403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5404. ASSERT_EQ(StatusCode::OK_200, res->status);
  5405. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5406. ASSERT_EQ("developer", res->body);
  5407. Params delete_params;
  5408. delete_params.emplace("name", "john5");
  5409. Headers headers;
  5410. headers.emplace("Custom-Header", "test-value");
  5411. res = cli_.Delete("/person", headers, delete_params);
  5412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5413. ASSERT_EQ(StatusCode::OK_200, res->status);
  5414. ASSERT_EQ("DELETED", res->body);
  5415. res = cli_.Get("/person/john5");
  5416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5417. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5418. }
  5419. TEST_F(ServerTest, DeleteMethod3) {
  5420. auto res = cli_.Get("/person/john6");
  5421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5422. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5423. Params params;
  5424. params.emplace("name", "john6");
  5425. params.emplace("note", "tester");
  5426. res = cli_.Post("/person", params);
  5427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5428. ASSERT_EQ(StatusCode::OK_200, res->status);
  5429. res = cli_.Get("/person/john6");
  5430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5431. ASSERT_EQ(StatusCode::OK_200, res->status);
  5432. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5433. ASSERT_EQ("tester", res->body);
  5434. Params delete_params;
  5435. delete_params.emplace("name", "john6");
  5436. Headers headers;
  5437. headers.emplace("Custom-Header", "test-value");
  5438. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5440. ASSERT_EQ(StatusCode::OK_200, res->status);
  5441. ASSERT_EQ("DELETED", res->body);
  5442. res = cli_.Get("/person/john6");
  5443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5444. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5445. }
  5446. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5447. Params params;
  5448. params.emplace("json", JSON_DATA);
  5449. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5451. ASSERT_EQ(StatusCode::OK_200, res->status);
  5452. ASSERT_EQ(JSON_DATA, res->body);
  5453. }
  5454. TEST_F(ServerTest, PostEmptyContent) {
  5455. auto res = cli_.Post("/empty", "", "text/plain");
  5456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5457. ASSERT_EQ(StatusCode::OK_200, res->status);
  5458. ASSERT_EQ("empty", res->body);
  5459. }
  5460. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5461. auto res = cli_.Post("/empty-no-content-type");
  5462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5463. ASSERT_EQ(StatusCode::OK_200, res->status);
  5464. ASSERT_EQ("empty-no-content-type", res->body);
  5465. }
  5466. TEST_F(ServerTest, PostPathOnly) {
  5467. auto res = cli_.Post("/path-only");
  5468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5469. ASSERT_EQ(StatusCode::OK_200, res->status);
  5470. ASSERT_EQ("path-only", res->body);
  5471. }
  5472. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5473. auto res = cli_.Post("/path-headers-only",
  5474. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5476. ASSERT_EQ(StatusCode::OK_200, res->status);
  5477. ASSERT_EQ("path-headers-only", res->body);
  5478. }
  5479. TEST_F(ServerTest, PostLarge) {
  5480. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5482. ASSERT_EQ(StatusCode::OK_200, res->status);
  5483. EXPECT_EQ(LARGE_DATA, res->body);
  5484. }
  5485. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5486. auto res = cli_.Put("/empty-no-content-type");
  5487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5488. ASSERT_EQ(StatusCode::OK_200, res->status);
  5489. ASSERT_EQ("empty-no-content-type", res->body);
  5490. }
  5491. TEST_F(ServerTest, GetMethodDir) {
  5492. auto res = cli_.Get("/dir/");
  5493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5494. EXPECT_EQ(StatusCode::OK_200, res->status);
  5495. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5496. auto body = R"(<html>
  5497. <head>
  5498. </head>
  5499. <body>
  5500. <a href="/dir/test.html">Test</a>
  5501. <a href="/hi">hi</a>
  5502. </body>
  5503. </html>
  5504. )";
  5505. EXPECT_EQ(body, res->body);
  5506. }
  5507. TEST_F(ServerTest, GetMethodDirTest) {
  5508. auto res = cli_.Get("/dir/test.html");
  5509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5510. EXPECT_EQ(StatusCode::OK_200, res->status);
  5511. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5512. EXPECT_EQ("test.html", res->body);
  5513. }
  5514. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5515. auto res = cli_.Get("/dir/../dir/test.html");
  5516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5517. EXPECT_EQ(StatusCode::OK_200, res->status);
  5518. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5519. EXPECT_EQ("test.html", res->body);
  5520. }
  5521. TEST_F(ServerTest, GetMethodInvalidPath) {
  5522. auto res = cli_.Get("/dir/../test.html");
  5523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5525. }
  5526. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5527. auto res = cli_.Get("/../www/dir/test.html");
  5528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5530. }
  5531. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5532. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5534. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5535. }
  5536. TEST_F(ServerTest, GetMethodDirMountTest) {
  5537. auto res = cli_.Get("/mount/dir/test.html");
  5538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5539. EXPECT_EQ(StatusCode::OK_200, res->status);
  5540. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5541. EXPECT_EQ("test.html", res->body);
  5542. }
  5543. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5544. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5546. EXPECT_EQ(StatusCode::OK_200, res->status);
  5547. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5548. EXPECT_EQ("test.html", res->body);
  5549. }
  5550. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5551. auto res = cli_.Get("/mount/dir/../test.html");
  5552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5553. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5554. }
  5555. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5556. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5558. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5559. }
  5560. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5561. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5563. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5564. }
  5565. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5566. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5569. }
  5570. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5571. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5573. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5574. }
  5575. TEST_F(ServerTest, PostMethod303) {
  5576. auto res = cli_.Post("/1", "body", "text/plain");
  5577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5578. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5579. EXPECT_EQ("/2", res->get_header_value("Location"));
  5580. }
  5581. TEST_F(ServerTest, PostMethod303Redirect) {
  5582. cli_.set_follow_location(true);
  5583. auto res = cli_.Post("/1", "body", "text/plain");
  5584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5585. EXPECT_EQ(StatusCode::OK_200, res->status);
  5586. EXPECT_EQ("redirected.", res->body);
  5587. EXPECT_EQ("/2", res->location);
  5588. }
  5589. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5590. auto res = cli_.Get("/dir/test.abcde");
  5591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5592. EXPECT_EQ(StatusCode::OK_200, res->status);
  5593. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5594. EXPECT_EQ("abcde", res->body);
  5595. }
  5596. TEST_F(ServerTest, StaticFileRange) {
  5597. auto res =
  5598. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5600. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5601. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5602. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5603. EXPECT_EQ(true, res->has_header("Content-Range"));
  5604. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5605. EXPECT_EQ(std::string("cd"), res->body);
  5606. }
  5607. TEST_F(ServerTest, StaticFileRanges) {
  5608. auto res = cli_.Get("/dir/test.abcde",
  5609. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5611. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5612. EXPECT_TRUE(
  5613. res->get_header_value("Content-Type")
  5614. .find(
  5615. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5616. 0);
  5617. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5618. }
  5619. TEST_F(ServerTest, StaticFileRangeHead) {
  5620. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5623. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5624. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5625. EXPECT_EQ(true, res->has_header("Content-Range"));
  5626. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5627. }
  5628. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5629. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5631. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5632. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5633. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5634. EXPECT_EQ(true, res->has_header("Content-Range"));
  5635. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5636. res->get_header_value("Content-Range"));
  5637. EXPECT_EQ("LAST\n", res->body);
  5638. }
  5639. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5640. auto res =
  5641. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5643. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5644. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5645. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5646. EXPECT_EQ(true, res->has_header("Content-Range"));
  5647. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5648. }
  5649. TEST_F(ServerTest, StaticFileBigFile) {
  5650. auto res = cli_.Get("/dir/1MB.txt");
  5651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5652. EXPECT_EQ(StatusCode::OK_200, res->status);
  5653. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5654. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5655. }
  5656. TEST_F(ServerTest, InvalidBaseDirMount) {
  5657. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5658. }
  5659. TEST_F(ServerTest, Binary) {
  5660. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5661. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5662. "application/octet-stream");
  5663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5664. ASSERT_EQ(StatusCode::OK_200, res->status);
  5665. ASSERT_EQ(4U, res->body.size());
  5666. res = cli_.Put("/binary", binary.data(), binary.size(),
  5667. "application/octet-stream");
  5668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5669. ASSERT_EQ(StatusCode::OK_200, res->status);
  5670. ASSERT_EQ(4U, res->body.size());
  5671. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5672. "application/octet-stream");
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. ASSERT_EQ(StatusCode::OK_200, res->status);
  5675. ASSERT_EQ(4U, res->body.size());
  5676. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5677. "application/octet-stream");
  5678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5679. ASSERT_EQ(StatusCode::OK_200, res->status);
  5680. ASSERT_EQ(4U, res->body.size());
  5681. }
  5682. TEST_F(ServerTest, BinaryString) {
  5683. auto binary = std::string("\x00\x01\x02\x03", 4);
  5684. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5686. ASSERT_EQ(StatusCode::OK_200, res->status);
  5687. ASSERT_EQ(4U, res->body.size());
  5688. res = cli_.Put("/binary", binary, "application/octet-stream");
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. ASSERT_EQ(StatusCode::OK_200, res->status);
  5691. ASSERT_EQ(4U, res->body.size());
  5692. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. ASSERT_EQ(StatusCode::OK_200, res->status);
  5695. ASSERT_EQ(4U, res->body.size());
  5696. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5698. ASSERT_EQ(StatusCode::OK_200, res->status);
  5699. ASSERT_EQ(4U, res->body.size());
  5700. }
  5701. TEST_F(ServerTest, EmptyRequest) {
  5702. auto res = cli_.Get("");
  5703. ASSERT_TRUE(!res);
  5704. EXPECT_EQ(Error::Connection, res.error());
  5705. }
  5706. TEST_F(ServerTest, LongRequest) {
  5707. std::string request;
  5708. for (size_t i = 0; i < 545; i++) {
  5709. request += "/TooLongRequest";
  5710. }
  5711. request += "OK";
  5712. auto res = cli_.Get(request.c_str());
  5713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5715. }
  5716. TEST_F(ServerTest, TooLongRequest) {
  5717. std::string request;
  5718. for (size_t i = 0; i < 546; i++) {
  5719. request += "/TooLongRequest";
  5720. }
  5721. request += "_NG";
  5722. auto start = std::chrono::high_resolution_clock::now();
  5723. cli_.set_keep_alive(true);
  5724. auto res = cli_.Get(request.c_str());
  5725. auto end = std::chrono::high_resolution_clock::now();
  5726. auto elapsed =
  5727. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5728. .count();
  5729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5730. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5731. EXPECT_LE(elapsed, 1000);
  5732. EXPECT_EQ("close", res->get_header_value("Connection"));
  5733. EXPECT_FALSE(cli_.is_socket_open());
  5734. }
  5735. TEST_F(ServerTest, AlmostTooLongRequest) {
  5736. // test for #2046 - URI length check shouldn't include other content on req
  5737. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5738. // leading /, space, HTTP/1.1)
  5739. std::string request =
  5740. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5741. auto res = cli_.Get(request.c_str());
  5742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5743. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5744. }
  5745. TEST_F(ServerTest, LongHeader) {
  5746. Request req;
  5747. req.method = "GET";
  5748. req.path = "/hi";
  5749. std::string host_and_port;
  5750. host_and_port += HOST;
  5751. host_and_port += ":";
  5752. host_and_port += std::to_string(PORT);
  5753. req.headers.emplace("Host", host_and_port.c_str());
  5754. req.headers.emplace("Accept", "*/*");
  5755. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5756. req.headers.emplace(
  5757. "Header-Name",
  5758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5786. "@@@@@@@@@@@@@@@@");
  5787. auto res = std::make_shared<Response>();
  5788. auto error = Error::Success;
  5789. auto ret = cli_.send(req, *res, error);
  5790. ASSERT_TRUE(ret);
  5791. EXPECT_EQ(StatusCode::OK_200, res->status);
  5792. }
  5793. TEST_F(ServerTest, LongQueryValue) {
  5794. auto start = std::chrono::high_resolution_clock::now();
  5795. cli_.set_keep_alive(true);
  5796. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5797. auto end = std::chrono::high_resolution_clock::now();
  5798. auto elapsed =
  5799. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5800. .count();
  5801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5802. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5803. EXPECT_LE(elapsed, 1000);
  5804. EXPECT_EQ("close", res->get_header_value("Connection"));
  5805. EXPECT_FALSE(cli_.is_socket_open());
  5806. }
  5807. TEST_F(ServerTest, TooLongQueryValue) {
  5808. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5809. ASSERT_FALSE(res);
  5810. EXPECT_EQ(Error::Read, res.error());
  5811. }
  5812. TEST_F(ServerTest, TooLongHeader) {
  5813. Request req;
  5814. req.method = "GET";
  5815. req.path = "/hi";
  5816. std::string host_and_port;
  5817. host_and_port += HOST;
  5818. host_and_port += ":";
  5819. host_and_port += std::to_string(PORT);
  5820. req.headers.emplace("Host", host_and_port.c_str());
  5821. req.headers.emplace("Accept", "*/*");
  5822. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5823. req.headers.emplace(
  5824. "Header-Name",
  5825. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5826. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5827. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5828. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5853. "@@@@@@@@@@@@@@@@@");
  5854. auto res = std::make_shared<Response>();
  5855. auto error = Error::Success;
  5856. auto ret = cli_.send(req, *res, error);
  5857. ASSERT_TRUE(ret);
  5858. EXPECT_EQ(StatusCode::OK_200, res->status);
  5859. }
  5860. TEST_F(ServerTest, HeaderCountAtLimit) {
  5861. // Test with headers just under the 100 limit
  5862. httplib::Headers headers;
  5863. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5864. // This should keep us just under the 100 header limit
  5865. for (int i = 0; i < 95; i++) {
  5866. std::string name = "X-Test-Header-" + std::to_string(i);
  5867. std::string value = "value" + std::to_string(i);
  5868. headers.emplace(name, value);
  5869. }
  5870. // This should work fine as we're under the limit
  5871. auto res = cli_.Get("/hi", headers);
  5872. EXPECT_TRUE(res);
  5873. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5874. }
  5875. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5876. // Test with many headers to exceed the 100 limit
  5877. httplib::Headers headers;
  5878. // Add 150 headers to definitely exceed the 100 limit
  5879. for (int i = 0; i < 150; i++) {
  5880. std::string name = "X-Test-Header-" + std::to_string(i);
  5881. std::string value = "value" + std::to_string(i);
  5882. headers.emplace(name, value);
  5883. }
  5884. // This should fail due to exceeding header count limit
  5885. cli_.set_keep_alive(true);
  5886. auto res = cli_.Get("/hi", headers);
  5887. // The server should respond with 400 Bad Request
  5888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5889. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5890. EXPECT_EQ("close", res->get_header_value("Connection"));
  5891. EXPECT_FALSE(cli_.is_socket_open());
  5892. }
  5893. TEST_F(ServerTest, PercentEncoding) {
  5894. auto res = cli_.Get("/e%6edwith%");
  5895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5896. EXPECT_EQ(StatusCode::OK_200, res->status);
  5897. }
  5898. TEST_F(ServerTest, PercentEncodingUnicode) {
  5899. auto res = cli_.Get("/e%u006edwith%");
  5900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5901. EXPECT_EQ(StatusCode::OK_200, res->status);
  5902. }
  5903. TEST_F(ServerTest, InvalidPercentEncoding) {
  5904. auto res = cli_.Get("/%endwith%");
  5905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5906. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5907. }
  5908. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5909. auto res = cli_.Get("/%uendwith%");
  5910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5911. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5912. }
  5913. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5914. auto res = cli_.Get("/hello?aaa=bbb%");
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5917. }
  5918. TEST_F(ServerTest, PlusSignEncoding) {
  5919. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5921. EXPECT_EQ(StatusCode::OK_200, res->status);
  5922. EXPECT_EQ("a +b", res->body);
  5923. }
  5924. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5925. // This test simulates a potential DoS attack using many headers
  5926. // to verify our security fix prevents memory exhaustion
  5927. httplib::Headers attack_headers;
  5928. // Attempt to add many headers like an attacker would (200 headers to far
  5929. // exceed limit)
  5930. for (int i = 0; i < 200; i++) {
  5931. std::string name = "X-Attack-Header-" + std::to_string(i);
  5932. std::string value = "attack_payload_" + std::to_string(i);
  5933. attack_headers.emplace(name, value);
  5934. }
  5935. // Try to POST with excessive headers
  5936. cli_.set_keep_alive(true);
  5937. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5938. // Should either fail or return 400 Bad Request due to security limit
  5939. if (res) {
  5940. // If we get a response, it should be 400 Bad Request
  5941. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5942. EXPECT_EQ("close", res->get_header_value("Connection"));
  5943. }
  5944. EXPECT_FALSE(cli_.is_socket_open());
  5945. }
  5946. TEST_F(ServerTest, MultipartFormData) {
  5947. UploadFormDataItems items = {
  5948. {"text1", "text default", "", ""},
  5949. {"text2", "aωb", "", ""},
  5950. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5951. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5952. {"file3", "", "", "application/octet-stream"},
  5953. {"file4", "", "", " application/json tmp-string "}};
  5954. auto res = cli_.Post("/multipart", items);
  5955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5956. EXPECT_EQ(StatusCode::OK_200, res->status);
  5957. }
  5958. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5959. UploadFormDataItems items = {
  5960. {"text", "default text", "", ""},
  5961. {"multi_text1", "aaaaa", "", ""},
  5962. {"multi_text1", "bbbbb", "", ""},
  5963. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5964. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5965. "application/json"},
  5966. };
  5967. auto res = cli_.Post("/multipart/multi_file_values", items);
  5968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5969. EXPECT_EQ(StatusCode::OK_200, res->status);
  5970. }
  5971. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5972. auto res = cli_.Get("/hi");
  5973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5974. EXPECT_EQ(StatusCode::OK_200, res->status);
  5975. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5976. EXPECT_EQ("Hello World!", res->body);
  5977. }
  5978. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5979. Request req;
  5980. req.method = "POST";
  5981. req.path = "/chunked";
  5982. std::string host_and_port;
  5983. host_and_port += HOST;
  5984. host_and_port += ":";
  5985. host_and_port += std::to_string(PORT);
  5986. req.headers.emplace("Host", host_and_port.c_str());
  5987. req.headers.emplace("Accept", "*/*");
  5988. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5989. req.headers.emplace("Content-Type", "text/plain");
  5990. req.headers.emplace("Content-Length", "0");
  5991. req.headers.emplace(
  5992. "Transfer-Encoding",
  5993. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5994. // Client does not chunk, so make a chunked body manually.
  5995. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5996. auto res = std::make_shared<Response>();
  5997. auto error = Error::Success;
  5998. auto ret = cli_.send(req, *res, error);
  5999. ASSERT_TRUE(ret);
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. }
  6002. template <typename ClientT>
  6003. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6004. int expected_status) {
  6005. Request req;
  6006. req.method = "POST";
  6007. req.path = "/chunked";
  6008. std::string host_and_port;
  6009. host_and_port += HOST;
  6010. host_and_port += ":";
  6011. host_and_port += std::to_string(PORT);
  6012. req.headers.emplace("Host", host_and_port.c_str());
  6013. req.headers.emplace("Content-Length", "0");
  6014. req.headers.emplace("Transfer-Encoding", "chunked");
  6015. req.body = body;
  6016. auto res = std::make_shared<Response>();
  6017. auto error = Error::Success;
  6018. ASSERT_TRUE(cli.send(req, *res, error));
  6019. EXPECT_EQ(expected_status, res->status);
  6020. }
  6021. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6022. // rather than treat them as valid lengths.
  6023. template <typename ClientT>
  6024. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6025. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6026. }
  6027. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6028. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6029. }
  6030. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6031. expect_chunked_body_rejected(
  6032. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6033. }
  6034. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6035. // chunk-size line carries no CR, LF or other control character ahead of its
  6036. // terminator. Such a line must be refused rather than read as extension text.
  6037. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6038. expect_chunked_body_rejected(
  6039. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6040. }
  6041. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6042. expect_chunked_body_rejected(
  6043. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6044. }
  6045. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6046. expect_chunked_body_rejected(
  6047. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6048. }
  6049. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6050. // The literal stays split: a hex escape consumes every hex digit that
  6051. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6052. expect_chunked_body_rejected(
  6053. cli_, "4;a\x01"
  6054. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6055. }
  6056. TEST_F(ServerTest, AcceptsChunkExtension) {
  6057. expect_chunked_body_status(cli_,
  6058. "4;name=value\r\ndech\r\n"
  6059. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6060. "0;last\r\n\r\n",
  6061. StatusCode::OK_200);
  6062. }
  6063. TEST_F(ServerTest, GetStreamed2) {
  6064. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6066. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6067. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6068. EXPECT_EQ(true, res->has_header("Content-Range"));
  6069. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6070. EXPECT_EQ(std::string("ab"), res->body);
  6071. }
  6072. TEST_F(ServerTest, GetStreamed) {
  6073. auto res = cli_.Get("/streamed");
  6074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6075. EXPECT_EQ(StatusCode::OK_200, res->status);
  6076. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6077. EXPECT_EQ(std::string("aaabbb"), res->body);
  6078. }
  6079. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6080. auto res = cli_.Get("/streamed-without-length",
  6081. Headers{make_range_header({{0, -1}})});
  6082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6083. EXPECT_EQ(StatusCode::OK_200, res->status);
  6084. EXPECT_EQ(false, res->has_header("Content-Length"));
  6085. EXPECT_EQ(false, res->has_header("Content-Range"));
  6086. EXPECT_EQ(std::string("abcdefg"), res->body);
  6087. }
  6088. TEST_F(ServerTest, GetStreamedWithRange1) {
  6089. auto res =
  6090. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6092. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6093. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6094. EXPECT_EQ(true, res->has_header("Content-Range"));
  6095. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6096. EXPECT_EQ(std::string("def"), res->body);
  6097. }
  6098. TEST_F(ServerTest, GetStreamedWithRange2) {
  6099. auto res =
  6100. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6102. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6103. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6104. EXPECT_EQ(true, res->has_header("Content-Range"));
  6105. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6106. EXPECT_EQ(std::string("bcdefg"), res->body);
  6107. }
  6108. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6109. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6111. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6112. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6113. EXPECT_EQ(true, res->has_header("Content-Range"));
  6114. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6115. EXPECT_EQ(std::string("efg"), res->body);
  6116. }
  6117. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6118. auto res =
  6119. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  6120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6121. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6122. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6123. EXPECT_EQ(false, res->has_header("Content-Range"));
  6124. EXPECT_EQ(0U, res->body.size());
  6125. }
  6126. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6127. // Only a 206 is served as a partial representation. Under any other status
  6128. // `apply_ranges()` reported the full content length, so the body must match
  6129. // that header, and the content provider must never be asked for an offset
  6130. // outside the representation.
  6131. auto check = [&](int status, const char *range) {
  6132. auto path =
  6133. std::string("/streamed-with-range?status=") + std::to_string(status);
  6134. auto ctx = path + " Range: " + range;
  6135. auto res = cli_.Get(path, Headers{{"Range", range}});
  6136. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6137. EXPECT_EQ(status, res->status) << ctx;
  6138. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6139. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6140. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6141. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6142. };
  6143. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6144. check(403, "bytes=3-5");
  6145. // The offset is far past the representation.
  6146. check(403, "bytes=100000-100200");
  6147. // `first_pos` is still -1 here, and the bounds asserts in
  6148. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6149. check(403, "bytes=-3");
  6150. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6151. // multipart branch would have written one that is empty.
  6152. check(403, "bytes=1-2, 4-5");
  6153. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6154. // covers the whole representation.
  6155. check(200, "bytes=3-5");
  6156. check(200, "bytes=1-2, 4-5");
  6157. }
  6158. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6159. auto res =
  6160. cli_.Get("/streamed-with-range",
  6161. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6162. "92233720368547758079223372036854775807"}});
  6163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6164. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6165. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6166. EXPECT_EQ(false, res->has_header("Content-Range"));
  6167. EXPECT_EQ(0U, res->body.size());
  6168. }
  6169. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6170. auto res = cli_.Get(
  6171. "/with-range",
  6172. Headers{{"Range",
  6173. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6174. {"Accept-Encoding", ""}});
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6177. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6178. EXPECT_EQ(true, res->has_header("Content-Range"));
  6179. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6180. EXPECT_EQ(std::string("abcdefg"), res->body);
  6181. }
  6182. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6183. auto res = cli_.Get("/with-range", Headers{
  6184. {"Range", "bytes=0-"},
  6185. {"Accept-Encoding", ""},
  6186. });
  6187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6188. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6189. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6190. EXPECT_EQ(true, res->has_header("Content-Range"));
  6191. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6192. EXPECT_EQ(std::string("abcdefg"), res->body);
  6193. }
  6194. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6195. auto res = cli_.Get("/streamed-with-range",
  6196. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6199. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6200. EXPECT_EQ(false, res->has_header("Content-Range"));
  6201. EXPECT_EQ(267U, res->body.size());
  6202. // Check that both range contents are present
  6203. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6204. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6205. // Check that Content-Range headers are present for both ranges
  6206. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6207. std::string::npos);
  6208. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6209. std::string::npos);
  6210. }
  6211. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6212. Ranges ranges;
  6213. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6214. ranges.emplace_back(0, -1);
  6215. }
  6216. auto res = cli_.Get("/streamed-with-range?error",
  6217. Headers{{make_range_header(ranges)}});
  6218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6219. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6220. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6221. EXPECT_EQ(false, res->has_header("Content-Range"));
  6222. EXPECT_EQ(0U, res->body.size());
  6223. }
  6224. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6225. auto res = cli_.Get("/streamed-with-range",
  6226. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6228. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6229. EXPECT_EQ(5U, res->body.size());
  6230. // Check that overlapping ranges are coalesced into a single range
  6231. EXPECT_EQ("bcdef", res->body);
  6232. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6233. // Should be single range, not multipart
  6234. EXPECT_TRUE(res->has_header("Content-Range"));
  6235. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6236. }
  6237. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6238. auto res = cli_.Get("/streamed-with-range",
  6239. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6241. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6242. EXPECT_EQ(268U, res->body.size());
  6243. // Check that both range contents are present
  6244. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6245. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6246. // Check that Content-Range headers are present for both ranges
  6247. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6248. std::string::npos);
  6249. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6250. std::string::npos);
  6251. }
  6252. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6253. auto res = cli_.Get("/streamed-with-range",
  6254. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6257. EXPECT_EQ(269U, res->body.size());
  6258. // Check that both duplicate range contents are present
  6259. size_t first_abc = res->body.find("abc\r\n");
  6260. EXPECT_TRUE(first_abc != std::string::npos);
  6261. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6262. EXPECT_TRUE(second_abc != std::string::npos);
  6263. // Check that Content-Range headers are present for both ranges
  6264. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6265. EXPECT_TRUE(first_range != std::string::npos);
  6266. size_t second_range =
  6267. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6268. EXPECT_TRUE(second_range != std::string::npos);
  6269. }
  6270. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6271. auto res =
  6272. cli_.Get("/streamed-with-range?error",
  6273. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6275. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6276. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6277. EXPECT_EQ(false, res->has_header("Content-Range"));
  6278. EXPECT_EQ(0U, res->body.size());
  6279. }
  6280. TEST_F(ServerTest, GetStreamedEndless) {
  6281. uint64_t offset = 0;
  6282. auto res = cli_.Get("/streamed-cancel",
  6283. [&](const char * /*data*/, uint64_t data_length) {
  6284. if (offset < 100) {
  6285. offset += data_length;
  6286. return true;
  6287. }
  6288. return false;
  6289. });
  6290. ASSERT_TRUE(!res);
  6291. EXPECT_EQ(Error::Canceled, res.error());
  6292. }
  6293. TEST_F(ServerTest, ClientStop) {
  6294. std::atomic_size_t count{4};
  6295. std::vector<std::thread> threads;
  6296. for (auto i = count.load(); i != 0; --i) {
  6297. threads.emplace_back([&]() {
  6298. auto res = cli_.Get("/streamed-cancel",
  6299. [&](const char *, uint64_t) { return true; });
  6300. --count;
  6301. ASSERT_TRUE(!res);
  6302. EXPECT_TRUE(res.error() == Error::Canceled ||
  6303. res.error() == Error::Read || res.error() == Error::Write);
  6304. });
  6305. }
  6306. std::this_thread::sleep_for(std::chrono::seconds(2));
  6307. while (count != 0) {
  6308. cli_.stop();
  6309. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6310. }
  6311. for (auto &t : threads) {
  6312. t.join();
  6313. }
  6314. }
  6315. TEST_F(ServerTest, GetWithRange1) {
  6316. auto res = cli_.Get("/with-range", Headers{
  6317. make_range_header({{3, 5}}),
  6318. {"Accept-Encoding", ""},
  6319. });
  6320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6321. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6322. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6323. EXPECT_EQ(true, res->has_header("Content-Range"));
  6324. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6325. EXPECT_EQ(std::string("def"), res->body);
  6326. }
  6327. TEST_F(ServerTest, GetWithRange2) {
  6328. auto res = cli_.Get("/with-range", Headers{
  6329. make_range_header({{1, -1}}),
  6330. {"Accept-Encoding", ""},
  6331. });
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6334. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6335. EXPECT_EQ(true, res->has_header("Content-Range"));
  6336. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6337. EXPECT_EQ(std::string("bcdefg"), res->body);
  6338. }
  6339. TEST_F(ServerTest, GetWithRange3) {
  6340. auto res = cli_.Get("/with-range", Headers{
  6341. make_range_header({{0, 0}}),
  6342. {"Accept-Encoding", ""},
  6343. });
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6346. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6347. EXPECT_EQ(true, res->has_header("Content-Range"));
  6348. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6349. EXPECT_EQ(std::string("a"), res->body);
  6350. }
  6351. TEST_F(ServerTest, GetWithRange4) {
  6352. auto res = cli_.Get("/with-range", Headers{
  6353. make_range_header({{-1, 2}}),
  6354. {"Accept-Encoding", ""},
  6355. });
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6358. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6359. EXPECT_EQ(true, res->has_header("Content-Range"));
  6360. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6361. EXPECT_EQ(std::string("fg"), res->body);
  6362. }
  6363. TEST_F(ServerTest, GetWithRange5) {
  6364. auto res = cli_.Get("/with-range", Headers{
  6365. make_range_header({{0, 5}}),
  6366. {"Accept-Encoding", ""},
  6367. });
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6370. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6371. EXPECT_EQ(true, res->has_header("Content-Range"));
  6372. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6373. EXPECT_EQ(std::string("abcdef"), res->body);
  6374. }
  6375. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6376. auto res =
  6377. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6379. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6380. }
  6381. TEST_F(ServerTest, GetWithRangeMultipart) {
  6382. auto res =
  6383. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6385. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6386. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6387. EXPECT_EQ(false, res->has_header("Content-Range"));
  6388. EXPECT_EQ(267U, res->body.size());
  6389. }
  6390. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6391. auto res = cli_.Get("/with-range",
  6392. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6394. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6395. }
  6396. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6397. auto res = cli_.Get("/with-range-customized-response",
  6398. Headers{{make_range_header({{1, 2}})}});
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6401. EXPECT_EQ(true, res->has_header("Content-Length"));
  6402. EXPECT_EQ(false, res->has_header("Content-Range"));
  6403. EXPECT_EQ(JSON_DATA, res->body);
  6404. }
  6405. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6406. auto res = cli_.Get("/with-range-customized-response",
  6407. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6409. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6410. EXPECT_EQ(true, res->has_header("Content-Length"));
  6411. EXPECT_EQ(false, res->has_header("Content-Range"));
  6412. EXPECT_EQ(JSON_DATA, res->body);
  6413. }
  6414. TEST_F(ServerTest, Issue1772) {
  6415. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6418. }
  6419. TEST_F(ServerTest, Issue609) {
  6420. auto res = cli_.Delete("/issue609");
  6421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6422. EXPECT_EQ(StatusCode::OK_200, res->status);
  6423. EXPECT_EQ(std::string("ok"), res->body);
  6424. }
  6425. TEST_F(ServerTest, GetStreamedChunked) {
  6426. auto res = cli_.Get("/streamed-chunked");
  6427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6428. EXPECT_EQ(StatusCode::OK_200, res->status);
  6429. EXPECT_EQ(std::string("123456789"), res->body);
  6430. }
  6431. TEST_F(ServerTest, GetStreamedChunked2) {
  6432. auto res = cli_.Get("/streamed-chunked2");
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. EXPECT_EQ(StatusCode::OK_200, res->status);
  6435. EXPECT_EQ(std::string("123456789"), res->body);
  6436. }
  6437. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6438. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6440. EXPECT_EQ(StatusCode::OK_200, res->status);
  6441. EXPECT_EQ(std::string("123456789"), res->body);
  6442. EXPECT_TRUE(res->has_header("Trailer"));
  6443. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6444. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6445. // Trailers are now stored separately from headers (security fix)
  6446. EXPECT_EQ(2U, res->trailers.size());
  6447. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6448. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6449. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6450. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6451. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6452. // Verify trailers are NOT in headers (security verification)
  6453. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6454. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6455. }
  6456. TEST_F(ServerTest, LargeChunkedPost) {
  6457. Request req;
  6458. req.method = "POST";
  6459. req.path = "/large-chunked";
  6460. std::string host_and_port;
  6461. host_and_port += HOST;
  6462. host_and_port += ":";
  6463. host_and_port += std::to_string(PORT);
  6464. req.headers.emplace("Host", host_and_port.c_str());
  6465. req.headers.emplace("Accept", "*/*");
  6466. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6467. req.headers.emplace("Content-Type", "text/plain");
  6468. req.headers.emplace("Content-Length", "0");
  6469. req.headers.emplace("Transfer-Encoding", "chunked");
  6470. std::string long_string(30 * 1024u, 'a');
  6471. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6472. // Attempt to make a large enough post to exceed OS buffers, to test that
  6473. // the server handles short reads if the full chunk data isn't available.
  6474. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6475. auto res = std::make_shared<Response>();
  6476. auto error = Error::Success;
  6477. auto ret = cli_.send(req, *res, error);
  6478. ASSERT_TRUE(ret);
  6479. EXPECT_EQ(StatusCode::OK_200, res->status);
  6480. }
  6481. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6482. auto res = cli_.Get("/remote_addr");
  6483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6484. EXPECT_EQ(StatusCode::OK_200, res->status);
  6485. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6486. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6487. }
  6488. TEST_F(ServerTest, GetMethodLocalAddr) {
  6489. auto res = cli_.Get("/local_addr");
  6490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6491. EXPECT_EQ(StatusCode::OK_200, res->status);
  6492. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6493. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6494. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6495. }
  6496. TEST_F(ServerTest, HTTPResponseSplitting) {
  6497. auto res = cli_.Get("/http_response_splitting");
  6498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6499. EXPECT_EQ(StatusCode::OK_200, res->status);
  6500. }
  6501. TEST_F(ServerTest, SlowRequest) {
  6502. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6503. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6504. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6505. }
  6506. #if 0
  6507. TEST_F(ServerTest, SlowPost) {
  6508. char buffer[64 * 1024];
  6509. memset(buffer, 0x42, sizeof(buffer));
  6510. auto res = cli_.Post(
  6511. "/slowpost", 64 * 1024 * 1024,
  6512. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6513. auto ret = sink.write(buffer, sizeof(buffer));
  6514. EXPECT_TRUE(ret);
  6515. return true;
  6516. },
  6517. "text/plain");
  6518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6519. EXPECT_EQ(StatusCode::OK_200, res->status);
  6520. }
  6521. TEST_F(ServerTest, SlowPostFail) {
  6522. char buffer[64 * 1024];
  6523. memset(buffer, 0x42, sizeof(buffer));
  6524. cli_.set_write_timeout(std::chrono::seconds(0));
  6525. auto res = cli_.Post(
  6526. "/slowpost", 64 * 1024 * 1024,
  6527. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6528. sink.write(buffer, sizeof(buffer));
  6529. return true;
  6530. },
  6531. "text/plain");
  6532. ASSERT_TRUE(!res);
  6533. EXPECT_EQ(Error::Write, res.error());
  6534. }
  6535. #endif
  6536. TEST_F(ServerTest, Put) {
  6537. auto res = cli_.Put("/put", "PUT", "text/plain");
  6538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6539. EXPECT_EQ(StatusCode::OK_200, res->status);
  6540. EXPECT_EQ("PUT", res->body);
  6541. }
  6542. TEST_F(ServerTest, PutWithContentProvider) {
  6543. auto res = cli_.Put(
  6544. "/put", 3,
  6545. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6546. sink.os << "PUT";
  6547. return true;
  6548. },
  6549. "text/plain");
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::OK_200, res->status);
  6552. EXPECT_EQ("PUT", res->body);
  6553. }
  6554. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6555. auto res = cli_.Post(
  6556. "/post", 42,
  6557. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6558. return false;
  6559. },
  6560. "text/plain");
  6561. ASSERT_TRUE(!res);
  6562. EXPECT_EQ(Error::Canceled, res.error());
  6563. }
  6564. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6565. auto res = cli_.Put(
  6566. "/put",
  6567. [](size_t /*offset*/, DataSink &sink) {
  6568. sink.os << "PUT";
  6569. sink.done();
  6570. return true;
  6571. },
  6572. "text/plain");
  6573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6574. EXPECT_EQ(StatusCode::OK_200, res->status);
  6575. EXPECT_EQ("PUT", res->body);
  6576. }
  6577. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6578. auto res = cli_.Post(
  6579. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6580. "text/plain");
  6581. ASSERT_TRUE(!res);
  6582. EXPECT_EQ(Error::Canceled, res.error());
  6583. }
  6584. TEST_F(ServerTest, PostLoopBack) {
  6585. std::string body;
  6586. auto res = cli_.Post(
  6587. "/post-loopback", 9,
  6588. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6589. EXPECT_EQ(9u, length);
  6590. sink.write("123", 3);
  6591. sink.write("456", 3);
  6592. sink.write("789", 3);
  6593. return true;
  6594. },
  6595. "text/plain",
  6596. [&body](const char *data, size_t data_length) {
  6597. body.append(data, data_length);
  6598. return true;
  6599. });
  6600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6601. EXPECT_EQ(StatusCode::OK_200, res->status);
  6602. EXPECT_EQ("123456789", body);
  6603. }
  6604. TEST_F(ServerTest, PutLoopBack) {
  6605. std::string body;
  6606. auto res = cli_.Put(
  6607. "/put-loopback", 9,
  6608. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6609. EXPECT_EQ(9u, length);
  6610. sink.write("123", 3);
  6611. sink.write("456", 3);
  6612. sink.write("789", 3);
  6613. return true;
  6614. },
  6615. "text/plain",
  6616. [&body](const char *data, size_t data_length) {
  6617. body.append(data, data_length);
  6618. return true;
  6619. });
  6620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6621. EXPECT_EQ(StatusCode::OK_200, res->status);
  6622. EXPECT_EQ("123456789", body);
  6623. }
  6624. TEST_F(ServerTest, PatchLoopBack) {
  6625. std::string body;
  6626. auto res = cli_.Patch(
  6627. "/patch-loopback", 9,
  6628. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6629. EXPECT_EQ(9u, length);
  6630. sink.write("123", 3);
  6631. sink.write("456", 3);
  6632. sink.write("789", 3);
  6633. return true;
  6634. },
  6635. "text/plain",
  6636. [&body](const char *data, size_t data_length) {
  6637. body.append(data, data_length);
  6638. return true;
  6639. });
  6640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6641. EXPECT_EQ(StatusCode::OK_200, res->status);
  6642. EXPECT_EQ("123456789", body);
  6643. }
  6644. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6645. std::string body;
  6646. auto res = cli_.Post(
  6647. "/post-loopback",
  6648. [](size_t /*offset*/, DataSink &sink) {
  6649. sink.write("123", 3);
  6650. sink.write("456", 3);
  6651. sink.write("789", 3);
  6652. sink.done();
  6653. return true;
  6654. },
  6655. "text/plain",
  6656. [&body](const char *data, size_t data_length) {
  6657. body.append(data, data_length);
  6658. return true;
  6659. });
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::OK_200, res->status);
  6662. EXPECT_EQ("123456789", body);
  6663. }
  6664. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6665. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6666. cli_.set_compress(true);
  6667. auto res = cli_.Put(
  6668. "/put", 3,
  6669. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6670. sink.os << "PUT";
  6671. return true;
  6672. },
  6673. "text/plain");
  6674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6675. EXPECT_EQ(StatusCode::OK_200, res->status);
  6676. EXPECT_EQ("PUT", res->body);
  6677. }
  6678. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6679. cli_.set_compress(true);
  6680. auto res = cli_.Post(
  6681. "/post", 42,
  6682. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6683. return false;
  6684. },
  6685. "text/plain");
  6686. ASSERT_TRUE(!res);
  6687. EXPECT_EQ(Error::Canceled, res.error());
  6688. }
  6689. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6690. cli_.set_compress(true);
  6691. auto res = cli_.Put(
  6692. "/put",
  6693. [](size_t /*offset*/, DataSink &sink) {
  6694. sink.os << "PUT";
  6695. sink.done();
  6696. return true;
  6697. },
  6698. "text/plain");
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ(StatusCode::OK_200, res->status);
  6701. EXPECT_EQ("PUT", res->body);
  6702. }
  6703. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6704. cli_.set_compress(true);
  6705. auto res = cli_.Post(
  6706. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6707. "text/plain");
  6708. ASSERT_TRUE(!res);
  6709. EXPECT_EQ(Error::Canceled, res.error());
  6710. }
  6711. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6712. cli_.set_compress(true);
  6713. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6715. EXPECT_EQ(StatusCode::OK_200, res->status);
  6716. EXPECT_EQ(LARGE_DATA, res->body);
  6717. }
  6718. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6719. #ifdef CPPHTTPLIB_SSL_ENABLED
  6720. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6721. Client cli(s.c_str());
  6722. cli.enable_server_certificate_verification(false);
  6723. #else
  6724. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6725. Client cli(s.c_str());
  6726. #endif
  6727. cli.set_compress(true);
  6728. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6730. EXPECT_EQ(StatusCode::OK_200, res->status);
  6731. EXPECT_EQ(LARGE_DATA, res->body);
  6732. // The compressed size should be less than a 10th of the original. May vary
  6733. // depending on the zlib library.
  6734. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6735. static_cast<uint64_t>(10 * 1024 * 1024));
  6736. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6737. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6738. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6739. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6740. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6741. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6742. #endif
  6743. }
  6744. TEST_F(ServerTest, PutContentWithDeflate) {
  6745. cli_.set_compress(false);
  6746. Headers headers;
  6747. headers.emplace("Content-Encoding", "deflate");
  6748. // PUT in deflate format:
  6749. auto res = cli_.Put("/put", headers,
  6750. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6752. EXPECT_EQ(StatusCode::OK_200, res->status);
  6753. EXPECT_EQ("PUT", res->body);
  6754. }
  6755. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6756. Headers headers;
  6757. headers.emplace("Accept-Encoding", "gzip, deflate");
  6758. auto res = cli_.Get("/streamed-chunked", headers);
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. EXPECT_EQ(StatusCode::OK_200, res->status);
  6761. EXPECT_EQ(std::string("123456789"), res->body);
  6762. }
  6763. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6764. Headers headers;
  6765. headers.emplace("Accept-Encoding", "gzip, deflate");
  6766. auto res = cli_.Get("/streamed-chunked2", headers);
  6767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6768. EXPECT_EQ(StatusCode::OK_200, res->status);
  6769. EXPECT_EQ(std::string("123456789"), res->body);
  6770. }
  6771. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6772. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6774. EXPECT_EQ(StatusCode::OK_200, res->status);
  6775. }
  6776. TEST(GzipDecompressor, ChunkedDecompression) {
  6777. std::string data;
  6778. for (size_t i = 0; i < 32 * 1024; ++i) {
  6779. data.push_back(static_cast<char>('a' + i % 26));
  6780. }
  6781. std::string compressed_data;
  6782. {
  6783. httplib::detail::gzip_compressor compressor;
  6784. bool result = compressor.compress(
  6785. data.data(), data.size(),
  6786. /*last=*/true,
  6787. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6788. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6789. compressed_data_size);
  6790. return true;
  6791. });
  6792. ASSERT_TRUE(result);
  6793. }
  6794. std::string decompressed_data;
  6795. {
  6796. httplib::detail::gzip_decompressor decompressor;
  6797. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6798. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6799. size_t chunk_size = 130;
  6800. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6801. chunk_begin += chunk_size) {
  6802. size_t current_chunk_size =
  6803. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6804. bool result = decompressor.decompress(
  6805. compressed_data.data() + chunk_begin, current_chunk_size,
  6806. [&](const char *decompressed_data_chunk,
  6807. size_t decompressed_data_chunk_size) {
  6808. decompressed_data.insert(decompressed_data.size(),
  6809. decompressed_data_chunk,
  6810. decompressed_data_chunk_size);
  6811. return true;
  6812. });
  6813. ASSERT_TRUE(result);
  6814. }
  6815. }
  6816. ASSERT_EQ(data, decompressed_data);
  6817. }
  6818. TEST(GzipDecompressor, DeflateDecompression) {
  6819. std::string original_text = "Raw deflate without gzip";
  6820. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6821. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6822. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6823. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6824. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6825. std::string decompressed_data;
  6826. {
  6827. httplib::detail::gzip_decompressor decompressor;
  6828. bool result = decompressor.decompress(
  6829. compressed_data.data(), compressed_data.size(),
  6830. [&](const char *decompressed_data_chunk,
  6831. size_t decompressed_data_chunk_size) {
  6832. decompressed_data.insert(decompressed_data.size(),
  6833. decompressed_data_chunk,
  6834. decompressed_data_chunk_size);
  6835. return true;
  6836. });
  6837. ASSERT_TRUE(result);
  6838. }
  6839. ASSERT_EQ(original_text, decompressed_data);
  6840. }
  6841. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6842. std::string original_text = "Raw deflate without gzip";
  6843. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6844. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6845. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6846. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6847. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6848. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6849. std::string decompressed_data;
  6850. {
  6851. httplib::detail::gzip_decompressor decompressor;
  6852. bool result = decompressor.decompress(
  6853. compressed_data.data(), compressed_data.size(),
  6854. [&](const char *decompressed_data_chunk,
  6855. size_t decompressed_data_chunk_size) {
  6856. decompressed_data.insert(decompressed_data.size(),
  6857. decompressed_data_chunk,
  6858. decompressed_data_chunk_size);
  6859. return true;
  6860. });
  6861. ASSERT_TRUE(result);
  6862. }
  6863. ASSERT_EQ(original_text, decompressed_data);
  6864. }
  6865. #endif
  6866. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6867. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6868. Headers headers;
  6869. headers.emplace("Accept-Encoding", "br");
  6870. auto res = cli_.Get("/streamed-chunked", headers);
  6871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6872. EXPECT_EQ(StatusCode::OK_200, res->status);
  6873. EXPECT_EQ(std::string("123456789"), res->body);
  6874. }
  6875. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6876. Headers headers;
  6877. headers.emplace("Accept-Encoding", "br");
  6878. auto res = cli_.Get("/streamed-chunked2", headers);
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. EXPECT_EQ(StatusCode::OK_200, res->status);
  6881. EXPECT_EQ(std::string("123456789"), res->body);
  6882. }
  6883. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6884. cli_.set_compress(true);
  6885. auto res = cli_.Put(
  6886. "/put", 3,
  6887. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6888. sink.os << "PUT";
  6889. return true;
  6890. },
  6891. "text/plain");
  6892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6893. EXPECT_EQ(StatusCode::OK_200, res->status);
  6894. EXPECT_EQ("PUT", res->body);
  6895. }
  6896. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6897. cli_.set_compress(true);
  6898. auto res = cli_.Put(
  6899. "/put",
  6900. [](size_t /*offset*/, DataSink &sink) {
  6901. sink.os << "PUT";
  6902. sink.done();
  6903. return true;
  6904. },
  6905. "text/plain");
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. EXPECT_EQ(StatusCode::OK_200, res->status);
  6908. EXPECT_EQ("PUT", res->body);
  6909. }
  6910. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6911. cli_.set_compress(true);
  6912. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6914. EXPECT_EQ(StatusCode::OK_200, res->status);
  6915. EXPECT_EQ(LARGE_DATA, res->body);
  6916. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6917. }
  6918. #endif
  6919. TEST_F(ServerTest, Patch) {
  6920. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6922. EXPECT_EQ(StatusCode::OK_200, res->status);
  6923. EXPECT_EQ("PATCH", res->body);
  6924. }
  6925. TEST_F(ServerTest, Delete) {
  6926. auto res = cli_.Delete("/delete");
  6927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6928. EXPECT_EQ(StatusCode::OK_200, res->status);
  6929. EXPECT_EQ("DELETE", res->body);
  6930. }
  6931. TEST_F(ServerTest, DeleteContentReceiver) {
  6932. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6934. EXPECT_EQ(StatusCode::OK_200, res->status);
  6935. EXPECT_EQ("content", res->body);
  6936. }
  6937. TEST_F(ServerTest, Options) {
  6938. auto res = cli_.Options("*");
  6939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6940. EXPECT_EQ(StatusCode::OK_200, res->status);
  6941. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6942. EXPECT_TRUE(res->body.empty());
  6943. }
  6944. TEST_F(ServerTest, URL) {
  6945. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. EXPECT_EQ(StatusCode::OK_200, res->status);
  6948. }
  6949. TEST_F(ServerTest, ArrayParam) {
  6950. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6952. EXPECT_EQ(StatusCode::OK_200, res->status);
  6953. }
  6954. TEST_F(ServerTest, ArrayParamValues) {
  6955. auto res =
  6956. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6958. EXPECT_EQ(StatusCode::OK_200, res->status);
  6959. }
  6960. TEST_F(ServerTest, NoMultipleHeaders) {
  6961. Headers headers = {{"Content-Length", "5"}};
  6962. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6963. "text/plain");
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. EXPECT_EQ(StatusCode::OK_200, res->status);
  6966. }
  6967. TEST_F(ServerTest, PostContentReceiver) {
  6968. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6970. ASSERT_EQ(StatusCode::OK_200, res->status);
  6971. ASSERT_EQ("content", res->body);
  6972. }
  6973. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6974. UploadFormDataItems items = {
  6975. {"text1", "text default", "", ""},
  6976. {"text2", "aωb", "", ""},
  6977. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6978. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6979. {"file3", "", "", "application/octet-stream"},
  6980. };
  6981. auto res = cli_.Post("/content_receiver", items);
  6982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6983. EXPECT_EQ(StatusCode::OK_200, res->status);
  6984. }
  6985. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6986. UploadFormDataItems items = {
  6987. {"text1", "text default", "", ""},
  6988. {"text2", "aωb", "", ""},
  6989. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6990. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6991. {"file3", "", "", "application/octet-stream"},
  6992. };
  6993. auto boundary = std::string("+++++");
  6994. std::string body;
  6995. for (const auto &item : items) {
  6996. body += "--" + boundary + "\r\n";
  6997. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6998. if (!item.filename.empty()) {
  6999. body += "; filename=\"" + item.filename + "\"";
  7000. }
  7001. body += "\r\n";
  7002. if (!item.content_type.empty()) {
  7003. body += "Content-Type: " + item.content_type + "\r\n";
  7004. }
  7005. body += "\r\n";
  7006. body += item.content + "\r\n";
  7007. }
  7008. body += "--" + boundary + "--\r\n";
  7009. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7010. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ(StatusCode::OK_200, res->status);
  7013. }
  7014. TEST(MultipartFormDataTest, FieldEscaping) {
  7015. Server svr;
  7016. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7017. const ContentReader &content_reader) {
  7018. ASSERT_TRUE(req.is_multipart_form_data());
  7019. std::vector<FormData> received;
  7020. content_reader(
  7021. [&](const FormData &file) {
  7022. received.push_back(file);
  7023. return true;
  7024. },
  7025. [&](const char *data, size_t data_length) {
  7026. received.back().content.append(data, data_length);
  7027. return true;
  7028. });
  7029. // '"', CR and LF in names and filenames are escaped following the
  7030. // WHATWG HTML standard, so each part still parses as a single part
  7031. // with no injected headers. Content types get CR/LF escaped too,
  7032. // while '"' (legal there, e.g. quoted charset) is preserved.
  7033. ASSERT_EQ(4U, received.size());
  7034. EXPECT_EQ("na%22me", received[0].name);
  7035. EXPECT_EQ("quoted name", received[0].content);
  7036. EXPECT_EQ("file", received[1].name);
  7037. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7038. received[1].filename);
  7039. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7040. EXPECT_EQ("injected", received[1].content);
  7041. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7042. EXPECT_EQ("my%22file.txt", received[2].filename);
  7043. EXPECT_EQ("cr lf name", received[2].content);
  7044. EXPECT_EQ("typed", received[3].name);
  7045. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7046. received[3].content_type);
  7047. EXPECT_EQ("typed content", received[3].content);
  7048. });
  7049. auto port = svr.bind_to_any_port("localhost");
  7050. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7051. auto se = detail::scope_exit([&] {
  7052. svr.stop();
  7053. t.join();
  7054. ASSERT_FALSE(svr.is_running());
  7055. });
  7056. svr.wait_until_ready();
  7057. Client cli("localhost", port);
  7058. UploadFormDataItems items = {
  7059. {"na\"me", "quoted name", "", ""},
  7060. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7061. "application/octet-stream"},
  7062. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7063. {"typed", "typed content", "",
  7064. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7065. };
  7066. auto res = cli.Post("/post", items);
  7067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7068. EXPECT_EQ(StatusCode::OK_200, res->status);
  7069. }
  7070. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7071. const UploadFormDataItems items = {
  7072. {"name1", "Content 1", "", ""},
  7073. {"name2", "Content 2", "file2.txt", "text/plain"},
  7074. };
  7075. Server svr;
  7076. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7077. const ContentReader &content_reader) {
  7078. ASSERT_TRUE(req.is_multipart_form_data());
  7079. std::vector<FormData> received;
  7080. content_reader(
  7081. [&](const FormData &file) {
  7082. received.push_back(file);
  7083. return true;
  7084. },
  7085. [&](const char *data, size_t data_length) {
  7086. received.back().content.append(data, data_length);
  7087. return true;
  7088. });
  7089. ASSERT_EQ(2U, received.size());
  7090. EXPECT_EQ("name1", received[0].name);
  7091. EXPECT_EQ("Content 1", received[0].content);
  7092. EXPECT_EQ("name2", received[1].name);
  7093. EXPECT_EQ("Content 2", received[1].content);
  7094. EXPECT_EQ("file2.txt", received[1].filename);
  7095. EXPECT_EQ("text/plain", received[1].content_type);
  7096. });
  7097. auto port = svr.bind_to_any_port("localhost");
  7098. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7099. auto se = detail::scope_exit([&] {
  7100. svr.stop();
  7101. t.join();
  7102. ASSERT_FALSE(svr.is_running());
  7103. });
  7104. svr.wait_until_ready();
  7105. Client cli("localhost", port);
  7106. // Whole-body serialization with a generated boundary
  7107. {
  7108. MultipartFormDataWriter writer;
  7109. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7110. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7111. writer.content_type());
  7112. auto body = writer.serialize(items);
  7113. EXPECT_EQ(body.size(), writer.content_length(items));
  7114. auto res = cli.Post("/post", body, writer.content_type());
  7115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7116. EXPECT_EQ(StatusCode::OK_200, res->status);
  7117. }
  7118. // Per-part framing with a custom boundary via a content provider
  7119. {
  7120. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7121. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7122. MultipartFormDataWriter writer("custom-boundary_123");
  7123. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7124. std::string body;
  7125. for (const auto &item : items) {
  7126. body += writer.item_begin(item);
  7127. body += item.content;
  7128. body += MultipartFormDataWriter::item_end();
  7129. }
  7130. body += writer.finish();
  7131. EXPECT_EQ(body.size(), writer.content_length(items));
  7132. auto res = cli.Post(
  7133. "/post", body.size(),
  7134. [&](size_t offset, size_t length, DataSink &sink) {
  7135. sink.write(body.data() + offset, length);
  7136. return true;
  7137. },
  7138. writer.content_type());
  7139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7140. EXPECT_EQ(StatusCode::OK_200, res->status);
  7141. }
  7142. }
  7143. TEST_F(ServerTest, PostContentReceiverGzip) {
  7144. cli_.set_compress(true);
  7145. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7147. ASSERT_EQ(StatusCode::OK_200, res->status);
  7148. ASSERT_EQ("content", res->body);
  7149. }
  7150. TEST_F(ServerTest, PutContentReceiver) {
  7151. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7153. ASSERT_EQ(StatusCode::OK_200, res->status);
  7154. ASSERT_EQ("content", res->body);
  7155. }
  7156. TEST_F(ServerTest, PatchContentReceiver) {
  7157. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7159. ASSERT_EQ(StatusCode::OK_200, res->status);
  7160. ASSERT_EQ("content", res->body);
  7161. }
  7162. template <typename ClientType>
  7163. void TestWithHeadersAndContentReceiver(
  7164. ClientType &cli,
  7165. std::function<Result(ClientType &, const std::string &, const Headers &,
  7166. const std::string &, const std::string &,
  7167. ContentReceiver, DownloadProgress)>
  7168. request_func) {
  7169. Headers headers;
  7170. headers.emplace("X-Custom-Header", "test-value");
  7171. std::string received_body;
  7172. auto res = request_func(
  7173. cli, "/content_receiver", headers, "content", "application/json",
  7174. [&](const char *data, size_t data_length) {
  7175. received_body.append(data, data_length);
  7176. return true;
  7177. },
  7178. nullptr);
  7179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7180. EXPECT_EQ(StatusCode::OK_200, res->status);
  7181. EXPECT_EQ("content", received_body);
  7182. }
  7183. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7184. #ifdef CPPHTTPLIB_SSL_ENABLED
  7185. using ClientT = SSLClient;
  7186. #else
  7187. using ClientT = Client;
  7188. #endif
  7189. TestWithHeadersAndContentReceiver<ClientT>(
  7190. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7191. const std::string &body, const std::string &content_type,
  7192. ContentReceiver receiver, DownloadProgress progress) {
  7193. return cli.Post(path, headers, body, content_type, receiver, progress);
  7194. });
  7195. }
  7196. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7197. #ifdef CPPHTTPLIB_SSL_ENABLED
  7198. using ClientT = SSLClient;
  7199. #else
  7200. using ClientT = Client;
  7201. #endif
  7202. TestWithHeadersAndContentReceiver<ClientT>(
  7203. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7204. const std::string &body, const std::string &content_type,
  7205. ContentReceiver receiver, DownloadProgress progress) {
  7206. return cli.Put(path, headers, body, content_type, receiver, progress);
  7207. });
  7208. }
  7209. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7210. #ifdef CPPHTTPLIB_SSL_ENABLED
  7211. using ClientT = SSLClient;
  7212. #else
  7213. using ClientT = Client;
  7214. #endif
  7215. TestWithHeadersAndContentReceiver<ClientT>(
  7216. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7217. const std::string &body, const std::string &content_type,
  7218. ContentReceiver receiver, DownloadProgress progress) {
  7219. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7220. });
  7221. }
  7222. template <typename ClientType>
  7223. void TestWithHeadersAndContentReceiverWithProgress(
  7224. ClientType &cli,
  7225. std::function<Result(ClientType &, const std::string &, const Headers &,
  7226. const std::string &, const std::string &,
  7227. ContentReceiver, DownloadProgress)>
  7228. request_func) {
  7229. Headers headers;
  7230. headers.emplace("X-Test-Header", "progress-test");
  7231. std::string received_body;
  7232. auto progress_called = false;
  7233. auto res = request_func(
  7234. cli, "/content_receiver", headers, "content", "text/plain",
  7235. [&](const char *data, size_t data_length) {
  7236. received_body.append(data, data_length);
  7237. return true;
  7238. },
  7239. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7240. progress_called = true;
  7241. return true;
  7242. });
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ("content", received_body);
  7246. EXPECT_TRUE(progress_called);
  7247. }
  7248. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7249. #ifdef CPPHTTPLIB_SSL_ENABLED
  7250. using ClientT = SSLClient;
  7251. #else
  7252. using ClientT = Client;
  7253. #endif
  7254. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7255. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7256. const std::string &body, const std::string &content_type,
  7257. ContentReceiver receiver, DownloadProgress progress) {
  7258. return cli.Post(path, headers, body, content_type, receiver, progress);
  7259. });
  7260. }
  7261. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7262. #ifdef CPPHTTPLIB_SSL_ENABLED
  7263. using ClientT = SSLClient;
  7264. #else
  7265. using ClientT = Client;
  7266. #endif
  7267. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7268. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7269. const std::string &body, const std::string &content_type,
  7270. ContentReceiver receiver, DownloadProgress progress) {
  7271. return cli.Put(path, headers, body, content_type, receiver, progress);
  7272. });
  7273. }
  7274. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7275. #ifdef CPPHTTPLIB_SSL_ENABLED
  7276. using ClientT = SSLClient;
  7277. #else
  7278. using ClientT = Client;
  7279. #endif
  7280. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7281. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7282. const std::string &body, const std::string &content_type,
  7283. ContentReceiver receiver, DownloadProgress progress) {
  7284. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7285. });
  7286. }
  7287. template <typename ClientType>
  7288. void TestWithHeadersAndContentReceiverError(
  7289. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7290. const Headers &, const std::string &,
  7291. const std::string &, ContentReceiver)>
  7292. request_func) {
  7293. Headers headers;
  7294. headers.emplace("X-Error-Test", "true");
  7295. std::string received_body;
  7296. auto receiver_failed = false;
  7297. auto res =
  7298. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7299. [&](const char *data, size_t data_length) {
  7300. received_body.append(data, data_length);
  7301. receiver_failed = true;
  7302. return false;
  7303. });
  7304. ASSERT_FALSE(res);
  7305. EXPECT_TRUE(receiver_failed);
  7306. }
  7307. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7308. #ifdef CPPHTTPLIB_SSL_ENABLED
  7309. using ClientT = SSLClient;
  7310. #else
  7311. using ClientT = Client;
  7312. #endif
  7313. TestWithHeadersAndContentReceiverError<ClientT>(
  7314. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7315. const std::string &body, const std::string &content_type,
  7316. ContentReceiver receiver) {
  7317. return cli.Post(path, headers, body, content_type, receiver);
  7318. });
  7319. }
  7320. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7321. #ifdef CPPHTTPLIB_SSL_ENABLED
  7322. using ClientT = SSLClient;
  7323. #else
  7324. using ClientT = Client;
  7325. #endif
  7326. TestWithHeadersAndContentReceiverError<ClientT>(
  7327. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7328. const std::string &body, const std::string &content_type,
  7329. ContentReceiver receiver) {
  7330. return cli.Put(path, headers, body, content_type, receiver);
  7331. });
  7332. }
  7333. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7334. #ifdef CPPHTTPLIB_SSL_ENABLED
  7335. using ClientT = SSLClient;
  7336. #else
  7337. using ClientT = Client;
  7338. #endif
  7339. TestWithHeadersAndContentReceiverError<ClientT>(
  7340. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7341. const std::string &body, const std::string &content_type,
  7342. ContentReceiver receiver) {
  7343. return cli.Patch(path, headers, body, content_type, receiver);
  7344. });
  7345. }
  7346. TEST_F(ServerTest, PostQueryStringAndBody) {
  7347. auto res =
  7348. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7350. ASSERT_EQ(StatusCode::OK_200, res->status);
  7351. }
  7352. TEST_F(ServerTest, HTTP2Magic) {
  7353. Request req;
  7354. req.method = "PRI";
  7355. req.path = "*";
  7356. req.body = "SM";
  7357. auto res = std::make_shared<Response>();
  7358. auto error = Error::Success;
  7359. auto ret = cli_.send(req, *res, error);
  7360. ASSERT_TRUE(ret);
  7361. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7362. }
  7363. TEST_F(ServerTest, KeepAlive) {
  7364. auto res = cli_.Get("/hi");
  7365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7366. EXPECT_EQ(StatusCode::OK_200, res->status);
  7367. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7368. EXPECT_EQ("Hello World!", res->body);
  7369. res = cli_.Get("/hi");
  7370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7371. EXPECT_EQ(StatusCode::OK_200, res->status);
  7372. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7373. EXPECT_EQ("Hello World!", res->body);
  7374. res = cli_.Get("/hi");
  7375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7376. EXPECT_EQ(StatusCode::OK_200, res->status);
  7377. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7378. EXPECT_EQ("Hello World!", res->body);
  7379. res = cli_.Get("/not-exist");
  7380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7381. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7382. res = cli_.Post("/empty", "", "text/plain");
  7383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7384. EXPECT_EQ(StatusCode::OK_200, res->status);
  7385. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7386. EXPECT_EQ("empty", res->body);
  7387. EXPECT_EQ("close", res->get_header_value("Connection"));
  7388. res = cli_.Post(
  7389. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7390. "text/plain");
  7391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7392. EXPECT_EQ(StatusCode::OK_200, res->status);
  7393. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7394. EXPECT_EQ("empty", res->body);
  7395. cli_.set_keep_alive(false);
  7396. res = cli_.Get("/last-request");
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::OK_200, res->status);
  7399. EXPECT_EQ("close", res->get_header_value("Connection"));
  7400. }
  7401. TEST_F(ServerTest, TooManyRedirect) {
  7402. cli_.set_follow_location(true);
  7403. auto res = cli_.Get("/redirect/0");
  7404. ASSERT_TRUE(!res);
  7405. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7406. }
  7407. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7408. Request req;
  7409. req.method = "FOOBAR";
  7410. req.path = "/hi";
  7411. cli_.set_keep_alive(true);
  7412. auto res = cli_.send(req);
  7413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7414. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7415. EXPECT_EQ("close", res->get_header_value("Connection"));
  7416. EXPECT_FALSE(cli_.is_socket_open());
  7417. }
  7418. TEST_F(ServerTest, CustomRouteReadsBody) {
  7419. const std::string xml =
  7420. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7421. Request req;
  7422. req.method = "PROPFIND";
  7423. req.path = "/dav/dir";
  7424. req.set_header("Depth", "1");
  7425. req.body = xml;
  7426. auto res = cli_.send(req);
  7427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7428. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7429. EXPECT_EQ(xml, res->body);
  7430. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7431. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7432. }
  7433. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7434. Request req;
  7435. req.method = "PROPFIND";
  7436. req.path = "/dav/42";
  7437. auto res = cli_.send(req);
  7438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7439. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7440. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7441. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7442. }
  7443. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7444. Request req;
  7445. req.method = "PROPFIND";
  7446. req.path = "/dav-re/123";
  7447. auto res = cli_.send(req);
  7448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7449. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7450. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7451. }
  7452. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7453. Request req;
  7454. req.method = "MKCOL";
  7455. req.path = "/dav-mkcol";
  7456. auto res = cli_.send(req);
  7457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7458. EXPECT_EQ(StatusCode::Created_201, res->status);
  7459. }
  7460. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7461. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7462. Request req;
  7463. req.method = "REPORT";
  7464. req.path = "/dav-report";
  7465. req.body = xml;
  7466. auto res = cli_.send(req);
  7467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7468. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7469. EXPECT_EQ(xml, res->body);
  7470. }
  7471. // A content reader route must fire even when the request carries no body,
  7472. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7473. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7474. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7475. Request req;
  7476. req.method = "REPORT";
  7477. req.path = "/dav-report";
  7478. auto res = cli_.send(req);
  7479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7480. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7481. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7482. }
  7483. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7484. Request req;
  7485. req.method = "PROPFIND";
  7486. req.path = "/not-dav";
  7487. auto res = cli_.send(req);
  7488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7489. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7490. }
  7491. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7492. Request req;
  7493. req.method = "UNLOCK";
  7494. req.path = "/dav/dir";
  7495. cli_.set_keep_alive(true);
  7496. auto res = cli_.send(req);
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7499. EXPECT_EQ("close", res->get_header_value("Connection"));
  7500. EXPECT_FALSE(cli_.is_socket_open());
  7501. }
  7502. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7503. // The mount point serves this path, but only for GET and HEAD.
  7504. auto get_res = cli_.Get("/dir/index.html");
  7505. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7506. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7507. Request req;
  7508. req.method = "PROPFIND";
  7509. req.path = "/dir/index.html";
  7510. auto res = cli_.send(req);
  7511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7513. }
  7514. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7515. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7516. cli_.set_keep_alive(true);
  7517. for (auto i = 0; i < 2; i++) {
  7518. Request req;
  7519. req.method = "PROPFIND";
  7520. req.path = "/dav/dir";
  7521. req.body = xml;
  7522. auto res = cli_.send(req);
  7523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7524. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7525. EXPECT_EQ(xml, res->body);
  7526. EXPECT_TRUE(cli_.is_socket_open());
  7527. }
  7528. // A built-in method must still be served on the same connection.
  7529. cli_.set_keep_alive(false);
  7530. auto res = cli_.Get("/hi");
  7531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7532. EXPECT_EQ(StatusCode::OK_200, res->status);
  7533. EXPECT_EQ("close", res->get_header_value("Connection"));
  7534. }
  7535. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7536. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7537. Request req;
  7538. req.method = "PROPFIND";
  7539. req.path = "/dav/dir";
  7540. req.set_header("Expect", "100-continue");
  7541. req.body = xml;
  7542. auto res = cli_.send(req);
  7543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7544. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7545. EXPECT_EQ(xml, res->body);
  7546. }
  7547. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7548. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7549. TEST_F(ServerTest, Gzip) {
  7550. Headers headers;
  7551. headers.emplace("Accept-Encoding", "gzip, deflate");
  7552. auto res = cli_.Get("/compress", headers);
  7553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7554. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7556. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7557. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7558. "7890123456789012345678901234567890",
  7559. res->body);
  7560. EXPECT_EQ(StatusCode::OK_200, res->status);
  7561. }
  7562. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7563. Headers headers;
  7564. headers.emplace("Accept-Encoding", "gzip, deflate");
  7565. auto res = cli_.Get("/compress-with-charset", headers);
  7566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7567. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7568. EXPECT_EQ("application/json; charset=utf-8",
  7569. res->get_header_value("Content-Type"));
  7570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7571. "7890123456789012345678901234567890",
  7572. res->body);
  7573. EXPECT_EQ(StatusCode::OK_200, res->status);
  7574. }
  7575. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7576. Headers headers;
  7577. headers.emplace("Accept-Encoding", "");
  7578. auto res = cli_.Get("/compress", headers);
  7579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7580. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7581. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7582. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7583. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7584. "7890123456789012345678901234567890",
  7585. res->body);
  7586. EXPECT_EQ(StatusCode::OK_200, res->status);
  7587. }
  7588. TEST_F(ServerTest, GzipWithContentReceiver) {
  7589. Headers headers;
  7590. headers.emplace("Accept-Encoding", "gzip, deflate");
  7591. std::string body;
  7592. auto res = cli_.Get("/compress", headers,
  7593. [&](const char *data, uint64_t data_length) {
  7594. EXPECT_EQ(100U, data_length);
  7595. body.append(data, data_length);
  7596. return true;
  7597. });
  7598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7599. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7600. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7601. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7602. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7603. "7890123456789012345678901234567890",
  7604. body);
  7605. EXPECT_EQ(StatusCode::OK_200, res->status);
  7606. }
  7607. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7608. Headers headers;
  7609. headers.emplace("Accept-Encoding", "gzip, deflate");
  7610. cli_.set_decompress(false);
  7611. auto res = cli_.Get("/compress", headers);
  7612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7613. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7614. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7615. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7616. EXPECT_EQ(33U, res->body.size());
  7617. EXPECT_EQ(StatusCode::OK_200, res->status);
  7618. }
  7619. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7620. Headers headers;
  7621. headers.emplace("Accept-Encoding", "");
  7622. std::string body;
  7623. auto res = cli_.Get("/compress", headers,
  7624. [&](const char *data, uint64_t data_length) {
  7625. EXPECT_EQ(100U, data_length);
  7626. body.append(data, data_length);
  7627. return true;
  7628. });
  7629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7630. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7631. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7632. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7633. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7634. "7890123456789012345678901234567890",
  7635. body);
  7636. EXPECT_EQ(StatusCode::OK_200, res->status);
  7637. }
  7638. TEST_F(ServerTest, NoGzip) {
  7639. Headers headers;
  7640. headers.emplace("Accept-Encoding", "gzip, deflate");
  7641. auto res = cli_.Get("/nocompress", headers);
  7642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7643. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7644. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7645. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7646. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7647. "7890123456789012345678901234567890",
  7648. res->body);
  7649. EXPECT_EQ(StatusCode::OK_200, res->status);
  7650. }
  7651. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7652. Headers headers;
  7653. headers.emplace("Accept-Encoding", "gzip, deflate");
  7654. std::string body;
  7655. auto res = cli_.Get("/nocompress", headers,
  7656. [&](const char *data, uint64_t data_length) {
  7657. EXPECT_EQ(100U, data_length);
  7658. body.append(data, data_length);
  7659. return true;
  7660. });
  7661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7662. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7663. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7664. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7665. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7666. "7890123456789012345678901234567890",
  7667. body);
  7668. EXPECT_EQ(StatusCode::OK_200, res->status);
  7669. }
  7670. TEST_F(ServerTest, MultipartFormDataGzip) {
  7671. UploadFormDataItems items = {
  7672. {"key1", "test", "", ""},
  7673. {"key2", "--abcdefg123", "", ""},
  7674. };
  7675. cli_.set_compress(true);
  7676. auto res = cli_.Post("/compress-multipart", items);
  7677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7678. EXPECT_EQ(StatusCode::OK_200, res->status);
  7679. }
  7680. #endif
  7681. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7682. // Static file compression is opt-in, so these run their own server rather than
  7683. // flipping it on for the shared ServerTest fixture, which would silently
  7684. // rewrite what every other static file test is asserting.
  7685. class StaticFileCompressionTest : public ::testing::Test {
  7686. protected:
  7687. void TearDown() override {
  7688. if (t_.joinable()) {
  7689. svr_.stop();
  7690. t_.join();
  7691. }
  7692. }
  7693. int start(const std::function<void(Server &)> &configure = nullptr) {
  7694. // Serves the same tree as a directory of build-time compressed assets
  7695. // would be served: the mount point names the coding the files are already
  7696. // stored in. Registered before "/" so it is the one that matches.
  7697. svr_.set_mount_point("/pre-encoded", "./www",
  7698. {{"Content-Encoding", "gzip"}});
  7699. svr_.set_mount_point("/", "./www");
  7700. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7701. res.set_file_content("./www/dir/index.html", "text/html");
  7702. });
  7703. svr_.Get("/pre-encoded-file-content",
  7704. [](const Request & /*req*/, Response &res) {
  7705. res.set_header("Content-Encoding", "gzip");
  7706. res.set_file_content("./www/dir/index.html", "text/html");
  7707. });
  7708. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7709. res.set_content_provider(
  7710. 6, "text/plain",
  7711. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7712. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7713. return true;
  7714. });
  7715. });
  7716. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7717. res.set_content_provider(
  7718. 1000, "text/plain",
  7719. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7720. if (offset < 100) {
  7721. std::string data(100, 'A');
  7722. sink.write(data.data(), data.size());
  7723. return true;
  7724. }
  7725. std::this_thread::sleep_for(std::chrono::seconds(2));
  7726. std::string data(900, 'B');
  7727. sink.write(data.data(), data.size());
  7728. return true;
  7729. });
  7730. });
  7731. if (configure) { configure(svr_); }
  7732. auto port = svr_.bind_to_any_port(HOST);
  7733. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7734. svr_.wait_until_ready();
  7735. return port;
  7736. }
  7737. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7738. // Every file under ./www except 1MB.txt is smaller than the default
  7739. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7740. // it out of the way.
  7741. static void enable_without_floor(Server &svr) {
  7742. svr.set_static_file_compression(true);
  7743. svr.set_static_file_compression_min_length(0);
  7744. }
  7745. Server svr_;
  7746. std::thread t_;
  7747. };
  7748. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7749. auto port = start();
  7750. Client cli(HOST, port);
  7751. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7755. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7756. EXPECT_EQ(1048576U, res->body.size());
  7757. }
  7758. TEST_F(StaticFileCompressionTest, MountPoint) {
  7759. auto port = start(enable);
  7760. Client cli(HOST, port);
  7761. cli.set_decompress(false);
  7762. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7764. EXPECT_EQ(StatusCode::OK_200, res->status);
  7765. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7766. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7767. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7768. // The response stays self-delimiting: a length, not a chunked body.
  7769. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7770. EXPECT_EQ(std::to_string(res->body.size()),
  7771. res->get_header_value("Content-Length"));
  7772. EXPECT_LT(res->body.size(), 1048576U);
  7773. EXPECT_FALSE(res->body.empty());
  7774. }
  7775. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7776. auto port = start(enable);
  7777. Client cli(HOST, port);
  7778. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7780. EXPECT_EQ(StatusCode::OK_200, res->status);
  7781. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7782. EXPECT_EQ(1048576U, res->body.size());
  7783. }
  7784. TEST_F(StaticFileCompressionTest, FileContent) {
  7785. auto port = start(enable_without_floor);
  7786. Client cli(HOST, port);
  7787. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7789. EXPECT_EQ(StatusCode::OK_200, res->status);
  7790. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7791. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7792. EXPECT_EQ(104U, res->body.size());
  7793. }
  7794. // A handler that serves an already-encoded file names the coding itself. The
  7795. // file-backed path decided its coding from Accept-Encoding and the content
  7796. // type alone, so it compressed the stored bytes a second time and appended a
  7797. // second Content-Encoding field line.
  7798. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7799. auto port = start(enable_without_floor);
  7800. Client cli(HOST, port);
  7801. cli.set_decompress(false);
  7802. auto res = cli.Get("/pre-encoded-file-content",
  7803. Headers{{"Accept-Encoding", "gzip"}});
  7804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7805. EXPECT_EQ(StatusCode::OK_200, res->status);
  7806. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7807. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7808. // Vary belongs to a coding the server chose, and it chose none here.
  7809. EXPECT_FALSE(res->has_header("Vary"));
  7810. // The file travels exactly as it is stored on disk.
  7811. EXPECT_EQ(104U, res->body.size());
  7812. }
  7813. // The 1MB file clears the default floor, so this one runs the configuration a
  7814. // deployment would actually have.
  7815. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7816. auto port = start(enable);
  7817. Client cli(HOST, port);
  7818. cli.set_decompress(false);
  7819. auto res =
  7820. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7822. EXPECT_EQ(StatusCode::OK_200, res->status);
  7823. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7824. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7825. EXPECT_FALSE(res->has_header("Vary"));
  7826. EXPECT_EQ(1048576U, res->body.size());
  7827. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7828. }
  7829. TEST_F(StaticFileCompressionTest, Head) {
  7830. auto port = start(enable);
  7831. Client cli(HOST, port);
  7832. cli.set_decompress(false);
  7833. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7834. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7835. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7837. EXPECT_EQ(StatusCode::OK_200, res->status);
  7838. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7839. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7840. // HEAD still reports the size a GET would return.
  7841. EXPECT_EQ(get->get_header_value("Content-Length"),
  7842. res->get_header_value("Content-Length"));
  7843. EXPECT_TRUE(res->body.empty());
  7844. }
  7845. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7846. auto port = start(enable);
  7847. Client cli(HOST, port);
  7848. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7849. {"Accept-Encoding", "gzip"}});
  7850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7851. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7852. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7853. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7854. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7855. EXPECT_EQ("cd", res->body);
  7856. }
  7857. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7858. auto port = start(enable);
  7859. Client cli(HOST, port);
  7860. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7862. EXPECT_EQ(StatusCode::OK_200, res->status);
  7863. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7864. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7865. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7866. }
  7867. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7868. auto port = start(enable);
  7869. Client cli(HOST, port);
  7870. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::OK_200, res->status);
  7873. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7874. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7875. EXPECT_TRUE(res->body.empty());
  7876. }
  7877. TEST_F(StaticFileCompressionTest, MinLength) {
  7878. auto port = start(enable);
  7879. Client cli(HOST, port);
  7880. // 104 bytes, well under the default floor. Compressing it would add the
  7881. // gzip header and trailer to a body that already fits in one packet.
  7882. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7884. EXPECT_EQ(StatusCode::OK_200, res->status);
  7885. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7886. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7887. }
  7888. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7889. auto port = start([](Server &svr) {
  7890. svr.set_static_file_compression(true);
  7891. svr.set_static_file_compression_min_length(1);
  7892. });
  7893. Client cli(HOST, port);
  7894. cli.set_decompress(false);
  7895. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7897. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7898. // A 9-byte file comes back larger than it went in, because gzip's header and
  7899. // trailer outweigh anything deflate can save. That is the end of the range
  7900. // the floor exists to keep out.
  7901. EXPECT_GT(res->body.size(), 9U);
  7902. }
  7903. TEST_F(StaticFileCompressionTest, MaxLength) {
  7904. auto port = start([](Server &svr) {
  7905. svr.set_static_file_compression(true);
  7906. svr.set_static_file_compression_min_length(0);
  7907. svr.set_static_file_compression_max_length(1024);
  7908. });
  7909. Client cli(HOST, port);
  7910. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7911. // defines `small` as a macro on Windows.
  7912. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7913. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7914. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7915. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7916. // Under it: compressed.
  7917. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7918. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7919. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7920. }
  7921. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7922. auto port = start(enable_without_floor);
  7923. Client cli(HOST, port);
  7924. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7925. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7926. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7927. auto identity_etag = identity->get_header_value("ETag");
  7928. ASSERT_FALSE(identity_etag.empty());
  7929. auto gzipped =
  7930. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7931. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7932. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7933. auto gzip_etag = gzipped->get_header_value("ETag");
  7934. ASSERT_FALSE(gzip_etag.empty());
  7935. // Two representations, two validators.
  7936. EXPECT_NE(identity_etag, gzip_etag);
  7937. // Each one revalidates against the request that would produce it...
  7938. auto fresh =
  7939. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7940. {"If-None-Match", gzip_etag}});
  7941. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7942. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7943. auto fresh_identity =
  7944. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7945. {"If-None-Match", identity_etag}});
  7946. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7947. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7948. // ...and not against the other representation.
  7949. auto crossed =
  7950. cli.Get("/dir/index.html",
  7951. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7952. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7953. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7954. }
  7955. // The opt-in covers responses the server reads off disk itself. A caller's own
  7956. // known-length provider keeps its Content-Length and, more importantly, keeps
  7957. // delivering incrementally: routing it through a compressor would hold every
  7958. // write back until zlib's window filled.
  7959. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7960. auto port = start(enable);
  7961. Client cli(HOST, port);
  7962. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7966. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7967. EXPECT_EQ("aaabbb", res->body);
  7968. }
  7969. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7970. auto port = start(enable);
  7971. Client cli(HOST, port);
  7972. cli.set_read_timeout(1, 0);
  7973. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7974. Headers{{"Accept-Encoding", "gzip"}});
  7975. ASSERT_TRUE(handle.is_valid());
  7976. // The provider writes 100 bytes and then stalls for longer than the read
  7977. // timeout. Those first bytes have to arrive anyway: run the response through
  7978. // a compressor and zlib holds them until its window fills, so the read would
  7979. // come back empty instead.
  7980. char buf[256];
  7981. auto n = handle.read(buf, sizeof(buf));
  7982. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7983. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7984. }
  7985. #endif
  7986. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7987. TEST_F(ServerTest, Brotli) {
  7988. Headers headers;
  7989. headers.emplace("Accept-Encoding", "br");
  7990. auto res = cli_.Get("/compress", headers);
  7991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7992. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7994. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7995. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7996. "7890123456789012345678901234567890",
  7997. res->body);
  7998. EXPECT_EQ(StatusCode::OK_200, res->status);
  7999. }
  8000. #endif
  8001. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8002. TEST_F(ServerTest, Zstd) {
  8003. Headers headers;
  8004. headers.emplace("Accept-Encoding", "zstd");
  8005. auto res = cli_.Get("/compress", headers);
  8006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8007. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8008. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8009. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8010. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8011. "7890123456789012345678901234567890",
  8012. res->body);
  8013. EXPECT_EQ(StatusCode::OK_200, res->status);
  8014. }
  8015. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8016. Headers headers;
  8017. headers.emplace("Accept-Encoding", "");
  8018. auto res = cli_.Get("/compress", headers);
  8019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8020. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8021. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8022. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8023. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8024. "7890123456789012345678901234567890",
  8025. res->body);
  8026. EXPECT_EQ(StatusCode::OK_200, res->status);
  8027. }
  8028. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8029. Headers headers;
  8030. headers.emplace("Accept-Encoding", "zstd");
  8031. std::string body;
  8032. auto res = cli_.Get("/compress", headers,
  8033. [&](const char *data, uint64_t data_length) {
  8034. EXPECT_EQ(100U, data_length);
  8035. body.append(data, data_length);
  8036. return true;
  8037. });
  8038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8039. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8040. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8041. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8042. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8043. "7890123456789012345678901234567890",
  8044. body);
  8045. EXPECT_EQ(StatusCode::OK_200, res->status);
  8046. }
  8047. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8048. Headers headers;
  8049. headers.emplace("Accept-Encoding", "zstd");
  8050. cli_.set_decompress(false);
  8051. auto res = cli_.Get("/compress", headers);
  8052. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8053. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8054. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8055. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8057. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8058. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8059. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8060. EXPECT_EQ(StatusCode::OK_200, res->status);
  8061. ASSERT_EQ(26U, res->body.size());
  8062. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8063. 0);
  8064. }
  8065. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8066. Headers headers;
  8067. headers.emplace("Accept-Encoding", "");
  8068. std::string body;
  8069. auto res = cli_.Get("/compress", headers,
  8070. [&](const char *data, uint64_t data_length) {
  8071. EXPECT_EQ(100U, data_length);
  8072. body.append(data, data_length);
  8073. return true;
  8074. });
  8075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8076. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8078. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8079. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8080. "7890123456789012345678901234567890",
  8081. body);
  8082. EXPECT_EQ(StatusCode::OK_200, res->status);
  8083. }
  8084. TEST_F(ServerTest, NoZstd) {
  8085. Headers headers;
  8086. headers.emplace("Accept-Encoding", "zstd");
  8087. auto res = cli_.Get("/nocompress", headers);
  8088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8089. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8090. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8091. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8092. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8093. "7890123456789012345678901234567890",
  8094. res->body);
  8095. EXPECT_EQ(StatusCode::OK_200, res->status);
  8096. }
  8097. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8098. Headers headers;
  8099. headers.emplace("Accept-Encoding", "zstd");
  8100. std::string body;
  8101. auto res = cli_.Get("/nocompress", headers,
  8102. [&](const char *data, uint64_t data_length) {
  8103. EXPECT_EQ(100U, data_length);
  8104. body.append(data, data_length);
  8105. return true;
  8106. });
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8109. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8110. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8111. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8112. "7890123456789012345678901234567890",
  8113. body);
  8114. EXPECT_EQ(StatusCode::OK_200, res->status);
  8115. }
  8116. // TODO: How to enable zstd ??
  8117. TEST_F(ServerTest, MultipartFormDataZstd) {
  8118. UploadFormDataItems items = {
  8119. {"key1", "test", "", ""},
  8120. {"key2", "--abcdefg123", "", ""},
  8121. };
  8122. Headers headers;
  8123. headers.emplace("Accept-Encoding", "zstd");
  8124. cli_.set_compress(true);
  8125. auto res = cli_.Post("/compress-multipart", headers, items);
  8126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8127. EXPECT_EQ(StatusCode::OK_200, res->status);
  8128. }
  8129. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8130. Headers headers;
  8131. headers.emplace("Accept-Encoding", "zstd");
  8132. cli_.set_compress(true);
  8133. auto res = cli_.Put(
  8134. "/put", headers, 3,
  8135. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8136. sink.os << "PUT";
  8137. return true;
  8138. },
  8139. "text/plain");
  8140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8141. EXPECT_EQ(StatusCode::OK_200, res->status);
  8142. EXPECT_EQ("PUT", res->body);
  8143. }
  8144. // Pre-compression logging tests
  8145. TEST_F(ServerTest, PreCompressionLogging) {
  8146. // Test data for compression (matches the actual /compress endpoint content)
  8147. const std::string test_content =
  8148. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8149. "3456789012345678901234567890";
  8150. // Variables to capture logging data
  8151. std::string pre_compression_body;
  8152. std::string pre_compression_content_type;
  8153. std::string pre_compression_content_encoding;
  8154. std::string post_compression_body;
  8155. std::string post_compression_content_type;
  8156. std::string post_compression_content_encoding;
  8157. // Set up pre-compression logger
  8158. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8159. const Response &res) {
  8160. pre_compression_body = res.body;
  8161. pre_compression_content_type = res.get_header_value("Content-Type");
  8162. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8163. });
  8164. // Set up post-compression logger
  8165. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8166. post_compression_body = res.body;
  8167. post_compression_content_type = res.get_header_value("Content-Type");
  8168. post_compression_content_encoding =
  8169. res.get_header_value("Content-Encoding");
  8170. });
  8171. // Test with gzip compression
  8172. Headers headers;
  8173. headers.emplace("Accept-Encoding", "gzip");
  8174. auto res = cli_.Get("/compress", headers);
  8175. // Verify response was compressed
  8176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8177. EXPECT_EQ(StatusCode::OK_200, res->status);
  8178. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8179. // Verify pre-compression logger captured uncompressed content
  8180. EXPECT_EQ(test_content, pre_compression_body);
  8181. EXPECT_EQ("text/plain", pre_compression_content_type);
  8182. EXPECT_TRUE(pre_compression_content_encoding
  8183. .empty()); // No encoding header before compression
  8184. // Verify post-compression logger captured compressed content
  8185. EXPECT_NE(test_content,
  8186. post_compression_body); // Should be different after compression
  8187. EXPECT_EQ("text/plain", post_compression_content_type);
  8188. EXPECT_EQ("gzip", post_compression_content_encoding);
  8189. // Verify compressed content is smaller
  8190. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8191. }
  8192. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8193. const std::string test_content =
  8194. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8195. "3456789012345678901234567890";
  8196. std::string pre_compression_body;
  8197. std::string post_compression_body;
  8198. svr_.set_pre_compression_logger(
  8199. [&](const Request & /*req*/, const Response &res) {
  8200. pre_compression_body = res.body;
  8201. });
  8202. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8203. post_compression_body = res.body;
  8204. });
  8205. Headers headers;
  8206. headers.emplace("Accept-Encoding", "br");
  8207. auto res = cli_.Get("/compress", headers);
  8208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8209. EXPECT_EQ(StatusCode::OK_200, res->status);
  8210. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8211. // Verify pre-compression content is uncompressed
  8212. EXPECT_EQ(test_content, pre_compression_body);
  8213. // Verify post-compression content is compressed
  8214. EXPECT_NE(test_content, post_compression_body);
  8215. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8216. }
  8217. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8218. const std::string test_content =
  8219. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8220. "3456789012345678901234567890";
  8221. std::string pre_compression_body;
  8222. std::string post_compression_body;
  8223. svr_.set_pre_compression_logger(
  8224. [&](const Request & /*req*/, const Response &res) {
  8225. pre_compression_body = res.body;
  8226. });
  8227. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8228. post_compression_body = res.body;
  8229. });
  8230. // Request without compression (use /nocompress endpoint)
  8231. Headers headers;
  8232. auto res = cli_.Get("/nocompress", headers);
  8233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8234. EXPECT_EQ(StatusCode::OK_200, res->status);
  8235. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8236. // Pre-compression logger should not be called when no compression is applied
  8237. EXPECT_TRUE(
  8238. pre_compression_body.empty()); // Pre-compression logger not called
  8239. EXPECT_EQ(
  8240. test_content,
  8241. post_compression_body); // Post-compression logger captures final content
  8242. }
  8243. TEST_F(ServerTest, LoggerSeesContentLength) {
  8244. size_t logged_content_length = 0;
  8245. std::string logged_content_length_header;
  8246. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8247. logged_content_length = res.content_length_;
  8248. logged_content_length_header = res.get_header_value("Content-Length");
  8249. });
  8250. auto res = cli_.Get("/nocompress");
  8251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8252. EXPECT_EQ(StatusCode::OK_200, res->status);
  8253. EXPECT_EQ(res->body.size(), logged_content_length);
  8254. EXPECT_EQ(std::to_string(logged_content_length),
  8255. logged_content_length_header);
  8256. }
  8257. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8258. const std::string test_content =
  8259. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8260. "3456789012345678901234567890";
  8261. std::string pre_compression_body;
  8262. bool pre_logger_called = false;
  8263. // Set only pre-compression logger
  8264. svr_.set_pre_compression_logger(
  8265. [&](const Request & /*req*/, const Response &res) {
  8266. pre_compression_body = res.body;
  8267. pre_logger_called = true;
  8268. });
  8269. Headers headers;
  8270. headers.emplace("Accept-Encoding", "gzip");
  8271. auto res = cli_.Get("/compress", headers);
  8272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8273. EXPECT_EQ(StatusCode::OK_200, res->status);
  8274. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8275. // Verify pre-compression logger was called
  8276. EXPECT_TRUE(pre_logger_called);
  8277. EXPECT_EQ(test_content, pre_compression_body);
  8278. }
  8279. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8280. {
  8281. // Test with Expect: 100-continue header - success case
  8282. // Server returns 100 Continue, client sends body, server returns 200 OK
  8283. Request req;
  8284. req.method = "POST";
  8285. req.path = "/post-large";
  8286. req.set_header("Expect", "100-continue");
  8287. req.body = LARGE_DATA;
  8288. Response res;
  8289. auto error = Error::Success;
  8290. cli_.set_keep_alive(true);
  8291. auto ret = cli_.send(req, res, error);
  8292. EXPECT_TRUE(ret);
  8293. EXPECT_EQ(StatusCode::OK_200, res.status);
  8294. EXPECT_EQ(LARGE_DATA, res.body);
  8295. }
  8296. {
  8297. // Test with Expect: 100-continue header - error case
  8298. // Client should not send the body when server returns an error
  8299. Request req;
  8300. req.method = "POST";
  8301. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8302. req.set_header("Expect", "100-continue");
  8303. req.body = LARGE_DATA;
  8304. Response res;
  8305. auto error = Error::Success;
  8306. auto start = std::chrono::high_resolution_clock::now();
  8307. cli_.set_keep_alive(true);
  8308. auto ret = cli_.send(req, res, error);
  8309. auto end = std::chrono::high_resolution_clock::now();
  8310. auto elapsed =
  8311. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8312. .count();
  8313. // With Expect: 100-continue, request completes successfully but with error
  8314. EXPECT_TRUE(ret);
  8315. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8316. EXPECT_EQ("close", res.get_header_value("Connection"));
  8317. EXPECT_FALSE(cli_.is_socket_open());
  8318. EXPECT_LE(elapsed, 2000);
  8319. }
  8320. {
  8321. // Send an extra GET request to ensure error recovery without hanging
  8322. Request req;
  8323. req.method = "GET";
  8324. req.path = "/hi";
  8325. auto start = std::chrono::high_resolution_clock::now();
  8326. auto res = cli_.send(req);
  8327. auto end = std::chrono::high_resolution_clock::now();
  8328. auto elapsed =
  8329. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8330. .count();
  8331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8332. EXPECT_EQ(StatusCode::OK_200, res->status);
  8333. EXPECT_EQ("Hello World!", res->body);
  8334. EXPECT_LE(elapsed, 500);
  8335. }
  8336. }
  8337. TEST(ZstdDecompressor, ChunkedDecompression) {
  8338. std::string data;
  8339. for (size_t i = 0; i < 32 * 1024; ++i) {
  8340. data.push_back(static_cast<char>('a' + i % 26));
  8341. }
  8342. std::string compressed_data;
  8343. {
  8344. httplib::detail::zstd_compressor compressor;
  8345. bool result = compressor.compress(
  8346. data.data(), data.size(),
  8347. /*last=*/true,
  8348. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8349. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8350. compressed_data_size);
  8351. return true;
  8352. });
  8353. ASSERT_TRUE(result);
  8354. }
  8355. std::string decompressed_data;
  8356. {
  8357. httplib::detail::zstd_decompressor decompressor;
  8358. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8359. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8360. size_t chunk_size = 130;
  8361. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8362. chunk_begin += chunk_size) {
  8363. size_t current_chunk_size =
  8364. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8365. bool result = decompressor.decompress(
  8366. compressed_data.data() + chunk_begin, current_chunk_size,
  8367. [&](const char *decompressed_data_chunk,
  8368. size_t decompressed_data_chunk_size) {
  8369. decompressed_data.insert(decompressed_data.size(),
  8370. decompressed_data_chunk,
  8371. decompressed_data_chunk_size);
  8372. return true;
  8373. });
  8374. ASSERT_TRUE(result);
  8375. }
  8376. }
  8377. ASSERT_EQ(data, decompressed_data);
  8378. }
  8379. TEST(ZstdDecompressor, Decompress) {
  8380. std::string original_text = "Compressed with ZSTD";
  8381. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8382. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8383. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8384. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8385. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8386. std::string decompressed_data;
  8387. {
  8388. httplib::detail::zstd_decompressor decompressor;
  8389. bool result = decompressor.decompress(
  8390. compressed_data.data(), compressed_data.size(),
  8391. [&](const char *decompressed_data_chunk,
  8392. size_t decompressed_data_chunk_size) {
  8393. decompressed_data.insert(decompressed_data.size(),
  8394. decompressed_data_chunk,
  8395. decompressed_data_chunk_size);
  8396. return true;
  8397. });
  8398. ASSERT_TRUE(result);
  8399. }
  8400. ASSERT_EQ(original_text, decompressed_data);
  8401. }
  8402. #endif
  8403. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8404. // separate chunks so that the server sees each part in its own read(). Used to
  8405. // place a read boundary at a specific offset of a request body.
  8406. static bool send_request_in_parts(time_t read_timeout_sec,
  8407. const std::vector<std::string> &parts,
  8408. std::string *resp = nullptr,
  8409. int port = PORT) {
  8410. auto error = Error::Success;
  8411. auto client_sock = detail::create_client_socket(
  8412. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8413. /*connection_timeout_sec=*/5, 0,
  8414. /*read_timeout_sec=*/5, 0,
  8415. /*write_timeout_sec=*/5, 0, std::string(), error);
  8416. if (client_sock == INVALID_SOCKET) { return false; }
  8417. auto ret = detail::process_client_socket(
  8418. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8419. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8420. for (size_t i = 0; i < parts.size(); i++) {
  8421. const auto &part = parts[i];
  8422. if (part.size() !=
  8423. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8424. return false;
  8425. }
  8426. if (i + 1 < parts.size()) {
  8427. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8428. }
  8429. }
  8430. char buf[512];
  8431. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8432. while (line_reader.getline()) {
  8433. if (resp) { *resp += line_reader.ptr(); }
  8434. }
  8435. return true;
  8436. });
  8437. detail::close_socket(client_sock);
  8438. return ret;
  8439. }
  8440. // Sends a raw request to a server listening at HOST:PORT.
  8441. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8442. std::string *resp = nullptr, int port = PORT) {
  8443. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8444. }
  8445. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8446. Server svr;
  8447. std::string header_value;
  8448. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8449. header_value = req.get_header_value("foo");
  8450. res.set_content("ok", "text/plain");
  8451. });
  8452. thread t = thread([&] { svr.listen(HOST, PORT); });
  8453. auto se = detail::scope_exit([&] {
  8454. svr.stop();
  8455. t.join();
  8456. ASSERT_FALSE(svr.is_running());
  8457. });
  8458. svr.wait_until_ready();
  8459. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8460. // like characters are not treated the same - use vertical tab and escape.
  8461. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8462. "foo: \t \v bar \x1B\t \r\n"
  8463. "Connection: close\r\n"
  8464. "\r\n";
  8465. std::string res;
  8466. ASSERT_TRUE(send_request(5, req, &res));
  8467. EXPECT_EQ(header_value, "");
  8468. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8469. }
  8470. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8471. Server svr;
  8472. std::string received;
  8473. svr.Get("/order", [&](const Request &req, Response &res) {
  8474. received = entries_to_string(req.headers);
  8475. res.set_content("ok", "text/plain");
  8476. });
  8477. auto port = svr.bind_to_any_port(HOST);
  8478. thread t = thread([&] { svr.listen_after_bind(); });
  8479. auto se = detail::scope_exit([&] {
  8480. svr.stop();
  8481. t.join();
  8482. ASSERT_FALSE(svr.is_running());
  8483. });
  8484. svr.wait_until_ready();
  8485. const std::string req = "GET /order HTTP/1.1\r\n"
  8486. "X-First: 1\r\n"
  8487. "X-Dup: a\r\n"
  8488. "X-Second: 2\r\n"
  8489. "X-Dup: b\r\n"
  8490. "Connection: close\r\n"
  8491. "\r\n";
  8492. std::string res;
  8493. ASSERT_TRUE(send_request(5, req, &res, port));
  8494. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8495. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8496. }
  8497. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8498. Server svr;
  8499. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8500. res.set_header("Set-Cookie", "first=1");
  8501. res.set_header("X-Between", "y");
  8502. res.set_header("Set-Cookie", "second=2");
  8503. res.set_content("ok", "text/plain");
  8504. });
  8505. auto port = svr.bind_to_any_port(HOST);
  8506. thread t = thread([&] { svr.listen_after_bind(); });
  8507. auto se = detail::scope_exit([&] {
  8508. svr.stop();
  8509. t.join();
  8510. ASSERT_FALSE(svr.is_running());
  8511. });
  8512. svr.wait_until_ready();
  8513. Client cli(HOST, port);
  8514. auto res = cli.Get("/cookies");
  8515. ASSERT_TRUE(res);
  8516. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8517. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8518. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8519. }
  8520. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8521. Server svr;
  8522. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8523. auto i = new int(0);
  8524. res.set_header("Trailer", "X-Safe, X-Reflected");
  8525. res.set_chunked_content_provider(
  8526. "text/plain",
  8527. [i](size_t /*offset*/, DataSink &sink) {
  8528. if (*i == 0) {
  8529. sink.os << "body";
  8530. } else {
  8531. Headers trailer;
  8532. // A valid trailer that must survive.
  8533. trailer.emplace("X-Safe", "safe");
  8534. // Attacker-controlled value carrying CR/LF (response splitting).
  8535. trailer.emplace("X-Reflected",
  8536. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8537. // Attacker-controlled name carrying CR/LF.
  8538. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8539. sink.done_with_trailer(trailer);
  8540. }
  8541. (*i)++;
  8542. return true;
  8543. },
  8544. [i](bool /*success*/) { delete i; });
  8545. });
  8546. thread t = thread([&] { svr.listen(HOST, PORT); });
  8547. auto se = detail::scope_exit([&] {
  8548. svr.stop();
  8549. t.join();
  8550. ASSERT_FALSE(svr.is_running());
  8551. });
  8552. svr.wait_until_ready();
  8553. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8554. "Host: " + HOST +
  8555. "\r\n"
  8556. "Connection: close\r\n"
  8557. "\r\n";
  8558. std::string res;
  8559. ASSERT_TRUE(send_request(5, req, &res));
  8560. // The injected fields must not appear anywhere in the raw response.
  8561. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8562. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8563. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8564. // Invalid trailers are dropped entirely, matching set_header().
  8565. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8566. // The valid trailer still passes through.
  8567. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8568. }
  8569. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8570. Server svr;
  8571. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8572. // res.headers is a public field an application can populate directly,
  8573. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8574. // A valid header that must survive.
  8575. res.headers.emplace("X-Safe", "safe");
  8576. // Attacker-controlled value carrying CR/LF (response splitting).
  8577. res.headers.emplace("X-Reflected",
  8578. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8579. // Attacker-controlled name carrying CR/LF.
  8580. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8581. res.set_content("body", "text/plain");
  8582. });
  8583. thread t = thread([&] { svr.listen(HOST, PORT); });
  8584. auto se = detail::scope_exit([&] {
  8585. svr.stop();
  8586. t.join();
  8587. ASSERT_FALSE(svr.is_running());
  8588. });
  8589. svr.wait_until_ready();
  8590. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8591. "Host: " + HOST +
  8592. "\r\n"
  8593. "Connection: close\r\n"
  8594. "\r\n";
  8595. std::string res;
  8596. ASSERT_TRUE(send_request(5, req, &res));
  8597. // The injected fields must not appear anywhere in the raw response.
  8598. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8599. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8600. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8601. // Invalid headers are dropped entirely, matching set_header().
  8602. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8603. // The valid header still passes through.
  8604. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8605. }
  8606. // Forward declaration: in split builds split.py strips `inline` and moves the
  8607. // definition into httplib.cc, so detail::write_request_line is not visible from
  8608. // the public httplib.h. Re-declaring it here lets the tests link against the
  8609. // symbol in both header-only and split builds.
  8610. namespace httplib {
  8611. namespace detail {
  8612. ssize_t write_request_line(Stream &strm, const std::string &method,
  8613. const std::string &path);
  8614. } // namespace detail
  8615. } // namespace httplib
  8616. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8617. // A well-formed target is written verbatim.
  8618. {
  8619. detail::BufferStream strm;
  8620. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8621. EXPECT_GT(n, 0);
  8622. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8623. }
  8624. // A target carrying CR/LF, SP or other control octets must be rejected
  8625. // before anything reaches the wire, otherwise it splits the request line and
  8626. // injects a header or a whole request.
  8627. const std::string evil_targets[] = {
  8628. "/a\r\nInjected: pwned",
  8629. "/a\rInjected",
  8630. "/a\nInjected",
  8631. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8632. "/a b",
  8633. "/a\tb",
  8634. "/a\x7f",
  8635. };
  8636. for (const auto &evil : evil_targets) {
  8637. detail::BufferStream strm;
  8638. auto n = detail::write_request_line(strm, "GET", evil);
  8639. EXPECT_LT(n, 0);
  8640. EXPECT_TRUE(strm.get_buffer().empty());
  8641. }
  8642. }
  8643. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8644. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8645. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8646. // target reaches write_request. The client must fail cleanly with
  8647. // Error::Write instead of putting a request-line-less, header-injecting
  8648. // request on the wire.
  8649. Server svr;
  8650. svr.Get("/a", [](const Request &, Response &res) {
  8651. res.set_content("ok", "text/plain");
  8652. });
  8653. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8654. auto se = detail::scope_exit([&] {
  8655. svr.stop();
  8656. thread.join();
  8657. ASSERT_FALSE(svr.is_running());
  8658. });
  8659. svr.wait_until_ready();
  8660. {
  8661. Client cli(HOST, PORT);
  8662. cli.set_path_encode(false);
  8663. // The request is rejected before anything is written, so the connection
  8664. // stays silent and the subsequent response read would otherwise block for
  8665. // the full default read timeout. Shorten it -- the assertion is on the
  8666. // error, not the timeout.
  8667. cli.set_read_timeout(1, 0);
  8668. auto res = cli.Get("/a\r\nInjected: pwned");
  8669. EXPECT_FALSE(res);
  8670. EXPECT_EQ(Error::Write, res.error());
  8671. }
  8672. }
  8673. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8674. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8675. // including extension methods.
  8676. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8677. for (const auto &method : good_methods) {
  8678. detail::BufferStream strm;
  8679. auto n = detail::write_request_line(strm, method, "/");
  8680. EXPECT_GT(n, 0);
  8681. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8682. }
  8683. // A method carrying CR/LF would split the request line and smuggle a whole
  8684. // request ahead of the real one. A space or an empty method corrupts the
  8685. // request line. All must be rejected before anything reaches the wire.
  8686. const std::string evil_methods[] = {
  8687. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8688. "GET\r\nInjected: pwned",
  8689. "GET\r",
  8690. "GET\n",
  8691. "GE T",
  8692. "",
  8693. };
  8694. for (const auto &evil : evil_methods) {
  8695. detail::BufferStream strm;
  8696. auto n = detail::write_request_line(strm, evil, "/");
  8697. EXPECT_LT(n, 0);
  8698. EXPECT_TRUE(strm.get_buffer().empty());
  8699. }
  8700. }
  8701. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8702. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8703. // through Client::send must fail with Error::Write and no request, neither
  8704. // the smuggled one nor the real one, may reach the server.
  8705. Server svr;
  8706. std::atomic<int> request_count(0);
  8707. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8708. request_count++;
  8709. res.status = StatusCode::OK_200;
  8710. return Server::HandlerResponse::Handled;
  8711. });
  8712. auto port = svr.bind_to_any_port(HOST);
  8713. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8714. auto se = detail::scope_exit([&] {
  8715. svr.stop();
  8716. thread.join();
  8717. ASSERT_FALSE(svr.is_running());
  8718. });
  8719. svr.wait_until_ready();
  8720. {
  8721. Client cli(HOST, port);
  8722. const std::string evil_methods[] = {
  8723. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8724. "GE T",
  8725. "",
  8726. };
  8727. for (const auto &evil : evil_methods) {
  8728. Request req;
  8729. req.method = evil;
  8730. req.path = "/";
  8731. auto res = cli.send(req);
  8732. EXPECT_FALSE(res);
  8733. EXPECT_EQ(Error::Write, res.error());
  8734. }
  8735. auto handle =
  8736. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8737. EXPECT_FALSE(handle.is_valid());
  8738. EXPECT_EQ(Error::Write, handle.error);
  8739. // A valid request on the same client still goes through.
  8740. auto res = cli.Get("/");
  8741. ASSERT_TRUE(res);
  8742. EXPECT_EQ(StatusCode::OK_200, res->status);
  8743. }
  8744. EXPECT_EQ(1, request_count.load());
  8745. }
  8746. // Sends a raw request and verifies that there isn't a crash or exception.
  8747. static void test_raw_request(const std::string &req,
  8748. std::string *out = nullptr) {
  8749. Server svr;
  8750. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8751. res.set_content("ok", "text/plain");
  8752. });
  8753. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8754. res.set_content("ok", "text/plain");
  8755. });
  8756. svr.Get("/header_field_value_check",
  8757. [&](const Request & /*req*/, Response &res) {
  8758. res.set_content("ok", "text/plain");
  8759. });
  8760. svr.CustomRoute("PROPFIND", "/dav",
  8761. [&](const Request & /*req*/, Response &res) {
  8762. res.status = StatusCode::MultiStatus_207;
  8763. });
  8764. // Server read timeout must be longer than the client read timeout for the
  8765. // bug to reproduce, probably to force the server to process a request
  8766. // without a trailing blank line.
  8767. const time_t client_read_timeout_sec = 1;
  8768. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8769. bool listen_thread_ok = false;
  8770. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8771. auto se = detail::scope_exit([&] {
  8772. svr.stop();
  8773. t.join();
  8774. ASSERT_FALSE(svr.is_running());
  8775. EXPECT_TRUE(listen_thread_ok);
  8776. });
  8777. svr.wait_until_ready();
  8778. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8779. }
  8780. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8781. // A certain header line causes an exception if the header property is parsed
  8782. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8783. test_raw_request(
  8784. "GET /hi HTTP/1.1\r\n"
  8785. " : "
  8786. " "
  8787. " ");
  8788. }
  8789. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8790. // A certain header line causes an exception if the header property *name* is
  8791. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8792. // greedy matcher and requires backtracking when there are a lot of ":"
  8793. // characters.
  8794. // This occurs with libc++ but not libstdc++.
  8795. test_raw_request(
  8796. "GET /hi HTTP/1.1\r\n"
  8797. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8798. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8799. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8800. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8801. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8802. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8803. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8804. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8805. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8806. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8807. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8808. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8809. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8810. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8811. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8812. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8813. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8814. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8815. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8816. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8817. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8818. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8819. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8820. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8821. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8822. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8823. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8824. "&&&%%%");
  8825. }
  8826. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8827. // Make sure this doesn't crash the server.
  8828. // In a previous version of the header line regex, the "\r" rendered the line
  8829. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8830. // a new position where the leading white space ended and the field value
  8831. // began.
  8832. // The crash occurs with libc++ but not libstdc++.
  8833. test_raw_request("GET /hi HTTP/1.1\r\n"
  8834. "a:" +
  8835. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8836. "\r\n"
  8837. "\r\n");
  8838. }
  8839. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8840. std::string out;
  8841. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8842. "Content-Type: text/plain\r\n"
  8843. "Transfer-Encoding: chunked\r\n"
  8844. "\r\n"
  8845. "nothex\r\n",
  8846. &out);
  8847. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8848. }
  8849. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8850. std::string out;
  8851. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8852. "Content-Type: text/plain\r\n"
  8853. "Transfer-Encoding: chunked\r\n"
  8854. "\r\n"
  8855. "3\r\n"
  8856. "xyz\r\n"
  8857. "NaN\r\n",
  8858. &out);
  8859. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8860. }
  8861. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8862. std::string out;
  8863. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8864. "Content-Type: text/plain\r\n"
  8865. "Transfer-Encoding: chunked\r\n"
  8866. "\r\n"
  8867. // Length is too large for 64 bits.
  8868. "1ffffffffffffffff\r\n"
  8869. "xyz\r\n",
  8870. &out);
  8871. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8872. }
  8873. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8874. test_raw_request("GET /hi HTTP/1.1\r\n"
  8875. "Content-Type: text/plain\r\n\r");
  8876. }
  8877. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8878. std::string out;
  8879. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8880. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8881. }
  8882. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8883. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8884. std::string out;
  8885. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8886. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8887. }
  8888. }
  8889. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8890. std::string out;
  8891. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8892. "Connection: close\r\n\r\n",
  8893. &out);
  8894. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8895. }
  8896. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8897. Server svr;
  8898. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8899. EXPECT_TRUE(!req.remote_addr.empty());
  8900. });
  8901. thread t = thread([&] { svr.listen(HOST, PORT); });
  8902. auto se = detail::scope_exit([&] {
  8903. svr.stop();
  8904. t.join();
  8905. ASSERT_FALSE(svr.is_running());
  8906. });
  8907. svr.wait_until_ready();
  8908. // Send an invalid request line to trigger Bad Request
  8909. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8910. std::string out;
  8911. ASSERT_TRUE(send_request(5, bad_req, &out));
  8912. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8913. }
  8914. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8915. // answered right away rather than blocking on a read that waits for EOF.
  8916. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8917. std::string out;
  8918. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8919. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8920. }
  8921. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8922. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8923. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8924. for (const auto *method : methods) {
  8925. Server svr;
  8926. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8927. EXPECT_FALSE(svr.is_valid()) << method;
  8928. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8929. }
  8930. }
  8931. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8932. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8933. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8934. for (const auto *method : methods) {
  8935. Server svr;
  8936. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8937. EXPECT_FALSE(svr.is_valid()) << method;
  8938. }
  8939. }
  8940. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8941. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8942. "COPY", "MOVE", "LOCK",
  8943. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8944. Server svr;
  8945. for (const auto *method : methods) {
  8946. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8947. }
  8948. EXPECT_TRUE(svr.is_valid());
  8949. }
  8950. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8951. Server svr;
  8952. svr.CustomRoute("POST", "/x",
  8953. [](const Request &, Response &, const ContentReader &) {});
  8954. EXPECT_FALSE(svr.is_valid());
  8955. }
  8956. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8957. Server svr;
  8958. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8959. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8960. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8961. EXPECT_FALSE(svr.is_valid());
  8962. }
  8963. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8964. Server svr;
  8965. auto captured = Error::Success;
  8966. svr.set_error_logger(
  8967. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8968. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8969. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8970. }
  8971. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8972. std::string out;
  8973. std::string request(
  8974. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8975. test_raw_request(request, &out);
  8976. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8977. }
  8978. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8979. std::string out;
  8980. std::string request(
  8981. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8982. test_raw_request(request, &out);
  8983. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8984. }
  8985. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8986. std::string out;
  8987. std::string request(
  8988. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8989. test_raw_request(request, &out);
  8990. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8991. }
  8992. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8993. std::string out;
  8994. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8995. "Test: \r\n\r\n",
  8996. &out);
  8997. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8998. }
  8999. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9000. Server svr;
  9001. std::string x_custom;
  9002. std::string cookie;
  9003. std::string xff;
  9004. std::string x_unicode;
  9005. std::string x_iis;
  9006. svr.Get("/check", [&](const Request &req, Response &res) {
  9007. x_custom = req.get_header_value("X-Custom");
  9008. cookie = req.get_header_value("Cookie");
  9009. xff = req.get_header_value("X-Forwarded-For");
  9010. x_unicode = req.get_header_value("X-Unicode");
  9011. x_iis = req.get_header_value("X-IIS");
  9012. res.set_content("ok", "text/plain");
  9013. });
  9014. thread t = thread([&] { svr.listen(HOST, PORT); });
  9015. auto se = detail::scope_exit([&] {
  9016. svr.stop();
  9017. t.join();
  9018. ASSERT_FALSE(svr.is_running());
  9019. });
  9020. svr.wait_until_ready();
  9021. const std::string req = "GET /check HTTP/1.1\r\n"
  9022. "Host: localhost\r\n"
  9023. "X-Custom: a%0D%0AInjected: b\r\n"
  9024. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9025. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9026. "X-Unicode: %E3%81%82\r\n"
  9027. "X-IIS: %u00E9\r\n"
  9028. "Connection: close\r\n"
  9029. "\r\n";
  9030. std::string res;
  9031. ASSERT_TRUE(send_request(5, req, &res));
  9032. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9033. // Every value must be returned verbatim (wire form), with no decoding.
  9034. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9035. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9036. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9037. EXPECT_EQ("%E3%81%82", x_unicode);
  9038. EXPECT_EQ("%u00E9", x_iis);
  9039. }
  9040. // Applications that previously relied on automatic percent-decoding can
  9041. // reproduce the old behavior by explicitly calling decode_path_component()
  9042. // or, for RFC 3986 conformance, decode_uri_component().
  9043. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9044. Server svr;
  9045. std::string decoded;
  9046. svr.Get("/check", [&](const Request &req, Response &res) {
  9047. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9048. res.set_content("ok", "text/plain");
  9049. });
  9050. thread t = thread([&] { svr.listen(HOST, PORT); });
  9051. auto se = detail::scope_exit([&] {
  9052. svr.stop();
  9053. t.join();
  9054. ASSERT_FALSE(svr.is_running());
  9055. });
  9056. svr.wait_until_ready();
  9057. const std::string req = "GET /check HTTP/1.1\r\n"
  9058. "Host: localhost\r\n"
  9059. "X-Custom: hello%20world\r\n"
  9060. "Connection: close\r\n"
  9061. "\r\n";
  9062. std::string res;
  9063. ASSERT_TRUE(send_request(5, req, &res));
  9064. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9065. EXPECT_EQ("hello world", decoded);
  9066. }
  9067. // Regression test for #2033. Browsers send Referer values that include
  9068. // percent-encoded characters such as %0A inside the URL. Decoding the
  9069. // header value would either trip the post-decode CR/LF/NUL guard (the
  9070. // original bug, returning 400) or, after that guard was relaxed, silently
  9071. // store a literal LF — both unacceptable. The wire form must round-trip.
  9072. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9073. Server svr;
  9074. std::string referer;
  9075. svr.Get("/check", [&](const Request &req, Response &res) {
  9076. referer = req.get_header_value("Referer");
  9077. res.set_content("ok", "text/plain");
  9078. });
  9079. thread t = thread([&] { svr.listen(HOST, PORT); });
  9080. auto se = detail::scope_exit([&] {
  9081. svr.stop();
  9082. t.join();
  9083. ASSERT_FALSE(svr.is_running());
  9084. });
  9085. svr.wait_until_ready();
  9086. const std::string req = "GET /check HTTP/1.1\r\n"
  9087. "Host: localhost\r\n"
  9088. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9089. "Connection: close\r\n"
  9090. "\r\n";
  9091. std::string res;
  9092. ASSERT_TRUE(send_request(5, req, &res));
  9093. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9094. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9095. }
  9096. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9097. Server svr;
  9098. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9099. res.set_header("Cache-Control", "no-cache");
  9100. res.set_chunked_content_provider(
  9101. "text/event-stream", [](size_t offset, DataSink &sink) {
  9102. std::string s = "data:";
  9103. s += std::to_string(offset);
  9104. s += "\n\n";
  9105. auto ret = sink.write(s.data(), s.size());
  9106. EXPECT_TRUE(ret);
  9107. std::this_thread::sleep_for(std::chrono::seconds(1));
  9108. return true;
  9109. });
  9110. });
  9111. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9112. svr.wait_until_ready();
  9113. Client client(HOST, PORT);
  9114. const Headers headers = {{"Accept", "text/event-stream"}};
  9115. auto get_thread = std::thread([&client, &headers]() {
  9116. auto res = client.Get(
  9117. "/events", headers,
  9118. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9119. });
  9120. auto se = detail::scope_exit([&] {
  9121. svr.stop();
  9122. get_thread.join();
  9123. listen_thread.join();
  9124. ASSERT_FALSE(svr.is_running());
  9125. });
  9126. // Give GET time to get a few messages.
  9127. std::this_thread::sleep_for(std::chrono::seconds(2));
  9128. }
  9129. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9130. httplib::Server svr;
  9131. svr.Post("/hi",
  9132. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9133. res.status = StatusCode::OK_200;
  9134. });
  9135. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9136. svr.wait_until_ready();
  9137. Client cli(HOST, PORT);
  9138. auto res = cli.Post("/hi", "data", "text/plain");
  9139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9140. EXPECT_EQ(StatusCode::OK_200, res->status);
  9141. svr.stop();
  9142. thread.join();
  9143. ASSERT_FALSE(svr.is_running());
  9144. res = cli.Post("/hi", "data", "text/plain");
  9145. ASSERT_FALSE(res);
  9146. }
  9147. TEST(ServerStopTest, ListenFailure) {
  9148. Server svr;
  9149. auto t = thread([&]() {
  9150. auto ret = svr.listen("????", PORT);
  9151. EXPECT_FALSE(ret);
  9152. });
  9153. svr.wait_until_ready();
  9154. svr.stop();
  9155. t.join();
  9156. }
  9157. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9158. TEST(ServerStopTest, Decommision) {
  9159. Server svr;
  9160. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9161. for (int i = 0; i < 4; i++) {
  9162. auto is_even = !(i % 2);
  9163. std::thread t{[&] {
  9164. try {
  9165. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9166. if (is_even) {
  9167. throw std::runtime_error("Some thing that happens to go wrong.");
  9168. }
  9169. svr.listen(HOST, PORT);
  9170. } catch (...) { svr.decommission(); }
  9171. }};
  9172. svr.wait_until_ready();
  9173. // Server is up
  9174. {
  9175. Client cli(HOST, PORT);
  9176. auto res = cli.Get("/hi");
  9177. if (is_even) {
  9178. EXPECT_FALSE(res);
  9179. } else {
  9180. EXPECT_TRUE(res);
  9181. EXPECT_EQ("hi...", res->body);
  9182. }
  9183. }
  9184. svr.stop();
  9185. t.join();
  9186. // Server is down...
  9187. {
  9188. Client cli(HOST, PORT);
  9189. auto res = cli.Get("/hi");
  9190. EXPECT_FALSE(res);
  9191. }
  9192. }
  9193. }
  9194. #endif
  9195. // Helper function for string body upload progress tests
  9196. template <typename SetupHandler, typename ClientCall>
  9197. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9198. ClientCall &&client_call,
  9199. const string &body) {
  9200. Server svr;
  9201. setup_handler(svr);
  9202. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9203. auto se = detail::scope_exit([&] {
  9204. svr.stop();
  9205. t.join();
  9206. });
  9207. svr.wait_until_ready();
  9208. Client cli(HOST, PORT);
  9209. vector<uint64_t> progress_values;
  9210. bool progress_called = false;
  9211. auto res =
  9212. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9213. progress_values.push_back(current);
  9214. progress_called = true;
  9215. return true;
  9216. });
  9217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9218. EXPECT_EQ(200, res->status);
  9219. EXPECT_TRUE(progress_called);
  9220. }
  9221. TEST(UploadProgressTest, PostStringBodyBasic) {
  9222. TestStringBodyUploadProgress(
  9223. [](Server &svr) {
  9224. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9225. res.set_content("received", "text/plain");
  9226. });
  9227. },
  9228. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9229. return cli.Post("/test", body, "text/plain", progress_callback);
  9230. },
  9231. "test data for upload progress");
  9232. }
  9233. TEST(UploadProgressTest, PutStringBodyBasic) {
  9234. TestStringBodyUploadProgress(
  9235. [](Server &svr) {
  9236. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9237. res.set_content("put received", "text/plain");
  9238. });
  9239. },
  9240. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9241. return cli.Put("/test", body, "text/plain", progress_callback);
  9242. },
  9243. "put test data for upload progress");
  9244. }
  9245. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9246. TestStringBodyUploadProgress(
  9247. [](Server &svr) {
  9248. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9249. res.set_content("patch received", "text/plain");
  9250. });
  9251. },
  9252. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9253. return cli.Patch("/test", body, "text/plain", progress_callback);
  9254. },
  9255. "patch test data for upload progress");
  9256. }
  9257. // Helper function for content provider upload progress tests
  9258. template <typename SetupHandler, typename ClientCall>
  9259. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9260. ClientCall &&client_call) {
  9261. Server svr;
  9262. setup_handler(svr);
  9263. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9264. auto se = detail::scope_exit([&] {
  9265. svr.stop();
  9266. t.join();
  9267. });
  9268. svr.wait_until_ready();
  9269. Client cli(HOST, PORT);
  9270. vector<uint64_t> progress_values;
  9271. auto res =
  9272. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9273. progress_values.push_back(current);
  9274. return true;
  9275. });
  9276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9277. EXPECT_EQ(200, res->status);
  9278. EXPECT_FALSE(progress_values.empty());
  9279. }
  9280. TEST(UploadProgressTest, PostContentProviderProgress) {
  9281. TestContentProviderUploadProgress(
  9282. [](Server &svr) {
  9283. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9284. res.set_content("provider received", "text/plain");
  9285. });
  9286. },
  9287. [](Client &cli, UploadProgress progress_callback) {
  9288. return cli.Post(
  9289. "/test", 10,
  9290. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9291. sink.os << "test data";
  9292. return true;
  9293. },
  9294. "text/plain", progress_callback);
  9295. });
  9296. }
  9297. // Helper function for multipart upload progress tests
  9298. template <typename SetupHandler, typename ClientCall>
  9299. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9300. ClientCall &&client_call,
  9301. const string &endpoint) {
  9302. Server svr;
  9303. setup_handler(svr);
  9304. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9305. auto se = detail::scope_exit([&] {
  9306. svr.stop();
  9307. t.join();
  9308. });
  9309. svr.wait_until_ready();
  9310. Client cli(HOST, PORT);
  9311. vector<uint64_t> progress_values;
  9312. UploadFormDataItems items = {
  9313. {"field1", "value1", "", ""},
  9314. {"field2", "longer value for progress tracking test", "", ""},
  9315. {"file1", "file content data for upload progress", "test.txt",
  9316. "text/plain"}};
  9317. auto res = client_call(cli, endpoint, items,
  9318. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9319. progress_values.push_back(current);
  9320. return true;
  9321. });
  9322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9323. EXPECT_EQ(200, res->status);
  9324. EXPECT_FALSE(progress_values.empty());
  9325. }
  9326. TEST(UploadProgressTest, PostMultipartProgress) {
  9327. TestMultipartUploadProgress(
  9328. [](Server &svr) {
  9329. svr.Post("/multipart", [](const Request &req, Response &res) {
  9330. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9331. res.set_content("multipart received", "text/plain");
  9332. });
  9333. },
  9334. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9335. UploadProgress progress_callback) {
  9336. return cli.Post(endpoint, items, progress_callback);
  9337. },
  9338. "/multipart");
  9339. }
  9340. // Helper function for basic download progress tests
  9341. template <typename SetupHandler, typename ClientCall>
  9342. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9343. ClientCall &&client_call, const string &endpoint,
  9344. size_t expected_content_size) {
  9345. Server svr;
  9346. setup_handler(svr);
  9347. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9348. auto se = detail::scope_exit([&] {
  9349. svr.stop();
  9350. t.join();
  9351. });
  9352. svr.wait_until_ready();
  9353. Client cli(HOST, PORT);
  9354. vector<uint64_t> progress_values;
  9355. auto res = client_call(cli, endpoint,
  9356. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9357. progress_values.push_back(current);
  9358. return true;
  9359. });
  9360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9361. EXPECT_EQ(200, res->status);
  9362. EXPECT_FALSE(progress_values.empty());
  9363. EXPECT_EQ(expected_content_size, res->body.size());
  9364. }
  9365. TEST(DownloadProgressTest, GetBasic) {
  9366. TestBasicDownloadProgress(
  9367. [](Server &svr) {
  9368. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9369. string content(1000, 'D');
  9370. res.set_content(content, "text/plain");
  9371. });
  9372. },
  9373. [](Client &cli, const string &endpoint,
  9374. DownloadProgress progress_callback) {
  9375. return cli.Get(endpoint, progress_callback);
  9376. },
  9377. "/download", 1000u);
  9378. }
  9379. // Helper function for content receiver download progress tests
  9380. template <typename SetupHandler, typename ClientCall>
  9381. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9382. ClientCall &&client_call,
  9383. const string &endpoint,
  9384. size_t expected_content_size) {
  9385. Server svr;
  9386. setup_handler(svr);
  9387. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9388. auto se = detail::scope_exit([&] {
  9389. svr.stop();
  9390. t.join();
  9391. });
  9392. svr.wait_until_ready();
  9393. Client cli(HOST, PORT);
  9394. vector<uint64_t> progress_values;
  9395. string received_body;
  9396. auto res = client_call(
  9397. cli, endpoint,
  9398. [&](const char *data, size_t data_length) -> bool {
  9399. received_body.append(data, data_length);
  9400. return true;
  9401. },
  9402. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9403. progress_values.push_back(current);
  9404. return true;
  9405. });
  9406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9407. EXPECT_EQ(200, res->status);
  9408. EXPECT_FALSE(progress_values.empty());
  9409. EXPECT_EQ(expected_content_size, received_body.size());
  9410. EXPECT_TRUE(res->body.empty());
  9411. }
  9412. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9413. TestContentReceiverDownloadProgress(
  9414. [](Server &svr) {
  9415. svr.Get("/download-receiver",
  9416. [](const Request & /*req*/, Response &res) {
  9417. string content(2000, 'R');
  9418. res.set_content(content, "text/plain");
  9419. });
  9420. },
  9421. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9422. DownloadProgress progress_callback) {
  9423. return cli.Get(endpoint, content_receiver, progress_callback);
  9424. },
  9425. "/download-receiver", 2000u);
  9426. }
  9427. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9428. // A provider reaching a pass with nothing to hand over - an empty buffer
  9429. // popped off a queue, say - must not be taken to mean the body is finished.
  9430. // It used to end the loop with the terminating chunk unwritten while the
  9431. // server still considered the response complete, so the peer waited for an
  9432. // end that never arrived.
  9433. Server svr;
  9434. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9435. auto step = std::make_shared<int>(0);
  9436. res.set_chunked_content_provider("text/plain",
  9437. [step](size_t /*offset*/, DataSink &sink) {
  9438. switch ((*step)++) {
  9439. case 0: sink.write("", 0); break;
  9440. case 1: sink.write("hello", 5); break;
  9441. default: sink.done(); break;
  9442. }
  9443. return true;
  9444. });
  9445. });
  9446. auto port = svr.bind_to_any_port(HOST);
  9447. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9448. auto listen_se = detail::scope_exit([&] {
  9449. svr.stop();
  9450. listen_thread.join();
  9451. ASSERT_FALSE(svr.is_running());
  9452. });
  9453. svr.wait_until_ready();
  9454. Client cli(HOST, port);
  9455. // Without the fix the body is never terminated, so bound the wait rather
  9456. // than letting the test hang on the default read timeout.
  9457. cli.set_read_timeout(5, 0);
  9458. auto res = cli.Get("/stream");
  9459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9460. EXPECT_EQ(StatusCode::OK_200, res->status);
  9461. EXPECT_EQ("hello", res->body);
  9462. }
  9463. TEST(StreamingTest, NoContentLengthStreaming) {
  9464. Server svr;
  9465. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9466. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9467. if (offset < 6) {
  9468. sink.os << (offset < 3 ? "a" : "b");
  9469. } else {
  9470. sink.done();
  9471. }
  9472. return true;
  9473. });
  9474. });
  9475. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9476. auto listen_se = detail::scope_exit([&] {
  9477. svr.stop();
  9478. listen_thread.join();
  9479. ASSERT_FALSE(svr.is_running());
  9480. });
  9481. svr.wait_until_ready();
  9482. Client client(HOST, PORT);
  9483. auto get_thread = std::thread([&client]() {
  9484. std::string s;
  9485. auto res =
  9486. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9487. s += std::string(data, len);
  9488. return true;
  9489. });
  9490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9491. EXPECT_EQ(StatusCode::OK_200, res->status);
  9492. EXPECT_EQ("aaabbb", s);
  9493. });
  9494. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9495. // Give GET time to get a few messages.
  9496. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9497. }
  9498. TEST(MountTest, Unmount) {
  9499. Server svr;
  9500. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9501. auto se = detail::scope_exit([&] {
  9502. svr.stop();
  9503. listen_thread.join();
  9504. ASSERT_FALSE(svr.is_running());
  9505. });
  9506. svr.wait_until_ready();
  9507. Client cli("localhost", PORT);
  9508. svr.set_mount_point("/mount2", "./www2");
  9509. auto res = cli.Get("/");
  9510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9511. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9512. res = cli.Get("/mount2/dir/test.html");
  9513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9514. EXPECT_EQ(StatusCode::OK_200, res->status);
  9515. svr.set_mount_point("/", "./www");
  9516. res = cli.Get("/dir/");
  9517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9518. EXPECT_EQ(StatusCode::OK_200, res->status);
  9519. svr.remove_mount_point("/");
  9520. res = cli.Get("/dir/");
  9521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9522. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9523. svr.remove_mount_point("/mount2");
  9524. res = cli.Get("/mount2/dir/test.html");
  9525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9527. }
  9528. TEST(MountTest, PathSegmentBoundary) {
  9529. Server svr;
  9530. svr.set_mount_point("/mount2", "./www2");
  9531. svr.set_mount_point("/", "./www");
  9532. auto port = svr.bind_to_any_port(HOST);
  9533. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9534. auto se = detail::scope_exit([&] {
  9535. svr.stop();
  9536. listen_thread.join();
  9537. ASSERT_FALSE(svr.is_running());
  9538. });
  9539. svr.wait_until_ready();
  9540. Client cli(HOST, port);
  9541. auto res = cli.Get("/mount2/dir/test.html");
  9542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9543. EXPECT_EQ(StatusCode::OK_200, res->status);
  9544. // "/mount2" must not match part-way through a path segment.
  9545. res = cli.Get("/mount2dir/test.html");
  9546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9547. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9548. // A mount point ending in '/' keeps matching every path below it.
  9549. res = cli.Get("/dir/test.html");
  9550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9551. EXPECT_EQ(StatusCode::OK_200, res->status);
  9552. }
  9553. TEST(MountTest, Redicect) {
  9554. Server svr;
  9555. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9556. auto se = detail::scope_exit([&] {
  9557. svr.stop();
  9558. listen_thread.join();
  9559. ASSERT_FALSE(svr.is_running());
  9560. });
  9561. svr.set_mount_point("/", "./www");
  9562. svr.wait_until_ready();
  9563. Client cli("localhost", PORT);
  9564. auto res = cli.Get("/dir/");
  9565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9566. EXPECT_EQ(StatusCode::OK_200, res->status);
  9567. res = cli.Get("/dir");
  9568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9569. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9570. res = cli.Get("/file");
  9571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9572. EXPECT_EQ(StatusCode::OK_200, res->status);
  9573. res = cli.Get("/file/");
  9574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9575. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9576. cli.set_follow_location(true);
  9577. res = cli.Get("/dir");
  9578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9579. EXPECT_EQ(StatusCode::OK_200, res->status);
  9580. }
  9581. TEST(MountTest, MultibytesPathName) {
  9582. Server svr;
  9583. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9584. auto se = detail::scope_exit([&] {
  9585. svr.stop();
  9586. listen_thread.join();
  9587. ASSERT_FALSE(svr.is_running());
  9588. });
  9589. svr.set_mount_point("/", "./www");
  9590. svr.wait_until_ready();
  9591. Client cli("localhost", PORT);
  9592. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9594. EXPECT_EQ(StatusCode::OK_200, res->status);
  9595. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9596. }
  9597. #ifdef _WIN32
  9598. // Issue #2435: mmap::open() must succeed even when another handle holds
  9599. // the file open for writing (e.g. an active log file).
  9600. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9601. const char *path = "mmap_concurrent_writer_test.txt";
  9602. const char *content = "hello";
  9603. {
  9604. std::ofstream f(path, std::ios::binary);
  9605. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9606. }
  9607. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9608. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9609. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9610. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9611. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9612. detail::mmap m(path);
  9613. ASSERT_TRUE(m.is_open());
  9614. EXPECT_EQ(strlen(content), m.size());
  9615. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9616. }
  9617. #endif
  9618. #ifndef _WIN32
  9619. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9620. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9621. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9622. TEST(MmapTest, FailedMappingIsNotOpen) {
  9623. const char *path = "./mmap_failed_mapping_test_dir";
  9624. ASSERT_EQ(0, ::mkdir(path, 0755));
  9625. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9626. detail::mmap m(path);
  9627. EXPECT_FALSE(m.is_open());
  9628. EXPECT_EQ(0U, m.size());
  9629. EXPECT_NE(static_cast<const void *>(m.data()),
  9630. static_cast<const void *>(MAP_FAILED));
  9631. }
  9632. #endif
  9633. TEST(KeepAliveTest, ReadTimeout) {
  9634. Server svr;
  9635. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9636. std::this_thread::sleep_for(std::chrono::seconds(2));
  9637. res.set_content("a", "text/plain");
  9638. });
  9639. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9640. res.set_content("b", "text/plain");
  9641. });
  9642. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9643. auto se = detail::scope_exit([&] {
  9644. svr.stop();
  9645. listen_thread.join();
  9646. ASSERT_FALSE(svr.is_running());
  9647. });
  9648. svr.wait_until_ready();
  9649. Client cli("localhost", PORT);
  9650. cli.set_keep_alive(true);
  9651. cli.set_read_timeout(std::chrono::seconds(1));
  9652. auto resa = cli.Get("/a");
  9653. ASSERT_FALSE(resa);
  9654. EXPECT_EQ(Error::Read, resa.error());
  9655. auto resb = cli.Get("/b");
  9656. ASSERT_TRUE(resb);
  9657. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9658. EXPECT_EQ("b", resb->body);
  9659. }
  9660. TEST(KeepAliveTest, MaxCount) {
  9661. size_t keep_alive_max_count = 3;
  9662. Server svr;
  9663. svr.set_keep_alive_max_count(keep_alive_max_count);
  9664. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9665. res.set_content("Hello World!", "text/plain");
  9666. });
  9667. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9668. auto se = detail::scope_exit([&] {
  9669. svr.stop();
  9670. listen_thread.join();
  9671. ASSERT_FALSE(svr.is_running());
  9672. });
  9673. svr.wait_until_ready();
  9674. Client cli(HOST, PORT);
  9675. cli.set_keep_alive(true);
  9676. for (size_t i = 0; i < 5; i++) {
  9677. auto result = cli.Get("/hi");
  9678. ASSERT_TRUE(result);
  9679. EXPECT_EQ(StatusCode::OK_200, result->status);
  9680. if (i == keep_alive_max_count - 1) {
  9681. EXPECT_EQ("close", result->get_header_value("Connection"));
  9682. } else {
  9683. EXPECT_FALSE(result->has_header("Connection"));
  9684. }
  9685. }
  9686. }
  9687. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9688. // can pull the next one into the server's buffer. The server must serve it
  9689. // without waiting for the socket to become readable again. The keep-alive
  9690. // timeout outlasts the client's read timeout, so a request left waiting for it
  9691. // shows up as a missing response.
  9692. static void serve_pipelining_routes(Server &svr,
  9693. const std::function<void(int)> &client) {
  9694. svr.set_keep_alive_timeout(5);
  9695. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9696. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9697. });
  9698. svr.Post("/echo", [](const Request &req, Response &res) {
  9699. res.set_content("echo " + req.body, "text/plain");
  9700. });
  9701. auto port = svr.bind_to_any_port(HOST);
  9702. thread t = thread([&] { svr.listen_after_bind(); });
  9703. auto se = detail::scope_exit([&] {
  9704. svr.stop();
  9705. t.join();
  9706. });
  9707. svr.wait_until_ready();
  9708. client(port);
  9709. }
  9710. static std::string
  9711. send_pipelined_requests(const std::vector<std::string> &parts) {
  9712. Server svr;
  9713. std::string res;
  9714. serve_pipelining_routes(svr, [&](int port) {
  9715. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9716. });
  9717. return res;
  9718. }
  9719. static void expect_in_order(const std::string &res,
  9720. const std::vector<std::string> &bodies) {
  9721. size_t pos = 0;
  9722. for (const auto &body : bodies) {
  9723. pos = res.find(body, pos);
  9724. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9725. pos += body.size();
  9726. }
  9727. }
  9728. TEST(KeepAliveTest, PipelinedRequests) {
  9729. auto res = send_pipelined_requests(
  9730. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9731. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9732. "Content-Length: 4\r\n\r\nbody"
  9733. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9734. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9735. }
  9736. // The second request starts in the server's buffer and ends on the socket.
  9737. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9738. auto res =
  9739. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9740. "GET /hi/2 HTTP/1.1\r\nHo",
  9741. "st: localhost\r\nConnection: close\r\n\r\n"});
  9742. expect_in_order(res, {"hi 1", "hi 2"});
  9743. }
  9744. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9745. // CRLF after a body does not turn into a 400 for the next request.
  9746. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9747. auto res = send_pipelined_requests(
  9748. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9749. "Content-Length: 4\r\n\r\nbody\r\n"
  9750. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9751. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9752. expect_in_order(res, {"echo body", "hi 2"});
  9753. }
  9754. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9755. // must not be served as the next request.
  9756. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9757. auto res = send_pipelined_requests(
  9758. {"INVALID REQUEST LINE\r\n\r\n"
  9759. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9760. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9761. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9762. }
  9763. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9764. // Over TLS, the next request is held by the TLS library as already decrypted
  9765. // data rather than on the socket.
  9766. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9767. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9768. std::string res;
  9769. serve_pipelining_routes(svr, [&](int port) {
  9770. auto error = Error::Success;
  9771. auto sock = detail::create_client_socket(
  9772. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9773. /*connection_timeout_sec=*/5, 0,
  9774. /*read_timeout_sec=*/2, 0,
  9775. /*write_timeout_sec=*/5, 0, std::string(), error);
  9776. ASSERT_NE(INVALID_SOCKET, sock);
  9777. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9778. auto ctx = SSL_CTX_new(TLS_client_method());
  9779. auto ssl = SSL_new(ctx);
  9780. auto ssl_se = detail::scope_exit([&] {
  9781. SSL_free(ssl);
  9782. SSL_CTX_free(ctx);
  9783. });
  9784. SSL_set_fd(ssl, static_cast<int>(sock));
  9785. ASSERT_EQ(1, SSL_connect(ssl));
  9786. // One write, so all three requests arrive in one TLS record
  9787. const std::string req =
  9788. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9789. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9790. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  9791. ASSERT_EQ(static_cast<int>(req.size()),
  9792. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  9793. char buf[512];
  9794. int n;
  9795. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9796. res.append(buf, static_cast<size_t>(n));
  9797. }
  9798. });
  9799. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  9800. }
  9801. #endif
  9802. TEST(KeepAliveTest, Issue1041) {
  9803. Server svr;
  9804. svr.set_keep_alive_timeout(3);
  9805. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9806. res.set_content("Hello World!", "text/plain");
  9807. });
  9808. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9809. auto se = detail::scope_exit([&] {
  9810. svr.stop();
  9811. listen_thread.join();
  9812. ASSERT_FALSE(svr.is_running());
  9813. });
  9814. svr.wait_until_ready();
  9815. Client cli(HOST, PORT);
  9816. cli.set_keep_alive(true);
  9817. auto result = cli.Get("/hi");
  9818. ASSERT_TRUE(result);
  9819. EXPECT_EQ(StatusCode::OK_200, result->status);
  9820. std::this_thread::sleep_for(std::chrono::seconds(5));
  9821. result = cli.Get("/hi");
  9822. ASSERT_TRUE(result);
  9823. EXPECT_EQ(StatusCode::OK_200, result->status);
  9824. }
  9825. TEST(KeepAliveTest, Issue1959) {
  9826. Server svr;
  9827. svr.set_keep_alive_timeout(5);
  9828. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9829. res.set_content("a", "text/plain");
  9830. });
  9831. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9832. auto se = detail::scope_exit([&] {
  9833. if (!svr.is_running()) return;
  9834. svr.stop();
  9835. listen_thread.join();
  9836. ASSERT_FALSE(svr.is_running());
  9837. });
  9838. svr.wait_until_ready();
  9839. Client cli("localhost", PORT);
  9840. cli.set_keep_alive(true);
  9841. using namespace std::chrono;
  9842. auto start = steady_clock::now();
  9843. cli.Get("/a");
  9844. svr.stop();
  9845. listen_thread.join();
  9846. auto end = steady_clock::now();
  9847. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9848. EXPECT_LT(elapsed, 5000);
  9849. }
  9850. #ifdef CPPHTTPLIB_SSL_ENABLED
  9851. TEST(KeepAliveTest, SSLClientReconnection) {
  9852. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9853. ASSERT_TRUE(svr.is_valid());
  9854. svr.set_keep_alive_timeout(1);
  9855. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9856. res.set_content("Hello World!", "text/plain");
  9857. });
  9858. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9859. auto se = detail::scope_exit([&] {
  9860. svr.stop();
  9861. listen_thread.join();
  9862. ASSERT_FALSE(svr.is_running());
  9863. });
  9864. svr.wait_until_ready();
  9865. SSLClient cli(HOST, PORT);
  9866. cli.enable_server_certificate_verification(false);
  9867. cli.set_keep_alive(true);
  9868. auto result = cli.Get("/hi");
  9869. ASSERT_TRUE(result);
  9870. EXPECT_EQ(StatusCode::OK_200, result->status);
  9871. result = cli.Get("/hi");
  9872. ASSERT_TRUE(result);
  9873. EXPECT_EQ(StatusCode::OK_200, result->status);
  9874. std::this_thread::sleep_for(std::chrono::seconds(2));
  9875. // Recoonect
  9876. result = cli.Get("/hi");
  9877. ASSERT_TRUE(result);
  9878. EXPECT_EQ(StatusCode::OK_200, result->status);
  9879. result = cli.Get("/hi");
  9880. ASSERT_TRUE(result);
  9881. EXPECT_EQ(StatusCode::OK_200, result->status);
  9882. }
  9883. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9884. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9885. ASSERT_TRUE(svr.is_valid());
  9886. svr.set_keep_alive_timeout(1);
  9887. std::string content = "reconnect";
  9888. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9889. res.set_content("Hello World!", "text/plain");
  9890. });
  9891. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9892. auto se = detail::scope_exit([&] {
  9893. svr.stop();
  9894. listen_thread.join();
  9895. ASSERT_FALSE(svr.is_running());
  9896. });
  9897. svr.wait_until_ready();
  9898. SSLClient cli(HOST, PORT);
  9899. cli.enable_server_certificate_verification(false);
  9900. cli.set_keep_alive(true);
  9901. auto result = cli.Post(
  9902. "/hi", content.size(),
  9903. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9904. sink.write(content.c_str(), content.size());
  9905. return true;
  9906. },
  9907. "text/plain");
  9908. ASSERT_TRUE(result);
  9909. EXPECT_EQ(200, result->status);
  9910. std::this_thread::sleep_for(std::chrono::seconds(2));
  9911. // Recoonect
  9912. result = cli.Post(
  9913. "/hi", content.size(),
  9914. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9915. sink.write(content.c_str(), content.size());
  9916. return true;
  9917. },
  9918. "text/plain");
  9919. ASSERT_TRUE(result);
  9920. EXPECT_EQ(200, result->status);
  9921. result = cli.Post(
  9922. "/hi", content.size(),
  9923. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9924. sink.write(content.c_str(), content.size());
  9925. return true;
  9926. },
  9927. "text/plain");
  9928. ASSERT_TRUE(result);
  9929. EXPECT_EQ(200, result->status);
  9930. }
  9931. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9932. using namespace httplib::tls;
  9933. {
  9934. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9935. ASSERT_TRUE(svr.is_valid());
  9936. svr.Get("/sni", [&](const Request &req, Response &res) {
  9937. std::string expected = req.sni();
  9938. EXPECT_EQ(expected, req.get_param_value("expected"));
  9939. res.set_content("ok", "text/plain");
  9940. });
  9941. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9942. auto se = detail::scope_exit([&] {
  9943. svr.stop();
  9944. listen_thread.join();
  9945. ASSERT_FALSE(svr.is_running());
  9946. });
  9947. svr.wait_until_ready();
  9948. {
  9949. SSLClient cli("localhost", PORT);
  9950. cli.enable_server_certificate_verification(false);
  9951. auto res = cli.Get("/sni?expected=localhost");
  9952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9953. }
  9954. {
  9955. SSLClient cli("::1", PORT);
  9956. cli.enable_server_certificate_verification(false);
  9957. auto res = cli.Get("/sni?expected=");
  9958. // NOTE: This may fail if the server is listening on IPv4 only
  9959. // (e.g., when localhost resolves to 127.0.0.1 only)
  9960. if (res) {
  9961. EXPECT_EQ(StatusCode::OK_200, res->status);
  9962. } else {
  9963. EXPECT_EQ(Error::Connection, res.error());
  9964. }
  9965. }
  9966. }
  9967. }
  9968. #endif
  9969. TEST(ClientProblemDetectionTest, ContentProvider) {
  9970. Server svr;
  9971. size_t content_length = 1024 * 1024;
  9972. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9973. res.set_content_provider(
  9974. content_length, "text/plain",
  9975. [&](size_t offset, size_t length, DataSink &sink) {
  9976. auto out_len = std::min(length, static_cast<size_t>(1024));
  9977. std::string out(out_len, '@');
  9978. sink.write(out.data(), out_len);
  9979. return offset < 4096;
  9980. },
  9981. [](bool success) { ASSERT_FALSE(success); });
  9982. });
  9983. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9984. res.set_content_provider(
  9985. 0, "text/plain",
  9986. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9987. EXPECT_TRUE(false);
  9988. return true;
  9989. },
  9990. [](bool success) { ASSERT_FALSE(success); });
  9991. });
  9992. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9993. auto se = detail::scope_exit([&] {
  9994. svr.stop();
  9995. listen_thread.join();
  9996. ASSERT_FALSE(svr.is_running());
  9997. });
  9998. svr.wait_until_ready();
  9999. Client cli("localhost", PORT);
  10000. {
  10001. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10002. size_t /*data_length*/) { return false; });
  10003. ASSERT_FALSE(res);
  10004. }
  10005. {
  10006. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10007. size_t /*data_length*/) { return false; });
  10008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10009. }
  10010. }
  10011. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10012. // A provider that reports success without writing anything and without
  10013. // calling done() used to be handed the same offset and length again on every
  10014. // pass, so it spun for as long as the peer stayed connected.
  10015. Server svr;
  10016. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10017. res.set_content("ok", "text/plain");
  10018. });
  10019. auto port = svr.bind_to_any_port(HOST);
  10020. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10021. auto se = detail::scope_exit([&] {
  10022. svr.stop();
  10023. listen_thread.join();
  10024. ASSERT_FALSE(svr.is_running());
  10025. });
  10026. svr.wait_until_ready();
  10027. std::atomic<int> call_count{0};
  10028. Client cli(HOST, port);
  10029. auto res = cli.Post(
  10030. "/", 1024,
  10031. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10032. // Give up after enough passes to show the spin, so that losing the
  10033. // check below fails this test instead of hanging it.
  10034. return ++call_count < 100;
  10035. },
  10036. "text/plain");
  10037. ASSERT_FALSE(res);
  10038. EXPECT_EQ(Error::Write, res.error());
  10039. EXPECT_EQ(1, call_count.load());
  10040. }
  10041. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10042. // A writer only has to assign `write`. The other three used to be left as
  10043. // empty std::functions, so a provider calling one threw
  10044. // std::bad_function_call out of the thread running it and took the whole
  10045. // process down.
  10046. DataSink sink;
  10047. std::string written;
  10048. sink.write = [&](const char *data, size_t data_len) {
  10049. written.append(data, data_len);
  10050. return true;
  10051. };
  10052. EXPECT_TRUE(sink.is_writable());
  10053. sink.done();
  10054. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10055. EXPECT_TRUE(written.empty());
  10056. }
  10057. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10058. // A sink that cannot carry trailers still has to finish.
  10059. DataSink sink;
  10060. auto done_count = 0;
  10061. sink.done = [&]() { done_count++; };
  10062. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10063. EXPECT_EQ(1, done_count);
  10064. }
  10065. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10066. Server svr;
  10067. const std::string body(4096, 'x');
  10068. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10069. res.set_content_provider(body.size(), "text/plain",
  10070. [&](size_t offset, size_t length, DataSink &sink) {
  10071. sink.write(body.data() + offset, length);
  10072. sink.done();
  10073. return true;
  10074. });
  10075. });
  10076. auto port = svr.bind_to_any_port(HOST);
  10077. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10078. auto se = detail::scope_exit([&] {
  10079. svr.stop();
  10080. listen_thread.join();
  10081. ASSERT_FALSE(svr.is_running());
  10082. });
  10083. svr.wait_until_ready();
  10084. Client cli(HOST, port);
  10085. auto res = cli.Get("/");
  10086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10087. EXPECT_EQ(StatusCode::OK_200, res->status);
  10088. EXPECT_EQ(body, res->body);
  10089. }
  10090. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10091. Server svr;
  10092. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10093. res.set_content_provider(
  10094. 1024, "text/plain",
  10095. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10096. sink.write("hello", 5);
  10097. sink.done(); // short of the 1024 bytes the response promised
  10098. return true;
  10099. });
  10100. });
  10101. auto port = svr.bind_to_any_port(HOST);
  10102. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10103. auto se = detail::scope_exit([&] {
  10104. svr.stop();
  10105. listen_thread.join();
  10106. ASSERT_FALSE(svr.is_running());
  10107. });
  10108. svr.wait_until_ready();
  10109. Client cli(HOST, port);
  10110. cli.set_read_timeout(5, 0);
  10111. // The response is short of its Content-Length, so the client cannot read a
  10112. // complete body. What matters is that this returns at all: a no-op done()
  10113. // would leave the writer looping over a provider that never makes progress.
  10114. auto res = cli.Get("/");
  10115. EXPECT_FALSE(res);
  10116. }
  10117. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10118. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10119. // The compressed path builds the whole body before connecting, so this
  10120. // fails client-side and never reaches a server.
  10121. Client cli(HOST, PORT);
  10122. cli.set_compress(true);
  10123. auto res = cli.Post(
  10124. "/", 1024,
  10125. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10126. sink.write("hello", 5);
  10127. sink.done(); // short of the 1024 bytes the request announced
  10128. return true;
  10129. },
  10130. "text/plain");
  10131. ASSERT_FALSE(res);
  10132. EXPECT_EQ(Error::Write, res.error());
  10133. }
  10134. #endif
  10135. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10136. Server svr;
  10137. svr.set_error_handler([](Request const &, Response &res) -> void {
  10138. res.set_chunked_content_provider(
  10139. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10140. sink.os << "hello";
  10141. sink.os << "world";
  10142. sink.done();
  10143. return true;
  10144. });
  10145. });
  10146. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10147. auto se = detail::scope_exit([&] {
  10148. svr.stop();
  10149. listen_thread.join();
  10150. ASSERT_FALSE(svr.is_running());
  10151. });
  10152. svr.wait_until_ready();
  10153. Client cli("localhost", PORT);
  10154. auto res = cli.Get("/");
  10155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10156. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10157. EXPECT_EQ("helloworld", res->body);
  10158. }
  10159. TEST(LongPollingTest, ClientCloseDetection) {
  10160. Server svr;
  10161. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10162. res.set_chunked_content_provider(
  10163. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10164. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10165. sink.os << "hello";
  10166. auto count = 10;
  10167. while (count > 0 && sink.is_writable()) {
  10168. this_thread::sleep_for(chrono::milliseconds(10));
  10169. count--;
  10170. }
  10171. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10172. return true;
  10173. });
  10174. });
  10175. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10176. auto se = detail::scope_exit([&] {
  10177. svr.stop();
  10178. listen_thread.join();
  10179. ASSERT_FALSE(svr.is_running());
  10180. });
  10181. svr.wait_until_ready();
  10182. Client cli("localhost", PORT);
  10183. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10184. EXPECT_EQ("hello", string(data, data_length));
  10185. return false; // close the socket immediately.
  10186. });
  10187. ASSERT_FALSE(res);
  10188. }
  10189. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10190. Server svr;
  10191. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10192. res.set_chunked_content_provider(
  10193. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10194. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10195. sink.os << "hello";
  10196. EXPECT_TRUE(sink.os.good());
  10197. // Wait for the client to close the connection
  10198. auto count = 10;
  10199. while (count > 0 && sink.is_writable()) {
  10200. this_thread::sleep_for(chrono::milliseconds(10));
  10201. count--;
  10202. }
  10203. // After client disconnect, write repeatedly until the socket
  10204. // write actually fails (small writes may be absorbed by the
  10205. // kernel buffer)
  10206. std::string chunk(1024, 'x');
  10207. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10208. sink.os << chunk;
  10209. }
  10210. EXPECT_TRUE(sink.os.fail());
  10211. return true;
  10212. });
  10213. });
  10214. auto port = svr.bind_to_any_port("localhost");
  10215. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10216. auto se = detail::scope_exit([&] {
  10217. svr.stop();
  10218. listen_thread.join();
  10219. ASSERT_FALSE(svr.is_running());
  10220. });
  10221. svr.wait_until_ready();
  10222. Client cli("localhost", port);
  10223. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10224. EXPECT_EQ("hello", string(data, data_length));
  10225. return false; // close the socket immediately.
  10226. });
  10227. ASSERT_FALSE(res);
  10228. }
  10229. TEST(GetWithParametersTest, GetWithParameters) {
  10230. Server svr;
  10231. svr.Get("/", [&](const Request &req, Response &) {
  10232. EXPECT_EQ("world", req.get_param_value("hello"));
  10233. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10234. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10235. });
  10236. svr.Get("/params", [&](const Request &req, Response &) {
  10237. EXPECT_EQ("world", req.get_param_value("hello"));
  10238. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10239. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10240. });
  10241. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10242. EXPECT_EQ("resource-id", req.matches[1]);
  10243. EXPECT_EQ("foo", req.get_param_value("param1"));
  10244. EXPECT_EQ("bar", req.get_param_value("param2"));
  10245. });
  10246. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10247. EXPECT_EQ("user-id", req.path_params.at("id"));
  10248. EXPECT_EQ("foo", req.get_param_value("param1"));
  10249. EXPECT_EQ("bar", req.get_param_value("param2"));
  10250. });
  10251. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10252. auto se = detail::scope_exit([&] {
  10253. svr.stop();
  10254. listen_thread.join();
  10255. ASSERT_FALSE(svr.is_running());
  10256. });
  10257. svr.wait_until_ready();
  10258. {
  10259. Client cli(HOST, PORT);
  10260. Params params;
  10261. params.emplace("hello", "world");
  10262. params.emplace("hello2", "world2");
  10263. params.emplace("hello3", "world3");
  10264. auto res = cli.Get("/", params, Headers{});
  10265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10266. EXPECT_EQ(StatusCode::OK_200, res->status);
  10267. }
  10268. {
  10269. Client cli(HOST, PORT);
  10270. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10272. EXPECT_EQ(StatusCode::OK_200, res->status);
  10273. }
  10274. {
  10275. Client cli(HOST, PORT);
  10276. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10278. EXPECT_EQ(StatusCode::OK_200, res->status);
  10279. }
  10280. {
  10281. Client cli(HOST, PORT);
  10282. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10284. EXPECT_EQ(StatusCode::OK_200, res->status);
  10285. }
  10286. }
  10287. TEST(GetWithParametersTest, GetWithParameters2) {
  10288. Server svr;
  10289. svr.Get("/", [&](const Request &req, Response &res) {
  10290. auto text = req.get_param_value("hello");
  10291. res.set_content(text, "text/plain");
  10292. });
  10293. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10294. auto se = detail::scope_exit([&] {
  10295. svr.stop();
  10296. listen_thread.join();
  10297. ASSERT_FALSE(svr.is_running());
  10298. });
  10299. svr.wait_until_ready();
  10300. Client cli("localhost", PORT);
  10301. Params params;
  10302. params.emplace("hello", "world");
  10303. std::string body;
  10304. auto res = cli.Get("/", params, Headers{},
  10305. [&](const char *data, size_t data_length) {
  10306. body.append(data, data_length);
  10307. return true;
  10308. });
  10309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10310. EXPECT_EQ(StatusCode::OK_200, res->status);
  10311. EXPECT_EQ("world", body);
  10312. }
  10313. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10314. Server svr;
  10315. svr.Get("/search", [&](const Request &req, Response &res) {
  10316. auto q = req.get_param_value("q");
  10317. res.set_content(q, "text/plain");
  10318. });
  10319. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10320. auto se = detail::scope_exit([&] {
  10321. svr.stop();
  10322. listen_thread.join();
  10323. ASSERT_FALSE(svr.is_running());
  10324. });
  10325. svr.wait_until_ready();
  10326. Client cli("localhost", PORT);
  10327. // Verify that Get(path, params) works without requiring Headers argument
  10328. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10330. EXPECT_EQ(StatusCode::OK_200, res->status);
  10331. EXPECT_EQ("cpp-httplib", res->body);
  10332. }
  10333. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10334. auto host = "httpbingo.org";
  10335. auto path = std::string{"/range/32"};
  10336. #ifdef CPPHTTPLIB_SSL_ENABLED
  10337. SSLClient cli(host);
  10338. #else
  10339. Client cli(host);
  10340. #endif
  10341. cli.set_default_headers({make_range_header({{1, 10}})});
  10342. cli.set_connection_timeout(5);
  10343. {
  10344. auto res = cli.Get(path);
  10345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10346. EXPECT_EQ("bcdefghijk", res->body);
  10347. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10348. }
  10349. {
  10350. auto res = cli.Get(path);
  10351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10352. EXPECT_EQ("bcdefghijk", res->body);
  10353. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10354. }
  10355. }
  10356. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10357. Server svr;
  10358. svr.set_default_headers({{"Hello", "World"}});
  10359. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10360. res.set_content("ok", "text/plain");
  10361. });
  10362. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10363. auto se = detail::scope_exit([&] {
  10364. svr.stop();
  10365. listen_thread.join();
  10366. ASSERT_FALSE(svr.is_running());
  10367. });
  10368. svr.wait_until_ready();
  10369. Client cli("localhost", PORT);
  10370. auto res = cli.Get("/");
  10371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10372. EXPECT_EQ(StatusCode::OK_200, res->status);
  10373. EXPECT_EQ("ok", res->body);
  10374. EXPECT_EQ("World", res->get_header_value("Hello"));
  10375. }
  10376. #ifdef CPPHTTPLIB_SSL_ENABLED
  10377. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10378. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10379. ASSERT_TRUE(svr.is_valid());
  10380. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10381. std::this_thread::sleep_for(std::chrono::seconds(2));
  10382. res.set_content("a", "text/plain");
  10383. });
  10384. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10385. res.set_content("b", "text/plain");
  10386. });
  10387. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10388. auto se = detail::scope_exit([&] {
  10389. svr.stop();
  10390. listen_thread.join();
  10391. ASSERT_FALSE(svr.is_running());
  10392. });
  10393. svr.wait_until_ready();
  10394. SSLClient cli("localhost", PORT);
  10395. cli.enable_server_certificate_verification(false);
  10396. cli.set_keep_alive(true);
  10397. cli.set_read_timeout(std::chrono::seconds(1));
  10398. auto resa = cli.Get("/a");
  10399. ASSERT_TRUE(!resa);
  10400. EXPECT_EQ(Error::Read, resa.error());
  10401. auto resb = cli.Get("/b");
  10402. ASSERT_TRUE(resb);
  10403. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10404. EXPECT_EQ("b", resb->body);
  10405. }
  10406. // Closing an idle keep-alive connection sends close_notify and returns. The
  10407. // server must not wait for the client's close_notify: an idle client never
  10408. // sends one, so the worker would be held until the read timeout expires, and
  10409. // stop() would wait for it.
  10410. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10412. ASSERT_TRUE(svr.is_valid());
  10413. svr.set_keep_alive_timeout(1);
  10414. svr.set_read_timeout(10, 0);
  10415. svr.Get("/", [](const Request &, Response &res) {
  10416. res.set_content("ok", "text/plain");
  10417. });
  10418. auto port = svr.bind_to_any_port(HOST);
  10419. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10420. auto se = detail::scope_exit([&] {
  10421. if (listen_thread.joinable()) {
  10422. svr.stop();
  10423. listen_thread.join();
  10424. }
  10425. });
  10426. svr.wait_until_ready();
  10427. SSLClient cli(HOST, port);
  10428. cli.enable_server_certificate_verification(false);
  10429. cli.set_keep_alive(true);
  10430. auto res = cli.Get("/");
  10431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10432. EXPECT_EQ(StatusCode::OK_200, res->status);
  10433. // Stay idle past the keep-alive timeout so the server closes the connection.
  10434. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10435. auto start = std::chrono::steady_clock::now();
  10436. svr.stop();
  10437. listen_thread.join();
  10438. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10439. std::chrono::steady_clock::now() - start)
  10440. .count();
  10441. EXPECT_LT(elapsed, 3000);
  10442. }
  10443. #endif
  10444. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10445. protected:
  10446. ServerTestWithAI_PASSIVE()
  10447. : cli_(HOST, PORT)
  10448. #ifdef CPPHTTPLIB_SSL_ENABLED
  10449. ,
  10450. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10451. #endif
  10452. {
  10453. #ifdef CPPHTTPLIB_SSL_ENABLED
  10454. cli_.enable_server_certificate_verification(false);
  10455. #endif
  10456. }
  10457. virtual void SetUp() {
  10458. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10459. res.set_content("Hello World!", "text/plain");
  10460. });
  10461. t_ = thread(
  10462. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10463. svr_.wait_until_ready();
  10464. }
  10465. virtual void TearDown() {
  10466. svr_.stop();
  10467. t_.join();
  10468. }
  10469. #ifdef CPPHTTPLIB_SSL_ENABLED
  10470. SSLClient cli_;
  10471. SSLServer svr_;
  10472. #else
  10473. Client cli_;
  10474. Server svr_;
  10475. #endif
  10476. thread t_;
  10477. };
  10478. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10479. auto res = cli_.Get("/hi");
  10480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10481. EXPECT_EQ(StatusCode::OK_200, res->status);
  10482. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10483. EXPECT_EQ("Hello World!", res->body);
  10484. }
  10485. class ServerUpDownTest : public ::testing::Test {
  10486. protected:
  10487. ServerUpDownTest() : cli_(HOST, PORT) {}
  10488. virtual void SetUp() {
  10489. t_ = thread([&]() {
  10490. svr_.bind_to_any_port(HOST);
  10491. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10492. ASSERT_TRUE(svr_.listen_after_bind());
  10493. });
  10494. svr_.wait_until_ready();
  10495. }
  10496. virtual void TearDown() {
  10497. svr_.stop();
  10498. t_.join();
  10499. }
  10500. Client cli_;
  10501. Server svr_;
  10502. thread t_;
  10503. };
  10504. TEST_F(ServerUpDownTest, QuickStartStop) {
  10505. // Should not crash, especially when run with
  10506. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10507. }
  10508. class PayloadMaxLengthTest : public ::testing::Test {
  10509. protected:
  10510. PayloadMaxLengthTest()
  10511. : cli_(HOST, PORT)
  10512. #ifdef CPPHTTPLIB_SSL_ENABLED
  10513. ,
  10514. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10515. #endif
  10516. {
  10517. #ifdef CPPHTTPLIB_SSL_ENABLED
  10518. cli_.enable_server_certificate_verification(false);
  10519. #endif
  10520. }
  10521. virtual void SetUp() {
  10522. svr_.set_payload_max_length(8);
  10523. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10524. res.set_content("test", "text/plain");
  10525. });
  10526. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10527. svr_.wait_until_ready();
  10528. }
  10529. virtual void TearDown() {
  10530. svr_.stop();
  10531. t_.join();
  10532. }
  10533. #ifdef CPPHTTPLIB_SSL_ENABLED
  10534. SSLClient cli_;
  10535. SSLServer svr_;
  10536. #else
  10537. Client cli_;
  10538. Server svr_;
  10539. #endif
  10540. thread t_;
  10541. };
  10542. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10543. auto res = cli_.Post("/test", "123456789", "text/plain");
  10544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10545. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10546. res = cli_.Post("/test", "12345678", "text/plain");
  10547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10548. EXPECT_EQ(StatusCode::OK_200, res->status);
  10549. }
  10550. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10551. // Test chunked encoding with payload exceeding the 8-byte limit
  10552. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10553. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10555. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10556. }
  10557. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10558. // Test chunked encoding with payload within the 8-byte limit
  10559. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10560. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10562. EXPECT_EQ(StatusCode::OK_200, res->status);
  10563. }
  10564. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10565. // Test using send_request to send chunked data exceeding payload limit
  10566. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10567. "Host: " +
  10568. std::string(HOST) + ":" + std::to_string(PORT) +
  10569. "\r\n"
  10570. "Transfer-Encoding: chunked\r\n"
  10571. "Connection: close\r\n"
  10572. "\r\n"
  10573. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10574. "0123456789\r\n"
  10575. "0\r\n" // End chunk
  10576. "\r\n";
  10577. std::string response;
  10578. bool result = send_request(1, chunked_request, &response);
  10579. if (!result) {
  10580. // If send_request fails, it might be because the server closed the
  10581. // connection due to payload limit enforcement, which is acceptable
  10582. SUCCEED()
  10583. << "Server rejected oversized chunked request (connection closed)";
  10584. } else {
  10585. // If we got a response, check if it's an error response or connection was
  10586. // closed early Short response length indicates connection was closed due to
  10587. // payload limit
  10588. if (response.length() <= 10) {
  10589. SUCCEED() << "Server closed connection for oversized chunked request";
  10590. } else {
  10591. // Check for error status codes
  10592. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10593. response.find("Payload Too Large") != std::string::npos ||
  10594. response.find("400") != std::string::npos);
  10595. }
  10596. }
  10597. }
  10598. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10599. // Test request without Content-Length header exceeding payload limit
  10600. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10601. "Host: " +
  10602. std::string(HOST) + ":" +
  10603. std::to_string(PORT) +
  10604. "\r\n"
  10605. "Connection: close\r\n"
  10606. "\r\n";
  10607. // Add payload exceeding the 8-byte limit
  10608. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10609. request_without_content_length += large_payload;
  10610. std::string response;
  10611. bool result = send_request(1, request_without_content_length, &response);
  10612. if (!result) {
  10613. // If send_request fails, server likely closed connection due to payload
  10614. // limit
  10615. SUCCEED() << "Server rejected oversized request without Content-Length "
  10616. "(connection closed)";
  10617. } else {
  10618. // Check if server responded with error or closed connection early
  10619. if (response.length() <= 10) {
  10620. SUCCEED() << "Server closed connection for oversized request without "
  10621. "Content-Length";
  10622. } else {
  10623. // Check for error status codes
  10624. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10625. response.find("Payload Too Large") != std::string::npos ||
  10626. response.find("400") != std::string::npos);
  10627. }
  10628. }
  10629. }
  10630. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10631. // Test request without Content-Length header within payload limit
  10632. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10633. "Host: " +
  10634. std::string(HOST) + ":" +
  10635. std::to_string(PORT) +
  10636. "\r\n"
  10637. "Connection: close\r\n"
  10638. "\r\n";
  10639. // Add payload within the 8-byte limit
  10640. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10641. request_without_content_length += small_payload;
  10642. std::string response;
  10643. bool result = send_request(1, request_without_content_length, &response);
  10644. // For requests without Content-Length, the server may have different behavior
  10645. // The key is that it should not reject due to payload limit for small
  10646. // payloads
  10647. if (result) {
  10648. // Check for any HTTP response (success or error, but not connection closed)
  10649. if (response.length() > 10) {
  10650. SUCCEED()
  10651. << "Server processed request without Content-Length within limit";
  10652. } else {
  10653. // Short response might indicate connection closed, which is acceptable
  10654. SUCCEED() << "Server closed connection for request without "
  10655. "Content-Length (acceptable behavior)";
  10656. }
  10657. } else {
  10658. // Connection failure might be due to protocol requirements
  10659. SUCCEED() << "Connection issue with request without Content-Length "
  10660. "(environment-specific)";
  10661. }
  10662. }
  10663. class LargePayloadMaxLengthTest : public ::testing::Test {
  10664. protected:
  10665. LargePayloadMaxLengthTest()
  10666. : cli_(HOST, PORT)
  10667. #ifdef CPPHTTPLIB_SSL_ENABLED
  10668. ,
  10669. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10670. #endif
  10671. {
  10672. #ifdef CPPHTTPLIB_SSL_ENABLED
  10673. cli_.enable_server_certificate_verification(false);
  10674. #endif
  10675. }
  10676. virtual void SetUp() {
  10677. // Set 10MB payload limit
  10678. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10679. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10680. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10681. res.set_content("Large payload test", "text/plain");
  10682. });
  10683. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10684. svr_.wait_until_ready();
  10685. }
  10686. virtual void TearDown() {
  10687. svr_.stop();
  10688. t_.join();
  10689. }
  10690. #ifdef CPPHTTPLIB_SSL_ENABLED
  10691. SSLClient cli_;
  10692. SSLServer svr_;
  10693. #else
  10694. Client cli_;
  10695. Server svr_;
  10696. #endif
  10697. thread t_;
  10698. };
  10699. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10700. // Test chunked encoding with payload within 10MB limit
  10701. std::string medium_payload(5 * 1024 * 1024,
  10702. 'A'); // 5MB payload, within 10MB limit
  10703. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10705. EXPECT_EQ(StatusCode::OK_200, res->status);
  10706. }
  10707. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10708. // Test chunked encoding with payload exceeding 10MB limit
  10709. std::string large_payload(12 * 1024 * 1024,
  10710. 'B'); // 12MB payload, exceeds 10MB limit
  10711. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10712. // Server may either return 413 or close the connection
  10713. if (res) {
  10714. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10715. } else {
  10716. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10717. }
  10718. }
  10719. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10720. // Test request without Content-Length header within 10MB limit
  10721. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10722. "Host: " +
  10723. std::string(HOST) + ":" +
  10724. std::to_string(PORT) +
  10725. "\r\n"
  10726. "Connection: close\r\n"
  10727. "\r\n";
  10728. // Add 1MB payload (within 10MB limit)
  10729. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10730. request_without_content_length += medium_payload;
  10731. std::string response;
  10732. bool result = send_request(5, request_without_content_length, &response);
  10733. if (result) {
  10734. // Should get a proper HTTP response for payloads within limit
  10735. if (response.length() > 10) {
  10736. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10737. "10MB limit";
  10738. } else {
  10739. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10740. "Content-Length)";
  10741. }
  10742. } else {
  10743. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10744. }
  10745. }
  10746. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10747. // Test request without Content-Length header exceeding 10MB limit
  10748. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10749. "Host: " +
  10750. std::string(HOST) + ":" +
  10751. std::to_string(PORT) +
  10752. "\r\n"
  10753. "Connection: close\r\n"
  10754. "\r\n";
  10755. // Add 12MB payload (exceeds 10MB limit)
  10756. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10757. request_without_content_length += large_payload;
  10758. std::string response;
  10759. bool result = send_request(10, request_without_content_length, &response);
  10760. if (!result) {
  10761. // Server should close connection due to payload limit
  10762. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10763. "(connection closed)";
  10764. } else {
  10765. // Check for error response
  10766. if (response.length() <= 10) {
  10767. SUCCEED()
  10768. << "Server closed connection for 12MB request exceeding 10MB limit";
  10769. } else {
  10770. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10771. response.find("Payload Too Large") != std::string::npos ||
  10772. response.find("400") != std::string::npos);
  10773. }
  10774. }
  10775. }
  10776. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10777. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10778. // path.
  10779. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10780. Server svr;
  10781. const size_t LIMIT = 64 * 1024; // 64KB
  10782. svr.set_payload_max_length(LIMIT);
  10783. size_t total = 0;
  10784. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10785. const ContentReader &content_reader) {
  10786. content_reader([&](const char * /*data*/, size_t len) {
  10787. total += len;
  10788. return true;
  10789. });
  10790. res.status = 200;
  10791. res.set_content("stream_ok", "text/plain");
  10792. });
  10793. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10794. auto se = detail::scope_exit([&] {
  10795. svr.stop();
  10796. thread.join();
  10797. ASSERT_FALSE(svr.is_running());
  10798. });
  10799. svr.wait_until_ready();
  10800. // Prepare 256KB raw data and gzip-compress it
  10801. std::string raw(256 * 1024, 'A');
  10802. std::string gz;
  10803. {
  10804. z_stream zs{};
  10805. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10806. Z_DEFAULT_STRATEGY);
  10807. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10808. zs.avail_in = static_cast<uInt>(raw.size());
  10809. char outbuf[4096];
  10810. int ret;
  10811. do {
  10812. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10813. zs.avail_out = sizeof(outbuf);
  10814. ret = deflate(&zs, Z_FINISH);
  10815. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10816. } while (ret != Z_STREAM_END);
  10817. deflateEnd(&zs);
  10818. }
  10819. Client cli(HOST, PORT);
  10820. cli.set_connection_timeout(std::chrono::seconds(5));
  10821. Headers headers = {{"Content-Encoding", "gzip"}};
  10822. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10823. "application/octet-stream");
  10824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10825. // Server must reject oversized decompressed payloads with 413.
  10826. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10827. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10828. EXPECT_LE(total, LIMIT);
  10829. }
  10830. #ifndef CPPHTTPLIB_SSL_ENABLED
  10831. // For a request with neither Content-Length nor Transfer-Encoding, the
  10832. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10833. // compressed wire bytes straight to the ContentReader without ever routing
  10834. // them through the decompressor, so payload_max_length_ only bounded the
  10835. // compressed size on the wire, not the decompressed size.
  10836. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10837. Server svr;
  10838. const size_t LIMIT = 64 * 1024; // 64KB
  10839. svr.set_payload_max_length(LIMIT);
  10840. size_t total = 0;
  10841. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10842. const ContentReader &content_reader) {
  10843. content_reader([&](const char * /*data*/, size_t len) {
  10844. total += len;
  10845. return true;
  10846. });
  10847. res.status = 200;
  10848. res.set_content("stream_ok", "text/plain");
  10849. });
  10850. auto port = svr.bind_to_any_port(HOST);
  10851. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10852. auto se = detail::scope_exit([&] {
  10853. svr.stop();
  10854. thread.join();
  10855. ASSERT_FALSE(svr.is_running());
  10856. });
  10857. svr.wait_until_ready();
  10858. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10859. // StreamingGzipDecompression test above.
  10860. std::string raw(256 * 1024, 'A');
  10861. std::string gz;
  10862. {
  10863. httplib::detail::gzip_compressor compressor;
  10864. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10865. [&](const char *chunk, size_t len) {
  10866. gz.append(chunk, len);
  10867. return true;
  10868. });
  10869. ASSERT_TRUE(result);
  10870. }
  10871. // Send the gzip body over raw TCP with neither Content-Length nor
  10872. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10873. // kicks in.
  10874. std::string req = "POST /stream HTTP/1.1\r\n"
  10875. "Host: " +
  10876. std::string(HOST) + ":" + std::to_string(port) +
  10877. "\r\n"
  10878. "Content-Encoding: gzip\r\n"
  10879. "Connection: close\r\n"
  10880. "\r\n" +
  10881. gz;
  10882. std::string response;
  10883. ASSERT_TRUE(send_request(5, req, &response, port));
  10884. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10885. EXPECT_LE(total, LIMIT);
  10886. }
  10887. #endif
  10888. #endif
  10889. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10890. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10891. // the payload must be passed through untouched instead of being rejected.
  10892. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10893. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10894. Server svr;
  10895. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10896. res.set_content(body, "image/jpeg");
  10897. res.set_header("Content-Encoding", "UTF-8");
  10898. });
  10899. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10900. res.set_content(body, "image/jpeg");
  10901. res.set_header("Content-Encoding", "identity");
  10902. });
  10903. svr.Post("/echo", [](const Request &req, Response &res) {
  10904. res.set_content(req.body, "image/jpeg");
  10905. });
  10906. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10907. auto se = detail::scope_exit([&] {
  10908. svr.stop();
  10909. t.join();
  10910. ASSERT_FALSE(svr.is_running());
  10911. });
  10912. svr.wait_until_ready();
  10913. Client cli(HOST, PORT);
  10914. {
  10915. auto res = cli.Get("/image");
  10916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10917. EXPECT_EQ(StatusCode::OK_200, res->status);
  10918. EXPECT_EQ(body, res->body);
  10919. }
  10920. {
  10921. auto res = cli.Get("/identity");
  10922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10923. EXPECT_EQ(StatusCode::OK_200, res->status);
  10924. EXPECT_EQ(body, res->body);
  10925. }
  10926. {
  10927. // The same applies to a request body reaching the server.
  10928. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10929. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10931. EXPECT_EQ(StatusCode::OK_200, res->status);
  10932. EXPECT_EQ(body, res->body);
  10933. }
  10934. }
  10935. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10936. // gzip-encoded response even when the build has no zlib support.
  10937. static const char GZIPPED_HELLO_WORLD[] = {
  10938. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10939. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10940. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10941. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10942. // A content coding is a whole token, not something the field value merely
  10943. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10944. // as "fibre" look like Brotli, and turned a multi-coding value like
  10945. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10946. // it was never meant to see.
  10947. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10948. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10949. Server svr;
  10950. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10951. res.set_content(body, "image/jpeg");
  10952. res.set_header("Content-Encoding", "fibre");
  10953. });
  10954. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10955. res.set_content(body, "image/jpeg");
  10956. res.set_header("Content-Encoding", "gzip, br");
  10957. });
  10958. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10959. res.set_content(body, "image/jpeg");
  10960. res.set_header("Content-Encoding", "x-zstd-ish");
  10961. });
  10962. auto port = svr.bind_to_any_port(HOST);
  10963. thread t = thread([&]() { svr.listen_after_bind(); });
  10964. auto se = detail::scope_exit([&] {
  10965. svr.stop();
  10966. t.join();
  10967. ASSERT_FALSE(svr.is_running());
  10968. });
  10969. svr.wait_until_ready();
  10970. Client cli(HOST, port);
  10971. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10972. auto res = cli.Get(path);
  10973. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10974. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10975. // Not a coding we recognize, so the payload comes back untouched
  10976. EXPECT_EQ(body, res->body) << path;
  10977. }
  10978. }
  10979. // A content coding cpp-httplib recognizes but was not built with must be
  10980. // reported as such. Handing the still-compressed payload back to the caller
  10981. // would silently corrupt it.
  10982. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10983. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10984. Server svr;
  10985. // "image/jpeg" keeps the server from applying a content coding of its own,
  10986. // so the hand-crafted Content-Encoding below survives.
  10987. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10988. res.set_content(gzipped, "image/jpeg");
  10989. res.set_header("Content-Encoding", "gzip");
  10990. });
  10991. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10992. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10993. res.set_content(gzipped, "image/jpeg");
  10994. res.set_header("Content-Encoding", "GZIP");
  10995. });
  10996. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10997. auto se = detail::scope_exit([&] {
  10998. svr.stop();
  10999. t.join();
  11000. ASSERT_FALSE(svr.is_running());
  11001. });
  11002. svr.wait_until_ready();
  11003. Client cli(HOST, PORT);
  11004. {
  11005. auto res = cli.Get("/gzipped");
  11006. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11008. EXPECT_EQ("Hello World!", res->body);
  11009. #else
  11010. ASSERT_FALSE(res);
  11011. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11012. #endif
  11013. }
  11014. {
  11015. // open_stream() must behave the same way.
  11016. auto handle = cli.open_stream("GET", "/gzipped");
  11017. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11018. ASSERT_TRUE(handle.is_valid());
  11019. std::string received;
  11020. char buf[256];
  11021. ssize_t n;
  11022. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11023. received.append(buf, static_cast<size_t>(n));
  11024. }
  11025. EXPECT_EQ("Hello World!", received);
  11026. #else
  11027. EXPECT_FALSE(handle.is_valid());
  11028. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11029. #endif
  11030. }
  11031. {
  11032. // A differently-cased coding must not be mistaken for an unknown one, or
  11033. // the body would be handed back still compressed.
  11034. auto res = cli.Get("/gzipped-uppercase");
  11035. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11037. EXPECT_EQ("Hello World!", res->body);
  11038. #else
  11039. ASSERT_FALSE(res);
  11040. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11041. #endif
  11042. }
  11043. }
  11044. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11045. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11046. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11047. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11048. // body a second time and appending a second Content-Encoding field line, so
  11049. // clients that decode one coding per listed value handed back raw gzip bytes.
  11050. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11051. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11052. Server svr;
  11053. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11054. // keeps the server from applying a coding of its own.
  11055. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11056. res.set_content(gzipped, "text/plain");
  11057. res.set_header("Content-Encoding", "gzip");
  11058. });
  11059. auto port = svr.bind_to_any_port(HOST);
  11060. thread t = thread([&]() { svr.listen_after_bind(); });
  11061. auto se = detail::scope_exit([&] {
  11062. svr.stop();
  11063. t.join();
  11064. ASSERT_FALSE(svr.is_running());
  11065. });
  11066. svr.wait_until_ready();
  11067. Client cli(HOST, port);
  11068. Headers headers = {{"Accept-Encoding", "gzip"}};
  11069. auto res = cli.Get("/pre-gzipped", headers);
  11070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11071. EXPECT_EQ(StatusCode::OK_200, res->status);
  11072. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11073. EXPECT_EQ("Hello World!", res->body);
  11074. }
  11075. // A chunked provider settles its coding where the headers are written and
  11076. // reuses it at write time. Both ends of that have to hold: a handler's own
  11077. // Content-Encoding suppresses the coding, and a response without one is still
  11078. // compressed as it always was.
  11079. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11080. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11081. const std::string plain = "Hello World! Hello World! Hello World!";
  11082. Server svr;
  11083. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11084. res.set_header("Content-Encoding", "gzip");
  11085. res.set_chunked_content_provider(
  11086. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11087. sink.write(gzipped.data(), gzipped.size());
  11088. sink.done();
  11089. return true;
  11090. });
  11091. });
  11092. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11093. res.set_chunked_content_provider(
  11094. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11095. sink.write(plain.data(), plain.size());
  11096. sink.done();
  11097. return true;
  11098. });
  11099. });
  11100. auto port = svr.bind_to_any_port(HOST);
  11101. thread t = thread([&]() { svr.listen_after_bind(); });
  11102. auto se = detail::scope_exit([&] {
  11103. svr.stop();
  11104. t.join();
  11105. ASSERT_FALSE(svr.is_running());
  11106. });
  11107. svr.wait_until_ready();
  11108. Client cli(HOST, port);
  11109. Headers headers = {{"Accept-Encoding", "gzip"}};
  11110. {
  11111. auto res = cli.Get("/pre-gzipped", headers);
  11112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11113. EXPECT_EQ(StatusCode::OK_200, res->status);
  11114. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11115. EXPECT_EQ("Hello World!", res->body);
  11116. }
  11117. {
  11118. auto res = cli.Get("/negotiated", headers);
  11119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11120. EXPECT_EQ(StatusCode::OK_200, res->status);
  11121. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11122. EXPECT_EQ(plain, res->body);
  11123. }
  11124. }
  11125. #endif
  11126. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11127. // the same message as the comma-joined one, so both have to be read the same
  11128. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11129. // single gzip coding, and a body the sender says was encoded twice was handed
  11130. // back after one pass, still compressed but presented as decoded.
  11131. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11132. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11133. Server svr;
  11134. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11135. res.set_content(body, "image/jpeg");
  11136. res.headers.emplace("Content-Encoding", "gzip");
  11137. res.headers.emplace("Content-Encoding", "gzip");
  11138. });
  11139. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11140. res.set_content(body, "image/jpeg");
  11141. res.set_header("Content-Encoding", "gzip, gzip");
  11142. });
  11143. auto port = svr.bind_to_any_port(HOST);
  11144. thread t = thread([&]() { svr.listen_after_bind(); });
  11145. auto se = detail::scope_exit([&] {
  11146. svr.stop();
  11147. t.join();
  11148. ASSERT_FALSE(svr.is_running());
  11149. });
  11150. svr.wait_until_ready();
  11151. Client cli(HOST, port);
  11152. // Two codings is not something cpp-httplib decodes, so both representations
  11153. // take the pass-through path rather than one of them being gunzipped once.
  11154. for (const char *path : {"/split", "/joined"}) {
  11155. auto res = cli.Get(path);
  11156. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11157. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11158. EXPECT_EQ(body, res->body) << path;
  11159. }
  11160. }
  11161. // Regression test for DoS vulnerability: a malicious server sending a response
  11162. // without Content-Length header must not cause unbounded memory consumption on
  11163. // the client side. The client should stop reading after a reasonable limit,
  11164. // similar to the server-side set_payload_max_length protection.
  11165. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11166. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11167. #ifndef _WIN32
  11168. signal(SIGPIPE, SIG_IGN);
  11169. #endif
  11170. auto server_thread = std::thread([] {
  11171. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11172. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11173. default_socket_options(srv);
  11174. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11175. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11176. sockaddr_in addr{};
  11177. addr.sin_family = AF_INET;
  11178. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11179. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11180. int opt = 1;
  11181. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11182. #ifdef _WIN32
  11183. reinterpret_cast<const char *>(&opt),
  11184. #else
  11185. &opt,
  11186. #endif
  11187. sizeof(opt));
  11188. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11189. ::listen(srv, 1);
  11190. sockaddr_in cli_addr{};
  11191. socklen_t cli_len = sizeof(cli_addr);
  11192. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11193. if (cli != INVALID_SOCKET) {
  11194. char buf[4096];
  11195. ::recv(cli, buf, sizeof(buf), 0);
  11196. // Malicious response: no Content-Length, no chunked encoding
  11197. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11198. "Connection: close\r\n"
  11199. "\r\n";
  11200. ::send(cli,
  11201. #ifdef _WIN32
  11202. static_cast<const char *>(response_header.c_str()),
  11203. static_cast<int>(response_header.size()),
  11204. #else
  11205. response_header.c_str(), response_header.size(),
  11206. #endif
  11207. 0);
  11208. // Send 10MB of data
  11209. std::string chunk(64 * 1024, 'A');
  11210. size_t total_sent = 0;
  11211. while (total_sent < MALICIOUS_DATA_SIZE) {
  11212. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11213. auto sent = ::send(cli,
  11214. #ifdef _WIN32
  11215. static_cast<const char *>(chunk.c_str()),
  11216. static_cast<int>(to_send),
  11217. #else
  11218. chunk.c_str(), to_send,
  11219. #endif
  11220. 0);
  11221. if (sent <= 0) break;
  11222. total_sent += static_cast<size_t>(sent);
  11223. }
  11224. detail::close_socket(cli);
  11225. }
  11226. detail::close_socket(srv);
  11227. });
  11228. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11229. size_t total_read = 0;
  11230. {
  11231. Client cli("127.0.0.1", PORT + 2);
  11232. cli.set_read_timeout(5, 0);
  11233. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11234. auto stream = cli.open_stream("GET", "/malicious");
  11235. ASSERT_TRUE(stream.is_valid());
  11236. char buffer[64 * 1024];
  11237. ssize_t n;
  11238. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11239. total_read += static_cast<size_t>(n);
  11240. }
  11241. } // StreamHandle and Client destroyed here, closing the socket
  11242. server_thread.join();
  11243. // With set_payload_max_length, the client must stop reading before consuming
  11244. // all 10MB. The read loop should be cut off at or near the configured limit.
  11245. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11246. << "Client read " << total_read << " bytes, exceeding the configured "
  11247. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11248. }
  11249. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11250. // the entire response body without truncation.
  11251. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11252. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11253. #ifndef _WIN32
  11254. signal(SIGPIPE, SIG_IGN);
  11255. #endif
  11256. auto server_thread = std::thread([] {
  11257. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11258. default_socket_options(srv);
  11259. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11260. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11261. sockaddr_in addr{};
  11262. addr.sin_family = AF_INET;
  11263. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11264. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11265. int opt = 1;
  11266. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11267. #ifdef _WIN32
  11268. reinterpret_cast<const char *>(&opt),
  11269. #else
  11270. &opt,
  11271. #endif
  11272. sizeof(opt));
  11273. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11274. ::listen(srv, 1);
  11275. sockaddr_in cli_addr{};
  11276. socklen_t cli_len = sizeof(cli_addr);
  11277. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11278. if (cli != INVALID_SOCKET) {
  11279. char buf[4096];
  11280. ::recv(cli, buf, sizeof(buf), 0);
  11281. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11282. "Connection: close\r\n"
  11283. "\r\n";
  11284. ::send(cli,
  11285. #ifdef _WIN32
  11286. static_cast<const char *>(response_header.c_str()),
  11287. static_cast<int>(response_header.size()),
  11288. #else
  11289. response_header.c_str(), response_header.size(),
  11290. #endif
  11291. 0);
  11292. std::string chunk(64 * 1024, 'A');
  11293. size_t total_sent = 0;
  11294. while (total_sent < DATA_SIZE) {
  11295. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11296. auto sent = ::send(cli,
  11297. #ifdef _WIN32
  11298. static_cast<const char *>(chunk.c_str()),
  11299. static_cast<int>(to_send),
  11300. #else
  11301. chunk.c_str(), to_send,
  11302. #endif
  11303. 0);
  11304. if (sent <= 0) break;
  11305. total_sent += static_cast<size_t>(sent);
  11306. }
  11307. #ifdef _WIN32
  11308. ::shutdown(cli, SD_SEND);
  11309. #else
  11310. ::shutdown(cli, SHUT_WR);
  11311. #endif
  11312. // Drain until the client closes its end, ensuring all data is delivered
  11313. char drain[1024];
  11314. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11315. detail::close_socket(cli);
  11316. }
  11317. detail::close_socket(srv);
  11318. });
  11319. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11320. size_t total_read = 0;
  11321. {
  11322. Client cli("127.0.0.1", PORT + 2);
  11323. cli.set_read_timeout(5, 0);
  11324. cli.set_payload_max_length(0); // 0 means no limit
  11325. auto stream = cli.open_stream("GET", "/data");
  11326. ASSERT_TRUE(stream.is_valid());
  11327. char buffer[64 * 1024];
  11328. ssize_t n;
  11329. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11330. total_read += static_cast<size_t>(n);
  11331. }
  11332. }
  11333. server_thread.join();
  11334. EXPECT_EQ(total_read, DATA_SIZE)
  11335. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11336. << " bytes without truncation, but only read " << total_read << " bytes.";
  11337. }
  11338. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11339. // enormous Content-Length must not cause the client to pre-allocate a huge
  11340. // response body buffer. The reservation is capped at payload_max_length_, and
  11341. // the read itself fails when the body exceeds the limit.
  11342. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11343. #ifndef _WIN32
  11344. signal(SIGPIPE, SIG_IGN);
  11345. #endif
  11346. auto server_thread = std::thread([] {
  11347. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11348. default_socket_options(srv);
  11349. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11350. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11351. sockaddr_in addr{};
  11352. addr.sin_family = AF_INET;
  11353. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11354. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11355. int opt = 1;
  11356. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11357. #ifdef _WIN32
  11358. reinterpret_cast<const char *>(&opt),
  11359. #else
  11360. &opt,
  11361. #endif
  11362. sizeof(opt));
  11363. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11364. ::listen(srv, 1);
  11365. sockaddr_in cli_addr{};
  11366. socklen_t cli_len = sizeof(cli_addr);
  11367. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11368. if (cli != INVALID_SOCKET) {
  11369. char buf[4096];
  11370. ::recv(cli, buf, sizeof(buf), 0);
  11371. // Malicious response: claim a 20GB body but send only a tiny payload.
  11372. std::string response = "HTTP/1.1 200 OK\r\n"
  11373. "Content-Length: 20000000000\r\n"
  11374. "\r\n"
  11375. "abc";
  11376. ::send(cli,
  11377. #ifdef _WIN32
  11378. static_cast<const char *>(response.c_str()),
  11379. static_cast<int>(response.size()),
  11380. #else
  11381. response.c_str(), response.size(),
  11382. #endif
  11383. 0);
  11384. detail::close_socket(cli);
  11385. }
  11386. detail::close_socket(srv);
  11387. });
  11388. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11389. {
  11390. Client cli("127.0.0.1", PORT + 2);
  11391. cli.set_read_timeout(5, 0);
  11392. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11393. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11394. // (server claims more bytes than payload_max_length permits), but it must
  11395. // not exhaust memory before getting there.
  11396. auto res = cli.Get("/malicious");
  11397. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11398. }
  11399. server_thread.join();
  11400. }
  11401. // Verify that content_receiver bypasses the default payload_max_length,
  11402. // allowing streaming downloads larger than 100MB without requiring an explicit
  11403. // set_payload_max_length call.
  11404. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11405. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11406. #ifndef _WIN32
  11407. signal(SIGPIPE, SIG_IGN);
  11408. #endif
  11409. auto server_thread = std::thread([] {
  11410. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11411. default_socket_options(srv);
  11412. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11413. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11414. sockaddr_in addr{};
  11415. addr.sin_family = AF_INET;
  11416. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11417. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11418. int opt = 1;
  11419. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11420. #ifdef _WIN32
  11421. reinterpret_cast<const char *>(&opt),
  11422. #else
  11423. &opt,
  11424. #endif
  11425. sizeof(opt));
  11426. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11427. ::listen(srv, 1);
  11428. sockaddr_in cli_addr{};
  11429. socklen_t cli_len = sizeof(cli_addr);
  11430. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11431. if (cli != INVALID_SOCKET) {
  11432. char buf[4096];
  11433. ::recv(cli, buf, sizeof(buf), 0);
  11434. // Response with Content-Length larger than default 100MB limit
  11435. auto content_length = std::to_string(DATA_SIZE);
  11436. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11437. "Content-Length: " +
  11438. content_length +
  11439. "\r\n"
  11440. "Connection: close\r\n"
  11441. "\r\n";
  11442. ::send(cli,
  11443. #ifdef _WIN32
  11444. static_cast<const char *>(response_header.c_str()),
  11445. static_cast<int>(response_header.size()),
  11446. #else
  11447. response_header.c_str(), response_header.size(),
  11448. #endif
  11449. 0);
  11450. std::string chunk(64 * 1024, 'A');
  11451. size_t total_sent = 0;
  11452. while (total_sent < DATA_SIZE) {
  11453. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11454. auto sent = ::send(cli,
  11455. #ifdef _WIN32
  11456. static_cast<const char *>(chunk.c_str()),
  11457. static_cast<int>(to_send),
  11458. #else
  11459. chunk.c_str(), to_send,
  11460. #endif
  11461. 0);
  11462. if (sent <= 0) break;
  11463. total_sent += static_cast<size_t>(sent);
  11464. }
  11465. detail::close_socket(cli);
  11466. }
  11467. detail::close_socket(srv);
  11468. });
  11469. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11470. size_t total_received = 0;
  11471. {
  11472. Client cli("127.0.0.1", PORT + 2);
  11473. cli.set_read_timeout(10, 0);
  11474. // Do NOT call set_payload_max_length — use the default 100MB limit
  11475. auto res =
  11476. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11477. total_received += data_length;
  11478. return true;
  11479. });
  11480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11481. EXPECT_EQ(StatusCode::OK_200, res->status);
  11482. }
  11483. server_thread.join();
  11484. EXPECT_EQ(total_received, DATA_SIZE)
  11485. << "With content_receiver, the client should read all " << DATA_SIZE
  11486. << " bytes despite the default 100MB payload_max_length, but only read "
  11487. << total_received << " bytes.";
  11488. }
  11489. // Verify that an explicit set_payload_max_length smaller than the response is
  11490. // enforced even when a content_receiver is used.
  11491. TEST(ClientVulnerabilityTest,
  11492. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11493. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11494. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11495. #ifndef _WIN32
  11496. signal(SIGPIPE, SIG_IGN);
  11497. #endif
  11498. auto server_thread = std::thread([] {
  11499. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11500. default_socket_options(srv);
  11501. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11502. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11503. sockaddr_in addr{};
  11504. addr.sin_family = AF_INET;
  11505. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11506. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11507. int opt = 1;
  11508. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11509. #ifdef _WIN32
  11510. reinterpret_cast<const char *>(&opt),
  11511. #else
  11512. &opt,
  11513. #endif
  11514. sizeof(opt));
  11515. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11516. ::listen(srv, 1);
  11517. sockaddr_in cli_addr{};
  11518. socklen_t cli_len = sizeof(cli_addr);
  11519. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11520. if (cli != INVALID_SOCKET) {
  11521. char buf[4096];
  11522. ::recv(cli, buf, sizeof(buf), 0);
  11523. auto content_length = std::to_string(DATA_SIZE);
  11524. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11525. "Content-Length: " +
  11526. content_length +
  11527. "\r\n"
  11528. "Connection: close\r\n"
  11529. "\r\n";
  11530. ::send(cli,
  11531. #ifdef _WIN32
  11532. static_cast<const char *>(response_header.c_str()),
  11533. static_cast<int>(response_header.size()),
  11534. #else
  11535. response_header.c_str(), response_header.size(),
  11536. #endif
  11537. 0);
  11538. std::string chunk(64 * 1024, 'A');
  11539. size_t total_sent = 0;
  11540. while (total_sent < DATA_SIZE) {
  11541. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11542. auto sent = ::send(cli,
  11543. #ifdef _WIN32
  11544. static_cast<const char *>(chunk.c_str()),
  11545. static_cast<int>(to_send),
  11546. #else
  11547. chunk.c_str(), to_send,
  11548. #endif
  11549. 0);
  11550. if (sent <= 0) break;
  11551. total_sent += static_cast<size_t>(sent);
  11552. }
  11553. detail::close_socket(cli);
  11554. }
  11555. detail::close_socket(srv);
  11556. });
  11557. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11558. size_t total_received = 0;
  11559. {
  11560. Client cli("127.0.0.1", PORT + 2);
  11561. cli.set_read_timeout(10, 0);
  11562. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11563. auto res =
  11564. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11565. total_received += data_length;
  11566. return true;
  11567. });
  11568. // Should fail because 200MB exceeds the explicit 150MB limit
  11569. EXPECT_FALSE(res);
  11570. }
  11571. server_thread.join();
  11572. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11573. << "Client with content_receiver should respect the explicit "
  11574. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11575. << total_received << " bytes.";
  11576. }
  11577. // Verify that an explicit set_payload_max_length larger than the response
  11578. // allows the content_receiver to read all data successfully.
  11579. TEST(ClientVulnerabilityTest,
  11580. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11581. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11582. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11583. #ifndef _WIN32
  11584. signal(SIGPIPE, SIG_IGN);
  11585. #endif
  11586. auto server_thread = std::thread([] {
  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. auto content_length = std::to_string(DATA_SIZE);
  11612. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11613. "Content-Length: " +
  11614. content_length +
  11615. "\r\n"
  11616. "Connection: close\r\n"
  11617. "\r\n";
  11618. ::send(cli,
  11619. #ifdef _WIN32
  11620. static_cast<const char *>(response_header.c_str()),
  11621. static_cast<int>(response_header.size()),
  11622. #else
  11623. response_header.c_str(), response_header.size(),
  11624. #endif
  11625. 0);
  11626. std::string chunk(64 * 1024, 'A');
  11627. size_t total_sent = 0;
  11628. while (total_sent < DATA_SIZE) {
  11629. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11630. auto sent = ::send(cli,
  11631. #ifdef _WIN32
  11632. static_cast<const char *>(chunk.c_str()),
  11633. static_cast<int>(to_send),
  11634. #else
  11635. chunk.c_str(), to_send,
  11636. #endif
  11637. 0);
  11638. if (sent <= 0) break;
  11639. total_sent += static_cast<size_t>(sent);
  11640. }
  11641. #ifdef _WIN32
  11642. ::shutdown(cli, SD_SEND);
  11643. #else
  11644. ::shutdown(cli, SHUT_WR);
  11645. #endif
  11646. char drain[1024];
  11647. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11648. detail::close_socket(cli);
  11649. }
  11650. detail::close_socket(srv);
  11651. });
  11652. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11653. size_t total_received = 0;
  11654. {
  11655. Client cli("127.0.0.1", PORT + 2);
  11656. cli.set_read_timeout(10, 0);
  11657. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11658. auto res =
  11659. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11660. total_received += data_length;
  11661. return true;
  11662. });
  11663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11664. EXPECT_EQ(StatusCode::OK_200, res->status);
  11665. }
  11666. server_thread.join();
  11667. EXPECT_EQ(total_received, DATA_SIZE)
  11668. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11669. << " bytes (larger than " << DATA_SIZE
  11670. << " bytes response), content_receiver should read all data, but only "
  11671. "read "
  11672. << total_received << " bytes.";
  11673. }
  11674. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11675. // Regression test for "zip bomb" attack on the client side: a malicious server
  11676. // sends a small gzip-compressed response that decompresses to a huge payload.
  11677. // The client must enforce payload_max_length on the decompressed size.
  11678. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11679. constexpr size_t DECOMPRESSED_SIZE =
  11680. 10 * 1024 * 1024; // 10MB after decompression
  11681. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11682. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11683. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11684. std::string compressed;
  11685. {
  11686. httplib::detail::gzip_compressor compressor;
  11687. bool ok =
  11688. compressor.compress(uncompressed.data(), uncompressed.size(),
  11689. /*last=*/true, [&](const char *buf, size_t len) {
  11690. compressed.append(buf, len);
  11691. return true;
  11692. });
  11693. ASSERT_TRUE(ok);
  11694. }
  11695. // Sanity: compressed data should be much smaller than the decompressed size
  11696. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11697. #ifndef _WIN32
  11698. signal(SIGPIPE, SIG_IGN);
  11699. #endif
  11700. // Set up the listening socket in the main thread so the server is guaranteed
  11701. // to be ready before the client connects (eliminates race condition).
  11702. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11703. default_socket_options(srv);
  11704. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11705. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11706. sockaddr_in addr{};
  11707. addr.sin_family = AF_INET;
  11708. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11709. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11710. int opt = 1;
  11711. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11712. #ifdef _WIN32
  11713. reinterpret_cast<const char *>(&opt),
  11714. #else
  11715. &opt,
  11716. #endif
  11717. sizeof(opt));
  11718. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11719. ASSERT_EQ(0, ::listen(srv, 1));
  11720. auto server_thread = std::thread([&compressed, srv] {
  11721. sockaddr_in cli_addr{};
  11722. socklen_t cli_len = sizeof(cli_addr);
  11723. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11724. if (cli != INVALID_SOCKET) {
  11725. // Read the full HTTP request (until \r\n\r\n)
  11726. char buf[4096];
  11727. size_t total = 0;
  11728. while (total < sizeof(buf)) {
  11729. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11730. if (n <= 0) break;
  11731. total += static_cast<size_t>(n);
  11732. // Check for end of headers
  11733. if (total >= 4) {
  11734. std::string req(buf, total);
  11735. if (req.find("\r\n\r\n") != std::string::npos) break;
  11736. }
  11737. }
  11738. // Malicious response: gzip-compressed body, no Content-Length
  11739. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11740. "Content-Encoding: gzip\r\n"
  11741. "Connection: close\r\n"
  11742. "\r\n";
  11743. ::send(cli,
  11744. #ifdef _WIN32
  11745. static_cast<const char *>(response_header.c_str()),
  11746. static_cast<int>(response_header.size()),
  11747. #else
  11748. response_header.c_str(), response_header.size(),
  11749. #endif
  11750. 0);
  11751. // Send the compressed payload (small on the wire, huge when decompressed)
  11752. size_t total_sent = 0;
  11753. while (total_sent < compressed.size()) {
  11754. auto to_send = std::min(compressed.size() - total_sent,
  11755. static_cast<size_t>(64 * 1024));
  11756. auto sent =
  11757. ::send(cli,
  11758. #ifdef _WIN32
  11759. static_cast<const char *>(compressed.c_str() + total_sent),
  11760. static_cast<int>(to_send),
  11761. #else
  11762. compressed.c_str() + total_sent, to_send,
  11763. #endif
  11764. 0);
  11765. if (sent <= 0) break;
  11766. total_sent += static_cast<size_t>(sent);
  11767. }
  11768. detail::close_socket(cli);
  11769. }
  11770. });
  11771. auto se = detail::scope_exit([&] {
  11772. detail::close_socket(srv);
  11773. server_thread.join();
  11774. });
  11775. size_t total_decompressed = 0;
  11776. {
  11777. Client cli("127.0.0.1", PORT + 3);
  11778. cli.set_read_timeout(5, 0);
  11779. cli.set_decompress(true);
  11780. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11781. auto stream = cli.open_stream("GET", "/zipbomb");
  11782. ASSERT_TRUE(stream.is_valid());
  11783. char buffer[64 * 1024];
  11784. ssize_t n;
  11785. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11786. total_decompressed += static_cast<size_t>(n);
  11787. }
  11788. }
  11789. // The decompressed size must be capped by payload_max_length. Without
  11790. // protection, the client would decompress the full 10MB from a tiny
  11791. // compressed payload, enabling a zip bomb DoS attack.
  11792. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11793. << "Client decompressed " << total_decompressed
  11794. << " bytes from a gzip response. The decompressed size should be "
  11795. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11796. }
  11797. #endif
  11798. TEST(HostAndPortPropertiesTest, NoSSL) {
  11799. httplib::Client cli("www.google.com", 1234);
  11800. ASSERT_EQ("www.google.com", cli.host());
  11801. ASSERT_EQ(1234, cli.port());
  11802. }
  11803. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11804. httplib::Client cli("www.google.com:1234");
  11805. ASSERT_EQ("www.google.com", cli.host());
  11806. ASSERT_EQ(1234, cli.port());
  11807. }
  11808. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11809. // Port number that overflows int — should not crash, client becomes invalid
  11810. httplib::Client cli("http://www.google.com:99999999999999999999");
  11811. ASSERT_FALSE(cli.is_valid());
  11812. }
  11813. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11814. // Port 99999 exceeds valid range (1-65535) — should not crash
  11815. httplib::Client cli("http://www.google.com:99999");
  11816. ASSERT_FALSE(cli.is_valid());
  11817. }
  11818. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  11819. httplib::Client cli("http://www.google.com:80abc");
  11820. ASSERT_FALSE(cli.is_valid());
  11821. }
  11822. #ifdef CPPHTTPLIB_SSL_ENABLED
  11823. TEST(HostAndPortPropertiesTest, SSL) {
  11824. httplib::SSLClient cli("www.google.com");
  11825. ASSERT_EQ("www.google.com", cli.host());
  11826. ASSERT_EQ(443, cli.port());
  11827. }
  11828. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11829. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11830. std::string cert;
  11831. read_file(CA_CERT_FILE, cert);
  11832. httplib::SSLClient httplib_client("www.google.com");
  11833. // Load CA store first time
  11834. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11835. // Load CA store second time (update)
  11836. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11837. // Verify client is still valid and can make connections
  11838. httplib_client.enable_server_certificate_verification(true);
  11839. auto res = httplib_client.Get("/");
  11840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11841. // Google may return 200 or 301 depending on various factors
  11842. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11843. res->status == StatusCode::MovedPermanently_301);
  11844. }
  11845. TEST(SSLClientTest, ServerNameIndication_Online) {
  11846. auto host = "httpbingo.org";
  11847. auto path = std::string{"/get"};
  11848. SSLClient cli(host, 443);
  11849. auto res = cli.Get(path);
  11850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11851. ASSERT_EQ(StatusCode::OK_200, res->status);
  11852. }
  11853. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11854. // Use a site that will cause SSL verification failure due to self-signed cert
  11855. SSLClient cli("self-signed.badssl.com", 443);
  11856. cli.enable_server_certificate_verification(true);
  11857. auto res = cli.Get("/");
  11858. ASSERT_TRUE(!res);
  11859. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11860. // Verify backend error is captured for SSLServerVerification
  11861. // This occurs when certificate verification fails
  11862. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11863. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11864. EXPECT_NE(0UL, res.ssl_backend_error());
  11865. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11866. // For OpenSSL, ssl_error is 0 for verification errors
  11867. EXPECT_EQ(0, res.ssl_error());
  11868. #if !defined(_WIN32) || \
  11869. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11870. // On non-Windows or when Windows Schannel is disabled, the error comes
  11871. // from OpenSSL's verification
  11872. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11873. res.ssl_backend_error());
  11874. #endif
  11875. #endif
  11876. }
  11877. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11878. // Use a site where hostname doesn't match the certificate
  11879. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11880. SSLClient cli("wrong.host.badssl.com", 443);
  11881. cli.enable_server_certificate_verification(true);
  11882. cli.enable_server_hostname_verification(true);
  11883. auto res = cli.Get("/");
  11884. ASSERT_TRUE(!res);
  11885. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11886. // Verify backend error is captured for hostname verification failure
  11887. EXPECT_NE(0UL, res.ssl_backend_error());
  11888. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11889. // For OpenSSL, ssl_error is 0 for verification errors
  11890. EXPECT_EQ(0, res.ssl_error());
  11891. #if !defined(_WIN32) || \
  11892. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11893. // On non-Windows or when Windows Schannel is disabled, the error comes
  11894. // from OpenSSL's hostname verification
  11895. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11896. res.ssl_backend_error());
  11897. #endif
  11898. #endif
  11899. }
  11900. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11901. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11902. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11903. SSLClient cli("www.google.com", 443);
  11904. cli.enable_server_certificate_verification(true);
  11905. auto res = cli.Get("/");
  11906. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11907. }
  11908. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11909. SSLClient cli("www.google.com", 443);
  11910. cli.enable_server_certificate_verification(true);
  11911. cli.enable_windows_certificate_verification(false);
  11912. auto res = cli.Get("/");
  11913. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11914. }
  11915. // The server sends an intermediate cross-signed by a root Windows trusts,
  11916. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  11917. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  11918. SSLClient cli("accounts.spotify.com", 443);
  11919. auto res = cli.Get("/");
  11920. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  11921. << " ssl_backend_error=" << res.ssl_backend_error();
  11922. }
  11923. // Windows, not the backend, decides on the chain: the error carries a
  11924. // CryptoAPI trust status, which no backend error for a self-signed
  11925. // certificate has.
  11926. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  11927. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11928. ASSERT_TRUE(svr.is_valid());
  11929. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11930. auto se = detail::scope_exit([&] {
  11931. svr.stop();
  11932. t.join();
  11933. ASSERT_FALSE(svr.is_running());
  11934. });
  11935. svr.wait_until_ready();
  11936. SSLClient cli("127.0.0.1", PORT);
  11937. cli.set_connection_timeout(30);
  11938. auto res = cli.Get("/");
  11939. ASSERT_FALSE(res);
  11940. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11941. EXPECT_NE(0u, res.ssl_backend_error() & CERT_TRUST_IS_UNTRUSTED_ROOT)
  11942. << "ssl_backend_error=" << res.ssl_backend_error();
  11943. }
  11944. #endif
  11945. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11946. Client cli("https://google.com");
  11947. auto res = cli.Get("/");
  11948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11949. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11950. }
  11951. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11952. SSLClient cli("google.com");
  11953. cli.set_ca_cert_path(CA_CERT_FILE);
  11954. auto res = cli.Get("/");
  11955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11956. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11957. }
  11958. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11959. SSLClient cli("google.com");
  11960. cli.enable_server_certificate_verification(true);
  11961. cli.set_ca_cert_path("hello");
  11962. auto res = cli.Get("/");
  11963. ASSERT_TRUE(!res);
  11964. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11965. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11966. // should be set
  11967. EXPECT_EQ(0, res.ssl_error());
  11968. // Verify backend error is captured for SSLLoadingCerts
  11969. // This error occurs when loading CA certificates fails
  11970. EXPECT_NE(0UL, res.ssl_backend_error());
  11971. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11972. // OpenSSL specific error codes:
  11973. // > openssl errstr 0x80000002
  11974. // error:80000002:system library::No such file or directory
  11975. // > openssl errstr 0xA000126
  11976. // error:0A000126:SSL routines::unexpected eof while reading
  11977. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11978. res.ssl_backend_error() == 0xA000126);
  11979. #endif
  11980. }
  11981. TEST(SSLClientTest, ServerCertificateVerification4) {
  11982. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11983. ASSERT_TRUE(svr.is_valid());
  11984. svr.Get("/test", [&](const Request &, Response &res) {
  11985. res.set_content("test", "text/plain");
  11986. svr.stop();
  11987. ASSERT_TRUE(true);
  11988. });
  11989. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11990. auto se = detail::scope_exit([&] {
  11991. t.join();
  11992. ASSERT_FALSE(svr.is_running());
  11993. });
  11994. svr.wait_until_ready();
  11995. SSLClient cli("127.0.0.1", PORT);
  11996. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11997. cli.enable_server_certificate_verification(true);
  11998. cli.set_connection_timeout(30);
  11999. auto res = cli.Get("/test");
  12000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12001. ASSERT_EQ(StatusCode::OK_200, res->status);
  12002. }
  12003. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12004. std::string cert;
  12005. read_file(CA_CERT_FILE, cert);
  12006. SSLClient cli("google.com");
  12007. cli.load_ca_cert_store(cert.data(), cert.size());
  12008. const auto res = cli.Get("/");
  12009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12010. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12011. }
  12012. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12013. // clang-format off
  12014. static constexpr char cert[] =
  12015. "GlobalSign Root CA\n"
  12016. "==================\n"
  12017. "-----BEGIN CERTIFICATE-----\n"
  12018. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12019. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12020. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12021. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12022. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12023. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12024. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12025. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12026. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12027. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12028. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12029. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12030. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12031. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12032. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12033. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12034. "-----END CERTIFICATE-----\n";
  12035. // clang-format on
  12036. SSLClient cli("google.com");
  12037. cli.load_ca_cert_store(cert, sizeof(cert));
  12038. const auto res = cli.Get("/");
  12039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12040. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12041. }
  12042. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12043. SSLClient cli("www.youtube.com");
  12044. cli.set_ca_cert_path(CA_CERT_FILE);
  12045. cli.enable_server_certificate_verification(true);
  12046. cli.set_follow_location(true);
  12047. auto res = cli.Get("/");
  12048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12049. ASSERT_EQ(StatusCode::OK_200, res->status);
  12050. }
  12051. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12052. SSLClient cli("wWw.YouTube.Com");
  12053. cli.set_ca_cert_path(CA_CERT_FILE);
  12054. cli.enable_server_certificate_verification(true);
  12055. cli.enable_server_hostname_verification(true);
  12056. cli.set_follow_location(true);
  12057. auto res = cli.Get("/");
  12058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12059. ASSERT_EQ(StatusCode::OK_200, res->status);
  12060. }
  12061. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12062. SSLClient cli("gOoGlE.COm");
  12063. cli.enable_server_certificate_verification(true);
  12064. cli.enable_server_hostname_verification(true);
  12065. cli.set_follow_location(true);
  12066. auto res = cli.Get("/");
  12067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12068. ASSERT_EQ(StatusCode::OK_200, res->status);
  12069. }
  12070. TEST(SSLClientTest, Issue2004_Online) {
  12071. Client client("https://google.com");
  12072. client.set_follow_location(true);
  12073. auto res = client.Get("/");
  12074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12075. ASSERT_EQ(StatusCode::OK_200, res->status);
  12076. auto body = res->body;
  12077. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12078. }
  12079. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12080. // Create SSLClient with invalid cert/key to make is_valid() return false
  12081. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12082. "nonexistent_key.pem");
  12083. // is_valid() should be false due to cert loading failure
  12084. ASSERT_FALSE(cli.is_valid());
  12085. auto res = cli.Get("/");
  12086. ASSERT_FALSE(res);
  12087. EXPECT_EQ(Error::SSLConnection, res.error());
  12088. }
  12089. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12090. // Test for Issue #2251: SSL error not properly reported when client cert
  12091. // and key paths are swapped or mismatched
  12092. // This simulates the scenario where user accidentally swaps the cert and key
  12093. // files
  12094. // Using client cert file as private key and vice versa (completely wrong)
  12095. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12096. // Should fail validation due to cert/key mismatch
  12097. ASSERT_FALSE(cli.is_valid());
  12098. // Attempt to make a request should fail with proper error
  12099. auto res = cli.Get("/");
  12100. ASSERT_FALSE(res);
  12101. EXPECT_EQ(Error::SSLConnection, res.error());
  12102. // SSL error should be recorded in the Result object (this is the key fix for
  12103. // Issue #2251)
  12104. auto backend_error = res.ssl_backend_error();
  12105. EXPECT_NE(0u, backend_error);
  12106. }
  12107. // Tests cert/key mismatch detection at the TLS context level
  12108. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12109. // Test that using mismatched cert/key causes connection failure.
  12110. // We verify this at the SSLClient level rather than through internal
  12111. // TLS API functions.
  12112. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12113. cli.enable_server_certificate_verification(false);
  12114. cli.set_connection_timeout(2);
  12115. // The mismatch should cause a connection or handshake error
  12116. auto res = cli.Get("/test");
  12117. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12118. // Either way, the request should fail
  12119. EXPECT_FALSE(res);
  12120. }
  12121. #endif
  12122. #if 0
  12123. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12124. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12125. ASSERT_TRUE(cli != nullptr);
  12126. cli->set_address_family(AF_INET6);
  12127. cli->set_interface("en0");
  12128. auto res = cli->Get("/get");
  12129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12130. ASSERT_EQ(StatusCode::OK_200, res->status);
  12131. }
  12132. #endif
  12133. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12134. #ifdef CPPHTTPLIB_SSL_ENABLED
  12135. void ClientCertPresent(
  12136. const std::string &client_cert_file,
  12137. const std::string &client_private_key_file,
  12138. const std::string &client_encrypted_private_key_pass = std::string()) {
  12139. using namespace httplib::tls;
  12140. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12141. CLIENT_CA_CERT_DIR);
  12142. ASSERT_TRUE(svr.is_valid());
  12143. svr.Get("/test", [&](const Request &req, Response &res) {
  12144. res.set_content("test", "text/plain");
  12145. auto cert = req.peer_cert();
  12146. ASSERT_TRUE(static_cast<bool>(cert));
  12147. std::string common_name = cert.subject_cn();
  12148. EXPECT_EQ("Common Name", common_name);
  12149. });
  12150. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12151. auto se = detail::scope_exit([&] {
  12152. svr.stop();
  12153. t.join();
  12154. ASSERT_FALSE(svr.is_running());
  12155. });
  12156. svr.wait_until_ready();
  12157. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12158. client_encrypted_private_key_pass);
  12159. cli.enable_server_certificate_verification(false);
  12160. cli.set_connection_timeout(30);
  12161. auto res = cli.Get("/test");
  12162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12163. ASSERT_EQ(StatusCode::OK_200, res->status);
  12164. }
  12165. TEST(SSLClientServerTest, ClientCertPresent) {
  12166. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12167. }
  12168. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12169. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12170. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12171. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12172. }
  12173. // PEM memory-based constructor tests (works with all TLS backends)
  12174. void PemMemoryClientCertPresent(
  12175. const std::string &client_cert_file,
  12176. const std::string &client_private_key_file,
  12177. const std::string &client_encrypted_private_key_pass = std::string()) {
  12178. // Read PEM files into memory
  12179. std::string server_cert_pem, server_key_pem;
  12180. std::string client_ca_pem;
  12181. std::string client_cert_pem, client_key_pem;
  12182. read_file(SERVER_CERT_FILE, server_cert_pem);
  12183. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12184. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12185. read_file(client_cert_file, client_cert_pem);
  12186. read_file(client_private_key_file, client_key_pem);
  12187. // Create server with PEM memory
  12188. SSLServer::PemMemory server_pem = {
  12189. server_cert_pem.c_str(),
  12190. server_cert_pem.size(),
  12191. server_key_pem.c_str(),
  12192. server_key_pem.size(),
  12193. client_ca_pem.c_str(),
  12194. client_ca_pem.size(),
  12195. nullptr // no password for server key
  12196. };
  12197. SSLServer svr(server_pem);
  12198. ASSERT_TRUE(svr.is_valid());
  12199. svr.Get("/test", [&](const Request &, Response &res) {
  12200. res.set_content("test", "text/plain");
  12201. });
  12202. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12203. auto se = detail::scope_exit([&] {
  12204. svr.stop();
  12205. t.join();
  12206. ASSERT_FALSE(svr.is_running());
  12207. });
  12208. svr.wait_until_ready();
  12209. // Create client with PEM memory
  12210. const char *password = client_encrypted_private_key_pass.empty()
  12211. ? nullptr
  12212. : client_encrypted_private_key_pass.c_str();
  12213. SSLClient::PemMemory client_pem = {
  12214. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12215. client_key_pem.size(), password};
  12216. SSLClient cli(HOST, PORT, client_pem);
  12217. cli.enable_server_certificate_verification(false);
  12218. cli.set_connection_timeout(30);
  12219. auto res = cli.Get("/test");
  12220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12221. ASSERT_EQ(StatusCode::OK_200, res->status);
  12222. }
  12223. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12224. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12225. }
  12226. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12227. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12228. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12229. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12230. }
  12231. TEST(SSLClientServerTest, ClientCertMissing) {
  12232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12233. CLIENT_CA_CERT_DIR);
  12234. ASSERT_TRUE(svr.is_valid());
  12235. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12236. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12237. auto se = detail::scope_exit([&] {
  12238. svr.stop();
  12239. t.join();
  12240. ASSERT_FALSE(svr.is_running());
  12241. });
  12242. svr.wait_until_ready();
  12243. SSLClient cli(HOST, PORT);
  12244. cli.set_connection_timeout(30);
  12245. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12246. // the chain check on Windows, so the result does not depend on the order.
  12247. cli.enable_server_hostname_verification(false);
  12248. auto res = cli.Get("/test");
  12249. ASSERT_TRUE(!res);
  12250. // When client cert is missing and server requires it, connection fails
  12251. // Error type depends on backend implementation
  12252. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12253. res.error() == Error::SSLConnection);
  12254. // Verify backend error is captured
  12255. // Note: This test may have different error codes depending on the exact
  12256. // verification failure
  12257. EXPECT_NE(0UL, res.ssl_backend_error());
  12258. }
  12259. TEST(SSLClientServerTest, TrustDirOptional) {
  12260. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12261. ASSERT_TRUE(svr.is_valid());
  12262. svr.Get("/test", [&](const Request &, Response &res) {
  12263. res.set_content("test", "text/plain");
  12264. });
  12265. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12266. auto se = detail::scope_exit([&] {
  12267. svr.stop();
  12268. t.join();
  12269. ASSERT_FALSE(svr.is_running());
  12270. });
  12271. svr.wait_until_ready();
  12272. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12273. cli.enable_server_certificate_verification(false);
  12274. cli.set_connection_timeout(30);
  12275. auto res = cli.Get("/test");
  12276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12277. ASSERT_EQ(StatusCode::OK_200, res->status);
  12278. }
  12279. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12280. class NoListenSSLServer : public SSLServer {
  12281. public:
  12282. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12283. const char *client_ca_cert_file_path,
  12284. const char *client_ca_cert_dir_path = nullptr)
  12285. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12286. client_ca_cert_dir_path),
  12287. stop_(false) {}
  12288. std::atomic_bool stop_;
  12289. private:
  12290. bool process_and_close_socket(socket_t /*sock*/) override {
  12291. // Don't create SSL context
  12292. while (!stop_.load()) {
  12293. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12294. }
  12295. return true;
  12296. }
  12297. };
  12298. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12299. CLIENT_CA_CERT_FILE);
  12300. ASSERT_TRUE(svr.is_valid());
  12301. svr.Get("/test", [&](const Request &, Response &res) {
  12302. res.set_content("test", "text/plain");
  12303. });
  12304. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12305. auto se = detail::scope_exit([&] {
  12306. svr.stop_ = true;
  12307. svr.stop();
  12308. t.join();
  12309. ASSERT_FALSE(svr.is_running());
  12310. });
  12311. svr.wait_until_ready();
  12312. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12313. cli.enable_server_certificate_verification(false);
  12314. cli.set_connection_timeout(1);
  12315. auto res = cli.Get("/test");
  12316. ASSERT_TRUE(!res);
  12317. EXPECT_EQ(Error::SSLConnection, res.error());
  12318. // Timeout results in WantRead error code (maps to backend-specific value)
  12319. EXPECT_NE(0, res.ssl_error());
  12320. }
  12321. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12322. // Test SSLServer with client certificate verification using the standard
  12323. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12324. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12325. CLIENT_CA_CERT_DIR);
  12326. ASSERT_TRUE(svr.is_valid());
  12327. svr.Get("/test", [&](const Request &req, Response &res) {
  12328. res.set_content("test", "text/plain");
  12329. auto cert = req.peer_cert();
  12330. ASSERT_TRUE(static_cast<bool>(cert));
  12331. auto common_name = cert.subject_cn();
  12332. EXPECT_EQ("Common Name", common_name);
  12333. });
  12334. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12335. auto se = detail::scope_exit([&] {
  12336. svr.stop();
  12337. t.join();
  12338. ASSERT_FALSE(svr.is_running());
  12339. });
  12340. svr.wait_until_ready();
  12341. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12342. cli.enable_server_certificate_verification(false);
  12343. cli.set_connection_timeout(30);
  12344. auto res = cli.Get("/test");
  12345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12346. ASSERT_EQ(StatusCode::OK_200, res->status);
  12347. }
  12348. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12349. // Verifies that wildcard matching and exact matching work consistently
  12350. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12351. using namespace httplib::tls;
  12352. // We need a running server to test against
  12353. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12354. ASSERT_TRUE(svr.is_valid());
  12355. svr.Get("/test", [](const Request &, Response &res) {
  12356. res.set_content("ok", "text/plain");
  12357. });
  12358. thread t([&]() { svr.listen(HOST, PORT); });
  12359. auto se = detail::scope_exit([&] {
  12360. svr.stop();
  12361. t.join();
  12362. });
  12363. svr.wait_until_ready();
  12364. bool verify_callback_called = false;
  12365. bool verify_result_wrong = false;
  12366. SSLClient cli(HOST, PORT);
  12367. cli.enable_server_certificate_verification(true);
  12368. cli.set_ca_cert_path(CA_CERT_FILE);
  12369. cli.set_connection_timeout(5);
  12370. // Note: Test certificate has CN="Common Name", not "localhost"
  12371. bool verify_result_cn = false;
  12372. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12373. verify_callback_called = true;
  12374. if (!ctx.cert) return false;
  12375. // Test 1: "Common Name" should match (our test server cert CN)
  12376. verify_result_cn = ctx.check_hostname("Common Name");
  12377. // Test 2: wrong hostname should not match
  12378. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12379. return true; // Accept for the purpose of this test
  12380. });
  12381. auto res = cli.Get("/test");
  12382. // The request may succeed or fail depending on cert configuration
  12383. // but the callback should have been called
  12384. ASSERT_TRUE(verify_callback_called)
  12385. << "Verify callback should have been called";
  12386. // CN="Common Name" should match our test certificate
  12387. //
  12388. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12389. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12390. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12391. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12392. // <openssl/base.h>, which is included transitively when
  12393. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12394. #if defined(OPENSSL_IS_BORINGSSL)
  12395. EXPECT_FALSE(verify_result_cn)
  12396. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12397. #else
  12398. EXPECT_TRUE(verify_result_cn)
  12399. << "verify_hostname should match 'Common Name' (certificate CN)";
  12400. #endif
  12401. // Wrong hostname should not match
  12402. EXPECT_FALSE(verify_result_wrong)
  12403. << "verify_hostname should not match 'wronghost.example.com'";
  12404. }
  12405. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12406. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12407. // X509_check_ip behavior and must hold for every backend.
  12408. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12409. using namespace httplib::tls;
  12410. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12411. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12412. ASSERT_TRUE(svr.is_valid());
  12413. svr.Get("/test", [](const Request &, Response &res) {
  12414. res.set_content("ok", "text/plain");
  12415. });
  12416. thread t([&]() { svr.listen(HOST, PORT); });
  12417. auto se = detail::scope_exit([&] {
  12418. svr.stop();
  12419. t.join();
  12420. });
  12421. svr.wait_until_ready();
  12422. bool verify_callback_called = false;
  12423. bool ip_matched_via_cn = true;
  12424. SSLClient cli(HOST, PORT);
  12425. cli.enable_server_certificate_verification(true);
  12426. cli.set_ca_cert_path(CA_CERT_FILE);
  12427. cli.set_connection_timeout(5);
  12428. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12429. verify_callback_called = true;
  12430. if (!ctx.cert) return false;
  12431. // The IP appears only in the CN, so it must NOT be accepted.
  12432. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12433. return true; // Accept for the purpose of this test
  12434. });
  12435. cli.Get("/test");
  12436. ASSERT_TRUE(verify_callback_called)
  12437. << "Verify callback should have been called";
  12438. EXPECT_FALSE(ip_matched_via_cn)
  12439. << "An IP host must not be authenticated via the certificate CN";
  12440. }
  12441. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12442. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12443. using namespace httplib::tls;
  12444. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12445. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12446. ASSERT_TRUE(svr.is_valid());
  12447. svr.Get("/test", [](const Request &, Response &res) {
  12448. res.set_content("ok", "text/plain");
  12449. });
  12450. thread t([&]() { svr.listen(HOST, PORT); });
  12451. auto se = detail::scope_exit([&] {
  12452. svr.stop();
  12453. t.join();
  12454. });
  12455. svr.wait_until_ready();
  12456. bool verify_callback_called = false;
  12457. bool san_matched = false;
  12458. bool wrong_ipv6_matched = true;
  12459. bool cn_ipv6_matched = true;
  12460. SSLClient cli(HOST, PORT);
  12461. cli.enable_server_certificate_verification(true);
  12462. cli.set_ca_cert_path(CA_CERT_FILE);
  12463. cli.set_connection_timeout(5);
  12464. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12465. verify_callback_called = true;
  12466. if (!ctx.cert) return false;
  12467. // Matches the IPv6 iPAddress SAN.
  12468. san_matched = ctx.check_hostname("2001:db8::1");
  12469. // A different IPv6 address must not match.
  12470. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12471. // "::1" lives only in the CN, so it must not be accepted.
  12472. cn_ipv6_matched = ctx.check_hostname("::1");
  12473. return true; // Accept for the purpose of this test
  12474. });
  12475. cli.Get("/test");
  12476. ASSERT_TRUE(verify_callback_called)
  12477. << "Verify callback should have been called";
  12478. EXPECT_TRUE(san_matched)
  12479. << "verify_hostname should match an IPv6 iPAddress SAN";
  12480. EXPECT_FALSE(wrong_ipv6_matched)
  12481. << "verify_hostname should not match a non-matching IPv6 address";
  12482. EXPECT_FALSE(cn_ipv6_matched)
  12483. << "An IPv6 host must not be authenticated via the certificate CN";
  12484. }
  12485. #endif
  12486. // mbedTLS-specific callback constructor test
  12487. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12488. #ifdef CPPHTTPLIB_SSL_ENABLED
  12489. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12490. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12491. ASSERT_TRUE(svr.is_valid());
  12492. // Set up a handler to verify client certificate is present
  12493. bool client_cert_verified = false;
  12494. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12495. // Verify that client certificate was provided
  12496. client_cert_verified = true;
  12497. res.set_content("success", "text/plain");
  12498. });
  12499. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12500. auto se = detail::scope_exit([&] {
  12501. svr.stop();
  12502. t.join();
  12503. ASSERT_FALSE(svr.is_running());
  12504. });
  12505. svr.wait_until_ready();
  12506. // Client with certificate
  12507. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12508. cli.enable_server_certificate_verification(false);
  12509. cli.set_connection_timeout(30);
  12510. auto res = cli.Get("/test");
  12511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12512. ASSERT_EQ(StatusCode::OK_200, res->status);
  12513. ASSERT_TRUE(client_cert_verified);
  12514. EXPECT_EQ("success", res->body);
  12515. }
  12516. #endif
  12517. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12518. // backends
  12519. #ifdef CPPHTTPLIB_SSL_ENABLED
  12520. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12521. using namespace httplib::tls;
  12522. // Test that when client CA cert file is provided,
  12523. // the server properly requests and validates client certificates
  12524. // Create a server with client authentication
  12525. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12526. ASSERT_TRUE(svr.is_valid());
  12527. bool handler_called = false;
  12528. svr.Get("/test", [&](const Request &req, Response &res) {
  12529. handler_called = true;
  12530. // Verify that a client certificate was provided
  12531. auto cert = req.peer_cert();
  12532. ASSERT_TRUE(static_cast<bool>(cert));
  12533. // Get the issuer name
  12534. std::string issuer_str = cert.issuer_name();
  12535. ASSERT_FALSE(issuer_str.empty());
  12536. // The client certificate should be issued by our test CA
  12537. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12538. res.set_content("authenticated", "text/plain");
  12539. });
  12540. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12541. auto se = detail::scope_exit([&] {
  12542. svr.stop();
  12543. t.join();
  12544. ASSERT_FALSE(svr.is_running());
  12545. });
  12546. svr.wait_until_ready();
  12547. // Connect with a client certificate issued by the CA
  12548. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12549. cli.enable_server_certificate_verification(false);
  12550. cli.set_connection_timeout(30);
  12551. auto res = cli.Get("/test");
  12552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12553. ASSERT_EQ(StatusCode::OK_200, res->status);
  12554. ASSERT_TRUE(handler_called);
  12555. EXPECT_EQ("authenticated", res->body);
  12556. }
  12557. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12558. using namespace httplib::tls;
  12559. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12560. ASSERT_TRUE(svr.is_valid());
  12561. svr.Get("/test", [](const Request &, Response &res) {
  12562. res.set_content("ok", "text/plain");
  12563. });
  12564. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12565. auto se = detail::scope_exit([&] {
  12566. svr.stop();
  12567. t.join();
  12568. });
  12569. svr.wait_until_ready();
  12570. SSLClient cli(HOST, PORT);
  12571. cli.enable_server_certificate_verification(false);
  12572. cli.set_connection_timeout(30);
  12573. bool cert_checked = false;
  12574. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12575. if (ctx.cert) {
  12576. auto sans = ctx.sans();
  12577. // Test certificate may or may not have SANs - just verify the API
  12578. // works If SANs exist, verify the types are valid
  12579. for (const auto &san : sans) {
  12580. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12581. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12582. san.type == SanType::OTHER);
  12583. EXPECT_FALSE(san.value.empty());
  12584. }
  12585. cert_checked = true;
  12586. }
  12587. return true;
  12588. });
  12589. auto res = cli.Get("/test");
  12590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12591. EXPECT_TRUE(cert_checked);
  12592. }
  12593. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12594. using namespace httplib::tls;
  12595. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12596. ASSERT_TRUE(svr.is_valid());
  12597. svr.Get("/test", [](const Request &, Response &res) {
  12598. res.set_content("ok", "text/plain");
  12599. });
  12600. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12601. auto se = detail::scope_exit([&] {
  12602. svr.stop();
  12603. t.join();
  12604. });
  12605. svr.wait_until_ready();
  12606. SSLClient cli(HOST, PORT);
  12607. cli.enable_server_certificate_verification(false);
  12608. cli.set_connection_timeout(30);
  12609. bool validity_checked = false;
  12610. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12611. if (ctx.cert) {
  12612. time_t not_before = 0, not_after = 0;
  12613. bool result = ctx.validity(not_before, not_after);
  12614. EXPECT_TRUE(result);
  12615. // Verify that not_before < now < not_after for a valid cert
  12616. time_t now = time(nullptr);
  12617. EXPECT_LT(not_before, now);
  12618. EXPECT_GT(not_after, now);
  12619. validity_checked = true;
  12620. }
  12621. return true;
  12622. });
  12623. auto res = cli.Get("/test");
  12624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12625. EXPECT_TRUE(validity_checked);
  12626. }
  12627. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12628. using namespace httplib::tls;
  12629. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12630. ASSERT_TRUE(svr.is_valid());
  12631. svr.Get("/test", [](const Request &, Response &res) {
  12632. res.set_content("ok", "text/plain");
  12633. });
  12634. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12635. auto se = detail::scope_exit([&] {
  12636. svr.stop();
  12637. t.join();
  12638. });
  12639. svr.wait_until_ready();
  12640. SSLClient cli(HOST, PORT);
  12641. cli.enable_server_certificate_verification(false);
  12642. cli.set_connection_timeout(30);
  12643. bool serial_checked = false;
  12644. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12645. if (ctx.cert) {
  12646. std::string serial = ctx.serial();
  12647. EXPECT_FALSE(serial.empty());
  12648. // Serial should be a hex string
  12649. for (char c : serial) {
  12650. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12651. (c >= 'a' && c <= 'f'));
  12652. }
  12653. serial_checked = true;
  12654. }
  12655. return true;
  12656. });
  12657. auto res = cli.Get("/test");
  12658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12659. EXPECT_TRUE(serial_checked);
  12660. }
  12661. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12662. // Test 1: Valid CA file - no error should be recorded
  12663. {
  12664. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12665. CLIENT_CA_CERT_FILE);
  12666. ASSERT_TRUE(svr.is_valid());
  12667. // With valid setup, last_ssl_error should be 0
  12668. EXPECT_EQ(0, svr.ssl_last_error());
  12669. }
  12670. // Test 2: Invalid CA file content
  12671. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12672. {
  12673. // Create a temporary file with completely invalid content
  12674. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12675. {
  12676. std::ofstream ofs(temp_invalid_ca);
  12677. ofs << "This is not a certificate file at all\n";
  12678. ofs << "Just plain text content\n";
  12679. }
  12680. // Create server with invalid CA file
  12681. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12682. // Clean up temporary file
  12683. std::remove(temp_invalid_ca);
  12684. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12685. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12686. // Note: SSL_CTX_load_verify_locations typically fails first,
  12687. // but our error handling code path is still exercised
  12688. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12689. }
  12690. }
  12691. TEST(VerifyCallbackTest, VerifyContextFields) {
  12692. using namespace httplib::tls;
  12693. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12694. ASSERT_TRUE(svr.is_valid());
  12695. svr.Get("/test", [](const Request &, Response &res) {
  12696. res.set_content("ok", "text/plain");
  12697. });
  12698. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12699. auto se = detail::scope_exit([&] {
  12700. svr.stop();
  12701. t.join();
  12702. });
  12703. svr.wait_until_ready();
  12704. SSLClient cli(HOST, PORT);
  12705. cli.enable_server_certificate_verification(false);
  12706. cli.set_connection_timeout(30);
  12707. int callback_count = 0;
  12708. bool saw_leaf_cert = false;
  12709. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12710. if (ctx.cert) {
  12711. callback_count++;
  12712. // We should see at least one certificate (the leaf)
  12713. std::string cn = ctx.subject_cn();
  12714. if (!cn.empty()) { saw_leaf_cert = true; }
  12715. // Verify context fields are populated
  12716. EXPECT_NE(ctx.session, nullptr);
  12717. EXPECT_GE(ctx.depth, 0);
  12718. }
  12719. return true;
  12720. });
  12721. auto res = cli.Get("/test");
  12722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12723. EXPECT_GT(callback_count, 0);
  12724. EXPECT_TRUE(saw_leaf_cert);
  12725. }
  12726. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12727. using httplib::tls::TlsError;
  12728. // Test that verify_error_to_string returns empty for success
  12729. std::string success_str = TlsError::verify_error_to_string(0);
  12730. EXPECT_TRUE(success_str.empty());
  12731. // Test that verify_error_to_string returns non-empty for error codes
  12732. // Using a common error code (certificate expired)
  12733. std::string error_str =
  12734. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12735. EXPECT_FALSE(error_str.empty());
  12736. }
  12737. TEST(SessionVerifierTest, CertificateAccepted) {
  12738. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12739. ASSERT_TRUE(svr.is_valid());
  12740. svr.Get("/test", [](const Request &, Response &res) {
  12741. res.set_content("ok", "text/plain");
  12742. });
  12743. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12744. auto se = detail::scope_exit([&] {
  12745. svr.stop();
  12746. t.join();
  12747. });
  12748. svr.wait_until_ready();
  12749. SSLClient cli(HOST, PORT);
  12750. cli.enable_server_certificate_verification(false);
  12751. cli.set_connection_timeout(30);
  12752. bool callback_called = false;
  12753. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12754. EXPECT_NE(session, nullptr);
  12755. callback_called = true;
  12756. return SSLVerifierResponse::CertificateAccepted;
  12757. });
  12758. auto res = cli.Get("/test");
  12759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12760. EXPECT_EQ(200, res->status);
  12761. EXPECT_TRUE(callback_called);
  12762. }
  12763. TEST(SessionVerifierTest, CertificateRejected) {
  12764. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12765. ASSERT_TRUE(svr.is_valid());
  12766. svr.Get("/test", [](const Request &, Response &res) {
  12767. res.set_content("ok", "text/plain");
  12768. });
  12769. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12770. auto se = detail::scope_exit([&] {
  12771. svr.stop();
  12772. t.join();
  12773. });
  12774. svr.wait_until_ready();
  12775. SSLClient cli(HOST, PORT);
  12776. cli.enable_server_certificate_verification(false);
  12777. cli.set_connection_timeout(30);
  12778. bool callback_called = false;
  12779. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12780. EXPECT_NE(session, nullptr);
  12781. callback_called = true;
  12782. return SSLVerifierResponse::CertificateRejected;
  12783. });
  12784. auto res = cli.Get("/test");
  12785. EXPECT_FALSE(res);
  12786. EXPECT_TRUE(callback_called);
  12787. }
  12788. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12789. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12790. ASSERT_TRUE(svr.is_valid());
  12791. svr.Get("/test", [](const Request &, Response &res) {
  12792. res.set_content("ok", "text/plain");
  12793. });
  12794. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12795. auto se = detail::scope_exit([&] {
  12796. svr.stop();
  12797. t.join();
  12798. });
  12799. svr.wait_until_ready();
  12800. // NoDecisionMade with verification disabled should succeed (no default check)
  12801. SSLClient cli(HOST, PORT);
  12802. cli.enable_server_certificate_verification(false);
  12803. cli.set_connection_timeout(30);
  12804. bool callback_called = false;
  12805. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12806. EXPECT_NE(session, nullptr);
  12807. callback_called = true;
  12808. return SSLVerifierResponse::NoDecisionMade;
  12809. });
  12810. auto res = cli.Get("/test");
  12811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12812. EXPECT_EQ(200, res->status);
  12813. EXPECT_TRUE(callback_called);
  12814. }
  12815. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12816. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12817. ASSERT_TRUE(svr.is_valid());
  12818. svr.Get("/test", [](const Request &, Response &res) {
  12819. res.set_content("ok", "text/plain");
  12820. });
  12821. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12822. auto se = detail::scope_exit([&] {
  12823. svr.stop();
  12824. t.join();
  12825. });
  12826. svr.wait_until_ready();
  12827. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12828. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12829. // so we only check that the request fails, not whether the callback was
  12830. // called.
  12831. SSLClient cli(HOST, PORT);
  12832. cli.enable_server_certificate_verification(true);
  12833. cli.set_connection_timeout(30);
  12834. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12835. EXPECT_NE(session, nullptr);
  12836. return SSLVerifierResponse::NoDecisionMade;
  12837. });
  12838. auto res = cli.Get("/test");
  12839. EXPECT_FALSE(res);
  12840. }
  12841. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12842. // Test SSL server using PemMemory constructor with client CA certificates
  12843. // Read PEM files
  12844. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12845. read_file(SERVER_CERT_FILE, server_cert_pem);
  12846. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12847. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12848. // Create SSLServer with PemMemory constructor including client CA
  12849. SSLServer::PemMemory server_pem = {
  12850. server_cert_pem.c_str(),
  12851. server_cert_pem.size(),
  12852. server_key_pem.c_str(),
  12853. server_key_pem.size(),
  12854. client_ca_pem.c_str(),
  12855. client_ca_pem.size(),
  12856. nullptr // no password for server key
  12857. };
  12858. SSLServer svr(server_pem);
  12859. ASSERT_TRUE(svr.is_valid());
  12860. // No SSL error should be recorded for valid setup
  12861. EXPECT_EQ(0, svr.ssl_last_error());
  12862. // Set up server endpoints
  12863. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12864. res.set_content("ok", "text/plain");
  12865. });
  12866. // Start server in a thread
  12867. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12868. svr.wait_until_ready();
  12869. // Connect with client certificate (using constructor with paths)
  12870. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12871. cli.enable_server_certificate_verification(false);
  12872. auto res = cli.Get("/test-pem-ca");
  12873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12874. EXPECT_EQ(200, res->status);
  12875. EXPECT_EQ("ok", res->body);
  12876. svr.stop();
  12877. server_thread.join();
  12878. }
  12879. #endif
  12880. #ifdef _WIN32
  12881. TEST(CleanupTest, WSACleanup) {
  12882. int ret = WSACleanup();
  12883. ASSERT_EQ(0, ret);
  12884. }
  12885. #endif
  12886. #ifndef CPPHTTPLIB_SSL_ENABLED
  12887. TEST(NoSSLSupport, SimpleInterface) {
  12888. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12889. }
  12890. #endif
  12891. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12892. TEST(InvalidScheme, SimpleInterface) {
  12893. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12894. }
  12895. #endif
  12896. TEST(NoScheme, SimpleInterface) {
  12897. Client cli("yahoo.com:80");
  12898. ASSERT_TRUE(cli.is_valid());
  12899. }
  12900. TEST(SendAPI, SimpleInterface_Online) {
  12901. Client cli("http://yahoo.com");
  12902. Request req;
  12903. req.method = "GET";
  12904. req.path = "/";
  12905. auto res = cli.send(req);
  12906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12907. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12908. }
  12909. TEST(SendAPI, WithParamsInRequest) {
  12910. Server svr;
  12911. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12912. EXPECT_TRUE(req.has_param("test"));
  12913. EXPECT_EQ("test_value", req.get_param_value("test"));
  12914. });
  12915. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12916. auto se = detail::scope_exit([&] {
  12917. svr.stop();
  12918. t.join();
  12919. ASSERT_FALSE(svr.is_running());
  12920. });
  12921. svr.wait_until_ready();
  12922. Client cli(HOST, PORT);
  12923. {
  12924. Request req;
  12925. req.method = "GET";
  12926. req.path = "/";
  12927. req.params.emplace("test", "test_value");
  12928. auto res = cli.send(req);
  12929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12930. }
  12931. {
  12932. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12934. }
  12935. }
  12936. TEST(ClientImplMethods, GetSocketTest) {
  12937. httplib::Server svr;
  12938. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12939. res.status = StatusCode::OK_200;
  12940. });
  12941. auto port = svr.bind_to_any_port("127.0.0.1");
  12942. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12943. auto se = detail::scope_exit([&] {
  12944. svr.stop();
  12945. thread.join();
  12946. ASSERT_FALSE(svr.is_running());
  12947. });
  12948. svr.wait_until_ready();
  12949. {
  12950. httplib::Client cli("127.0.0.1", port);
  12951. cli.set_keep_alive(true);
  12952. // Use the behavior of cpp-httplib of opening the connection
  12953. // only when the first request happens. If that changes,
  12954. // this test would be obsolete.
  12955. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12956. // This also implicitly tests the server. But other tests would fail much
  12957. // earlier than this one to be considered.
  12958. auto res = cli.Get("/");
  12959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12960. EXPECT_EQ(StatusCode::OK_200, res->status);
  12961. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12962. }
  12963. }
  12964. #ifdef CPPHTTPLIB_SSL_ENABLED
  12965. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12966. Client cli("http://yahoo.com");
  12967. auto res = cli.Get("/");
  12968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12969. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12970. cli.set_follow_location(true);
  12971. res = cli.Get("/");
  12972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12973. EXPECT_EQ(StatusCode::OK_200, res->status);
  12974. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12975. }
  12976. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12977. Client cli("https://yahoo.com");
  12978. auto res = cli.Get("/");
  12979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12980. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12981. cli.set_follow_location(true);
  12982. res = cli.Get("/");
  12983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12984. EXPECT_EQ(StatusCode::OK_200, res->status);
  12985. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12986. }
  12987. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12988. Client cli("https://yahoo.com");
  12989. auto res = cli.Get("/");
  12990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12991. ASSERT_FALSE(!res);
  12992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12993. ASSERT_FALSE(res == nullptr);
  12994. ASSERT_TRUE(res != nullptr);
  12995. EXPECT_EQ(Error::Success, res.error());
  12996. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12997. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12998. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12999. cli.set_follow_location(true);
  13000. res = cli.Get("/");
  13001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13002. EXPECT_EQ(Error::Success, res.error());
  13003. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13004. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13005. EXPECT_EQ(StatusCode::OK_200, res->status);
  13006. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13007. }
  13008. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13009. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13010. Client cli("https://cdnjs.cloudflare.com");
  13011. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13012. Headers{{"Accept-Encoding", "br"}});
  13013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13014. EXPECT_EQ(StatusCode::OK_200, res->status);
  13015. EXPECT_EQ(287630U, res->body.size());
  13016. EXPECT_EQ("application/javascript; charset=utf-8",
  13017. res->get_header_value("Content-Type"));
  13018. }
  13019. #endif
  13020. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13021. #undef REDIR_HOST // Silence compiler warning
  13022. #define REDIR_HOST "https://httpbingo.org"
  13023. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13024. Client cli(REDIR_HOST);
  13025. cli.set_follow_location(true);
  13026. auto res =
  13027. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13029. EXPECT_EQ(StatusCode::OK_200, res->status);
  13030. }
  13031. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13032. Client cli(REDIR_HOST);
  13033. cli.set_follow_location(true);
  13034. Params params;
  13035. params.emplace("url", "http://example.com");
  13036. params.emplace("status_code", "302");
  13037. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13039. EXPECT_EQ(StatusCode::OK_200, res->status);
  13040. }
  13041. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13042. Client cli(REDIR_HOST);
  13043. cli.set_follow_location(true);
  13044. Params params;
  13045. params.emplace("url", "http://example.com");
  13046. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13048. EXPECT_EQ(StatusCode::OK_200, res->status);
  13049. }
  13050. TEST(HttpToHttpsRedirectTest, CertFile) {
  13051. auto ssl_port = PORT + 1;
  13052. Server svr;
  13053. ASSERT_TRUE(svr.is_valid());
  13054. svr.Get("/index", [&](const Request &, Response &res) {
  13055. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13056. "/index");
  13057. svr.stop();
  13058. });
  13059. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13060. ASSERT_TRUE(ssl_svr.is_valid());
  13061. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13062. res.set_content("test", "text/plain");
  13063. ssl_svr.stop();
  13064. });
  13065. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13066. thread t2 =
  13067. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13068. auto se = detail::scope_exit([&] {
  13069. t2.join();
  13070. t.join();
  13071. ASSERT_FALSE(svr.is_running());
  13072. });
  13073. svr.wait_until_ready();
  13074. ssl_svr.wait_until_ready();
  13075. Client cli("127.0.0.1", PORT);
  13076. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13077. cli.enable_server_certificate_verification(true);
  13078. cli.set_follow_location(true);
  13079. cli.set_connection_timeout(30);
  13080. auto res = cli.Get("/index");
  13081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13082. ASSERT_EQ(StatusCode::OK_200, res->status);
  13083. }
  13084. TEST(SSLClientRedirectTest, CertFile) {
  13085. auto ssl_port = PORT + 1;
  13086. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13087. ASSERT_TRUE(ssl_svr1.is_valid());
  13088. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13089. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13090. "/index");
  13091. ssl_svr1.stop();
  13092. });
  13093. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13094. ASSERT_TRUE(ssl_svr2.is_valid());
  13095. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13096. res.set_content("test", "text/plain");
  13097. ssl_svr2.stop();
  13098. });
  13099. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13100. thread t2 =
  13101. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13102. auto se = detail::scope_exit([&] {
  13103. t2.join();
  13104. t.join();
  13105. ASSERT_FALSE(ssl_svr1.is_running());
  13106. });
  13107. ssl_svr1.wait_until_ready();
  13108. ssl_svr2.wait_until_ready();
  13109. SSLClient cli("127.0.0.1", PORT);
  13110. std::string cert;
  13111. read_file(SERVER_CERT2_FILE, cert);
  13112. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13113. cli.enable_server_certificate_verification(true);
  13114. cli.set_follow_location(true);
  13115. cli.set_connection_timeout(30);
  13116. auto res = cli.Get("/index");
  13117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13118. ASSERT_EQ(StatusCode::OK_200, res->status);
  13119. }
  13120. #endif
  13121. #ifdef CPPHTTPLIB_SSL_ENABLED
  13122. // Test that set_ca_cert_store() skips system certs (consistent with
  13123. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13124. // should be trusted - system certs should NOT be loaded.
  13125. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13126. // Load a specific cert that is NOT a system CA cert
  13127. std::string cert;
  13128. read_file(SERVER_CERT2_FILE, cert);
  13129. SSLClient cli("google.com");
  13130. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13131. cli.enable_server_certificate_verification(true);
  13132. // This should FAIL because:
  13133. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13134. // 2. System certs should NOT be loaded when custom store is set
  13135. // If system certs WERE loaded, this would succeed
  13136. auto res = cli.Get("/");
  13137. ASSERT_FALSE(res);
  13138. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13139. }
  13140. // Same as above, but through the native store handle path. Regression test:
  13141. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13142. // merged system certs into the user-provided store.
  13143. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13144. std::string cert;
  13145. read_file(SERVER_CERT2_FILE, cert);
  13146. SSLClient cli("google.com");
  13147. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13148. cli.enable_server_certificate_verification(true);
  13149. auto res = cli.Get("/");
  13150. ASSERT_FALSE(res);
  13151. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13152. }
  13153. // A custom store set via the native handle must still verify a server whose
  13154. // cert it does contain.
  13155. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13156. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13157. ASSERT_TRUE(svr.is_valid());
  13158. svr.Get("/test", [&](const Request &, Response &res) {
  13159. res.set_content("test", "text/plain");
  13160. });
  13161. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13162. auto se = detail::scope_exit([&] {
  13163. svr.stop();
  13164. t.join();
  13165. ASSERT_FALSE(svr.is_running());
  13166. });
  13167. svr.wait_until_ready();
  13168. SSLClient cli("127.0.0.1", PORT);
  13169. std::string cert;
  13170. read_file(SERVER_CERT2_FILE, cert);
  13171. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13172. cli.enable_server_certificate_verification(true);
  13173. cli.set_connection_timeout(30);
  13174. auto res = cli.Get("/test");
  13175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13176. ASSERT_EQ(StatusCode::OK_200, res->status);
  13177. }
  13178. // CA certs loaded through the universal Client must be transferred to the
  13179. // client created internally for following an HTTPS redirect. Regression test:
  13180. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13181. // the CA data for redirect transfer.
  13182. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13183. auto ssl_port = PORT + 1;
  13184. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13185. ASSERT_TRUE(ssl_svr1.is_valid());
  13186. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13187. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13188. "/index");
  13189. });
  13190. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13191. ASSERT_TRUE(ssl_svr2.is_valid());
  13192. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13193. res.set_content("test", "text/plain");
  13194. });
  13195. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13196. thread t2 =
  13197. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13198. auto se = detail::scope_exit([&] {
  13199. ssl_svr2.stop();
  13200. ssl_svr1.stop();
  13201. t2.join();
  13202. t.join();
  13203. ASSERT_FALSE(ssl_svr1.is_running());
  13204. });
  13205. ssl_svr1.wait_until_ready();
  13206. ssl_svr2.wait_until_ready();
  13207. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13208. std::string cert;
  13209. read_file(SERVER_CERT2_FILE, cert);
  13210. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13211. cli.enable_server_certificate_verification(true);
  13212. cli.set_follow_location(true);
  13213. cli.set_connection_timeout(30);
  13214. auto res = cli.Get("/index");
  13215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13216. ASSERT_EQ(StatusCode::OK_200, res->status);
  13217. }
  13218. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13219. // so a host signed by a system CA verifies even though a custom CA is set
  13220. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13221. std::string cert;
  13222. read_file(SERVER_CERT2_FILE, cert);
  13223. SSLClient cli("google.com");
  13224. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13225. cli.enable_system_ca(true);
  13226. cli.enable_server_certificate_verification(true);
  13227. auto res = cli.Get("/");
  13228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13229. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13230. }
  13231. // The custom CA remains effective when combined with the system CA
  13232. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13233. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13234. ASSERT_TRUE(svr.is_valid());
  13235. svr.Get("/test", [&](const Request &, Response &res) {
  13236. res.set_content("test", "text/plain");
  13237. });
  13238. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13239. auto se = detail::scope_exit([&] {
  13240. svr.stop();
  13241. t.join();
  13242. ASSERT_FALSE(svr.is_running());
  13243. });
  13244. svr.wait_until_ready();
  13245. SSLClient cli("127.0.0.1", PORT);
  13246. std::string cert;
  13247. read_file(SERVER_CERT2_FILE, cert);
  13248. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13249. cli.enable_system_ca(true);
  13250. cli.enable_server_certificate_verification(true);
  13251. cli.set_connection_timeout(30);
  13252. auto res = cli.Get("/test");
  13253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13254. ASSERT_EQ(StatusCode::OK_200, res->status);
  13255. }
  13256. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13257. // skip chain verification entirely (only the certificate identity was
  13258. // checked), so a server presenting an untrusted certificate with a matching
  13259. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13260. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13261. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13262. ASSERT_TRUE(svr.is_valid());
  13263. svr.Get("/test", [&](const Request &, Response &res) {
  13264. res.set_content("test", "text/plain");
  13265. });
  13266. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13267. auto se = detail::scope_exit([&] {
  13268. svr.stop();
  13269. t.join();
  13270. ASSERT_FALSE(svr.is_running());
  13271. });
  13272. svr.wait_until_ready();
  13273. SSLClient cli("127.0.0.1", PORT);
  13274. std::string cert;
  13275. // A trusted CA that did not sign the server certificate. The server cert
  13276. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13277. // this connection.
  13278. read_file(CLIENT_CA_CERT_FILE, cert);
  13279. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13280. cli.enable_server_certificate_verification(true);
  13281. cli.set_connection_timeout(30);
  13282. auto res = cli.Get("/test");
  13283. ASSERT_FALSE(res);
  13284. }
  13285. // enable_system_ca(false) prevents system CA loading entirely
  13286. TEST(SSLClientTest, DisableSystemCa_Online) {
  13287. SSLClient cli("google.com");
  13288. cli.enable_system_ca(false);
  13289. cli.enable_server_certificate_verification(true);
  13290. auto res = cli.Get("/");
  13291. ASSERT_FALSE(res);
  13292. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13293. // itself when the CA chain is empty
  13294. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13295. res.error() == Error::SSLConnection);
  13296. }
  13297. // The universal Client forwards enable_system_ca()
  13298. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13299. std::string cert;
  13300. read_file(SERVER_CERT2_FILE, cert);
  13301. Client cli("https://google.com");
  13302. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13303. cli.enable_system_ca(true);
  13304. cli.enable_server_certificate_verification(true);
  13305. auto res = cli.Get("/");
  13306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13307. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13308. }
  13309. // The system CA policy must carry over to the client created internally for
  13310. // following a cross-host HTTPS redirect
  13311. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13312. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13313. ASSERT_TRUE(svr.is_valid());
  13314. svr.Get("/index", [&](const Request &, Response &res) {
  13315. res.set_redirect("https://www.google.com/");
  13316. });
  13317. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13318. auto se = detail::scope_exit([&] {
  13319. svr.stop();
  13320. t.join();
  13321. ASSERT_FALSE(svr.is_running());
  13322. });
  13323. svr.wait_until_ready();
  13324. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13325. std::string cert;
  13326. read_file(SERVER_CERT2_FILE, cert);
  13327. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13328. cli.enable_system_ca(true);
  13329. cli.enable_server_certificate_verification(true);
  13330. cli.set_follow_location(true);
  13331. cli.set_connection_timeout(30);
  13332. // Receiving any response proves the redirect client completed the TLS
  13333. // handshake with a system-CA-signed host
  13334. auto res = cli.Get("/index");
  13335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13336. }
  13337. TEST(MultipartFormDataTest, LargeData) {
  13338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13339. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13340. const ContentReader &content_reader) {
  13341. if (req.is_multipart_form_data()) {
  13342. std::vector<FormData> items;
  13343. content_reader(
  13344. [&](const FormData &file) {
  13345. items.push_back(file);
  13346. return true;
  13347. },
  13348. [&](const char *data, size_t data_length) {
  13349. items.back().content.append(data, data_length);
  13350. return true;
  13351. });
  13352. EXPECT_TRUE(std::string(items[0].name) == "document");
  13353. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13354. EXPECT_TRUE(items[0].filename == "2MB_data");
  13355. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13356. EXPECT_TRUE(items[1].name == "hello");
  13357. EXPECT_TRUE(items[1].content == "world");
  13358. EXPECT_TRUE(items[1].filename == "");
  13359. EXPECT_TRUE(items[1].content_type == "");
  13360. } else {
  13361. std::string body;
  13362. content_reader([&](const char *data, size_t data_length) {
  13363. body.append(data, data_length);
  13364. return true;
  13365. });
  13366. }
  13367. });
  13368. auto port = svr.bind_to_any_port(HOST);
  13369. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13370. auto se = detail::scope_exit([&] {
  13371. svr.stop();
  13372. t.join();
  13373. ASSERT_FALSE(svr.is_running());
  13374. });
  13375. svr.wait_until_ready();
  13376. {
  13377. std::string data(1024 * 1024 * 2, '.');
  13378. std::stringstream buffer;
  13379. buffer << data;
  13380. SSLClient cli(HOST, port);
  13381. cli.enable_server_certificate_verification(false);
  13382. UploadFormDataItems items{
  13383. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13384. {"hello", "world", "", ""},
  13385. };
  13386. auto res = cli.Post("/post", items);
  13387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13388. ASSERT_EQ(StatusCode::OK_200, res->status);
  13389. }
  13390. }
  13391. TEST(MultipartFormDataTest, DataProviderItems) {
  13392. std::random_device seed_gen;
  13393. std::mt19937 random(seed_gen());
  13394. std::string rand1;
  13395. rand1.resize(1000);
  13396. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13397. std::string rand2;
  13398. rand2.resize(3000);
  13399. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13400. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13401. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13402. const ContentReader &content_reader) {
  13403. ASSERT_FALSE(req.is_multipart_form_data());
  13404. std::string body;
  13405. content_reader([&](const char *data, size_t data_length) {
  13406. body.append(data, data_length);
  13407. return true;
  13408. });
  13409. EXPECT_EQ(body, "");
  13410. });
  13411. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13412. const ContentReader &content_reader) {
  13413. ASSERT_TRUE(req.is_multipart_form_data());
  13414. std::vector<FormData> items;
  13415. content_reader(
  13416. [&](const FormData &file) {
  13417. items.push_back(file);
  13418. return true;
  13419. },
  13420. [&](const char *data, size_t data_length) {
  13421. items.back().content.append(data, data_length);
  13422. return true;
  13423. });
  13424. ASSERT_TRUE(items.size() == 2);
  13425. EXPECT_EQ(std::string(items[0].name), "name1");
  13426. EXPECT_EQ(items[0].content, "Testing123");
  13427. EXPECT_EQ(items[0].filename, "filename1");
  13428. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13429. EXPECT_EQ(items[1].name, "name2");
  13430. EXPECT_EQ(items[1].content, "Testing456");
  13431. EXPECT_EQ(items[1].filename, "");
  13432. EXPECT_EQ(items[1].content_type, "");
  13433. });
  13434. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13435. const ContentReader &content_reader) {
  13436. ASSERT_TRUE(req.is_multipart_form_data());
  13437. std::vector<FormData> items;
  13438. content_reader(
  13439. [&](const FormData &file) {
  13440. items.push_back(file);
  13441. return true;
  13442. },
  13443. [&](const char *data, size_t data_length) {
  13444. items.back().content.append(data, data_length);
  13445. return true;
  13446. });
  13447. ASSERT_TRUE(items.size() == 2);
  13448. EXPECT_EQ(items[0].name, "name3");
  13449. EXPECT_EQ(items[0].content, rand1);
  13450. EXPECT_EQ(items[0].filename, "filename3");
  13451. EXPECT_EQ(items[0].content_type, "");
  13452. EXPECT_EQ(items[1].name, "name4");
  13453. EXPECT_EQ(items[1].content, rand2);
  13454. EXPECT_EQ(items[1].filename, "filename4");
  13455. EXPECT_EQ(items[1].content_type, "");
  13456. });
  13457. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13458. const ContentReader &content_reader) {
  13459. ASSERT_TRUE(req.is_multipart_form_data());
  13460. std::vector<FormData> items;
  13461. content_reader(
  13462. [&](const FormData &file) {
  13463. items.push_back(file);
  13464. return true;
  13465. },
  13466. [&](const char *data, size_t data_length) {
  13467. items.back().content.append(data, data_length);
  13468. return true;
  13469. });
  13470. ASSERT_TRUE(items.size() == 4);
  13471. EXPECT_EQ(std::string(items[0].name), "name1");
  13472. EXPECT_EQ(items[0].content, "Testing123");
  13473. EXPECT_EQ(items[0].filename, "filename1");
  13474. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13475. EXPECT_EQ(items[1].name, "name2");
  13476. EXPECT_EQ(items[1].content, "Testing456");
  13477. EXPECT_EQ(items[1].filename, "");
  13478. EXPECT_EQ(items[1].content_type, "");
  13479. EXPECT_EQ(items[2].name, "name3");
  13480. EXPECT_EQ(items[2].content, rand1);
  13481. EXPECT_EQ(items[2].filename, "filename3");
  13482. EXPECT_EQ(items[2].content_type, "");
  13483. EXPECT_EQ(items[3].name, "name4");
  13484. EXPECT_EQ(items[3].content, rand2);
  13485. EXPECT_EQ(items[3].filename, "filename4");
  13486. EXPECT_EQ(items[3].content_type, "");
  13487. });
  13488. auto port = svr.bind_to_any_port("localhost");
  13489. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13490. auto se = detail::scope_exit([&] {
  13491. svr.stop();
  13492. t.join();
  13493. ASSERT_FALSE(svr.is_running());
  13494. });
  13495. svr.wait_until_ready();
  13496. {
  13497. SSLClient cli("localhost", port);
  13498. cli.enable_server_certificate_verification(false);
  13499. UploadFormDataItems items{
  13500. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13501. {"name2", "Testing456", "", ""}, // not a file
  13502. };
  13503. {
  13504. auto res = cli.Post("/post-none", {}, {}, {});
  13505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13506. ASSERT_EQ(StatusCode::OK_200, res->status);
  13507. }
  13508. FormDataProviderItems providers;
  13509. {
  13510. auto res =
  13511. cli.Post("/post-items", {}, items, providers); // empty providers
  13512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13513. ASSERT_EQ(StatusCode::OK_200, res->status);
  13514. }
  13515. providers.push_back({"name3",
  13516. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13517. // test the offset is given correctly at each step
  13518. if (!offset)
  13519. sink.os.write(rand1.data(), 30);
  13520. else if (offset == 30)
  13521. sink.os.write(rand1.data() + 30, 300);
  13522. else if (offset == 330)
  13523. sink.os.write(rand1.data() + 330, 670);
  13524. else if (offset == rand1.size())
  13525. sink.done();
  13526. return true;
  13527. },
  13528. "filename3",
  13529. {}});
  13530. providers.push_back({"name4",
  13531. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13532. // test the offset is given correctly at each step
  13533. if (!offset)
  13534. sink.os.write(rand2.data(), 2000);
  13535. else if (offset == 2000)
  13536. sink.os.write(rand2.data() + 2000, 1);
  13537. else if (offset == 2001)
  13538. sink.os.write(rand2.data() + 2001, 999);
  13539. else if (offset == rand2.size())
  13540. sink.done();
  13541. return true;
  13542. },
  13543. "filename4",
  13544. {}});
  13545. {
  13546. auto res = cli.Post("/post-providers", {}, {}, providers);
  13547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13548. ASSERT_EQ(StatusCode::OK_200, res->status);
  13549. }
  13550. {
  13551. auto res = cli.Post("/post-both", {}, items, providers);
  13552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13553. ASSERT_EQ(StatusCode::OK_200, res->status);
  13554. }
  13555. }
  13556. }
  13557. TEST(MultipartFormDataTest, BadHeader) {
  13558. Server svr;
  13559. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13560. res.set_content("ok", "text/plain");
  13561. });
  13562. thread t = thread([&] { svr.listen(HOST, PORT); });
  13563. auto se = detail::scope_exit([&] {
  13564. svr.stop();
  13565. t.join();
  13566. ASSERT_FALSE(svr.is_running());
  13567. });
  13568. svr.wait_until_ready();
  13569. const std::string body =
  13570. "This is the preamble. It is to be ignored, though it\r\n"
  13571. "is a handy place for composition agents to include an\r\n"
  13572. "explanatory note to non-MIME conformant readers.\r\n"
  13573. "\r\n"
  13574. "\r\n"
  13575. "--simple boundary\r\n"
  13576. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13577. ": BAD...\r\n"
  13578. "\r\n"
  13579. "value1\r\n"
  13580. "--simple boundary\r\n"
  13581. "Content-Disposition: form-data; name=\"field2\"; "
  13582. "filename=\"example.txt\"\r\n"
  13583. "\r\n"
  13584. "value2\r\n"
  13585. "--simple boundary--\r\n"
  13586. "This is the epilogue. It is also to be ignored.\r\n";
  13587. std::string content_type =
  13588. R"(multipart/form-data; boundary="simple boundary")";
  13589. Client cli(HOST, PORT);
  13590. auto res = cli.Post("/post", body, content_type.c_str());
  13591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13592. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13593. }
  13594. TEST(MultipartFormDataTest, WithPreamble) {
  13595. Server svr;
  13596. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13597. res.set_content("ok", "text/plain");
  13598. });
  13599. thread t = thread([&] { svr.listen(HOST, PORT); });
  13600. auto se = detail::scope_exit([&] {
  13601. svr.stop();
  13602. t.join();
  13603. ASSERT_FALSE(svr.is_running());
  13604. });
  13605. svr.wait_until_ready();
  13606. const std::string body =
  13607. "This is the preamble. It is to be ignored, though it\r\n"
  13608. "is a handy place for composition agents to include an\r\n"
  13609. "explanatory note to non-MIME conformant readers.\r\n"
  13610. "\r\n"
  13611. "\r\n"
  13612. "--simple boundary\r\n"
  13613. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13614. "\r\n"
  13615. "value1\r\n"
  13616. "--simple boundary\r\n"
  13617. "Content-Disposition: form-data; name=\"field2\"; "
  13618. "filename=\"example.txt\"\r\n"
  13619. "\r\n"
  13620. "value2\r\n"
  13621. "--simple boundary--\r\n"
  13622. "This is the epilogue. It is also to be ignored.\r\n";
  13623. std::string content_type =
  13624. R"(multipart/form-data; boundary="simple boundary")";
  13625. Client cli(HOST, PORT);
  13626. auto res = cli.Post("/post", body, content_type.c_str());
  13627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13628. EXPECT_EQ(StatusCode::OK_200, res->status);
  13629. }
  13630. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13631. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13632. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13633. const ContentReader &content_reader) {
  13634. if (req.is_multipart_form_data()) {
  13635. std::vector<FormData> items;
  13636. content_reader(
  13637. [&](const FormData &file) {
  13638. items.push_back(file);
  13639. return true;
  13640. },
  13641. [&](const char *data, size_t data_length) {
  13642. items.back().content.append(data, data_length);
  13643. return true;
  13644. });
  13645. EXPECT_TRUE(std::string(items[0].name) == "document");
  13646. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13647. EXPECT_TRUE(items[0].filename == "2MB_data");
  13648. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13649. EXPECT_TRUE(items[1].name == "hello");
  13650. EXPECT_TRUE(items[1].content == "world");
  13651. EXPECT_TRUE(items[1].filename == "");
  13652. EXPECT_TRUE(items[1].content_type == "");
  13653. } else {
  13654. std::string body;
  13655. content_reader([&](const char *data, size_t data_length) {
  13656. body.append(data, data_length);
  13657. return true;
  13658. });
  13659. }
  13660. });
  13661. auto port = svr.bind_to_any_port("localhost");
  13662. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13663. auto se = detail::scope_exit([&] {
  13664. svr.stop();
  13665. t.join();
  13666. ASSERT_FALSE(svr.is_running());
  13667. });
  13668. svr.wait_until_ready();
  13669. {
  13670. std::string data(1024 * 1024 * 2, '.');
  13671. std::stringstream buffer;
  13672. buffer << data;
  13673. SSLClient cli("localhost", port);
  13674. cli.enable_server_certificate_verification(false);
  13675. UploadFormDataItems items{
  13676. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13677. {"hello", "world", "", ""},
  13678. };
  13679. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13681. ASSERT_EQ(StatusCode::OK_200, res->status);
  13682. }
  13683. }
  13684. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13685. std::string data(1024 * 1024 * 2, '&');
  13686. std::stringstream buffer;
  13687. buffer << data;
  13688. Client cli("https://localhost:8080");
  13689. UploadFormDataItems items{
  13690. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13691. {"hello", "world", "", ""},
  13692. };
  13693. for (const char &c : " \t\r\n") {
  13694. auto res =
  13695. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13696. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13697. ASSERT_FALSE(res);
  13698. }
  13699. }
  13700. TEST(MultipartFormDataTest, PutFormData) {
  13701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13702. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13703. const ContentReader &content_reader) {
  13704. if (req.is_multipart_form_data()) {
  13705. std::vector<FormData> items;
  13706. content_reader(
  13707. [&](const FormData &file) {
  13708. items.push_back(file);
  13709. return true;
  13710. },
  13711. [&](const char *data, size_t data_length) {
  13712. items.back().content.append(data, data_length);
  13713. return true;
  13714. });
  13715. EXPECT_TRUE(std::string(items[0].name) == "document");
  13716. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13717. EXPECT_TRUE(items[0].filename == "2MB_data");
  13718. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13719. EXPECT_TRUE(items[1].name == "hello");
  13720. EXPECT_TRUE(items[1].content == "world");
  13721. EXPECT_TRUE(items[1].filename == "");
  13722. EXPECT_TRUE(items[1].content_type == "");
  13723. } else {
  13724. std::string body;
  13725. content_reader([&](const char *data, size_t data_length) {
  13726. body.append(data, data_length);
  13727. return true;
  13728. });
  13729. }
  13730. });
  13731. auto port = svr.bind_to_any_port("localhost");
  13732. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13733. auto se = detail::scope_exit([&] {
  13734. svr.stop();
  13735. t.join();
  13736. ASSERT_FALSE(svr.is_running());
  13737. });
  13738. svr.wait_until_ready();
  13739. {
  13740. std::string data(1024 * 1024 * 2, '&');
  13741. std::stringstream buffer;
  13742. buffer << data;
  13743. SSLClient cli("localhost", port);
  13744. cli.enable_server_certificate_verification(false);
  13745. UploadFormDataItems items{
  13746. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13747. {"hello", "world", "", ""},
  13748. };
  13749. auto res = cli.Put("/put", items);
  13750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13751. ASSERT_EQ(StatusCode::OK_200, res->status);
  13752. }
  13753. }
  13754. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13755. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13756. svr.Put("/put_customboundary",
  13757. [&](const Request &req, const Response & /*res*/,
  13758. const ContentReader &content_reader) {
  13759. if (req.is_multipart_form_data()) {
  13760. std::vector<FormData> items;
  13761. content_reader(
  13762. [&](const FormData &file) {
  13763. items.push_back(file);
  13764. return true;
  13765. },
  13766. [&](const char *data, size_t data_length) {
  13767. items.back().content.append(data, data_length);
  13768. return true;
  13769. });
  13770. EXPECT_TRUE(std::string(items[0].name) == "document");
  13771. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13772. EXPECT_TRUE(items[0].filename == "2MB_data");
  13773. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13774. EXPECT_TRUE(items[1].name == "hello");
  13775. EXPECT_TRUE(items[1].content == "world");
  13776. EXPECT_TRUE(items[1].filename == "");
  13777. EXPECT_TRUE(items[1].content_type == "");
  13778. } else {
  13779. std::string body;
  13780. content_reader([&](const char *data, size_t data_length) {
  13781. body.append(data, data_length);
  13782. return true;
  13783. });
  13784. }
  13785. });
  13786. auto port = svr.bind_to_any_port("localhost");
  13787. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13788. auto se = detail::scope_exit([&] {
  13789. svr.stop();
  13790. t.join();
  13791. ASSERT_FALSE(svr.is_running());
  13792. });
  13793. svr.wait_until_ready();
  13794. {
  13795. std::string data(1024 * 1024 * 2, '&');
  13796. std::stringstream buffer;
  13797. buffer << data;
  13798. SSLClient cli("localhost", port);
  13799. cli.enable_server_certificate_verification(false);
  13800. UploadFormDataItems items{
  13801. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13802. {"hello", "world", "", ""},
  13803. };
  13804. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13806. ASSERT_EQ(StatusCode::OK_200, res->status);
  13807. }
  13808. }
  13809. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13810. std::string data(1024 * 1024 * 2, '&');
  13811. std::stringstream buffer;
  13812. buffer << data;
  13813. Client cli("https://localhost:8080");
  13814. cli.enable_server_certificate_verification(false);
  13815. UploadFormDataItems items{
  13816. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13817. {"hello", "world", "", ""},
  13818. };
  13819. for (const char &c : " \t\r\n") {
  13820. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13821. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13822. ASSERT_FALSE(res);
  13823. }
  13824. }
  13825. TEST(MultipartFormDataTest, AlternateFilename) {
  13826. auto handled = false;
  13827. Server svr;
  13828. svr.Post("/test", [&](const Request &req, Response &res) {
  13829. ASSERT_EQ(2u, req.form.files.size());
  13830. ASSERT_EQ(1u, req.form.fields.size());
  13831. // Test files
  13832. const auto &file1 = req.form.get_file("file1");
  13833. ASSERT_EQ("file1", file1.name);
  13834. ASSERT_EQ("A.txt", file1.filename);
  13835. ASSERT_EQ("text/plain", file1.content_type);
  13836. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13837. const auto &file2 = req.form.get_file("file2");
  13838. ASSERT_EQ("file2", file2.name);
  13839. ASSERT_EQ("a.html", file2.filename);
  13840. ASSERT_EQ("text/html", file2.content_type);
  13841. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13842. file2.content);
  13843. // Test text field
  13844. const auto &text = req.form.get_field("text");
  13845. ASSERT_EQ("text default", text);
  13846. res.set_content("ok", "text/plain");
  13847. handled = true;
  13848. });
  13849. thread t = thread([&] { svr.listen(HOST, PORT); });
  13850. auto se = detail::scope_exit([&] {
  13851. svr.stop();
  13852. t.join();
  13853. ASSERT_FALSE(svr.is_running());
  13854. ASSERT_TRUE(handled);
  13855. });
  13856. svr.wait_until_ready();
  13857. auto req = "POST /test HTTP/1.1\r\n"
  13858. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13859. "Content-Length: 399\r\n"
  13860. "\r\n"
  13861. "----------\r\n"
  13862. "Content-Disposition: form-data; name=\"text\"\r\n"
  13863. "\r\n"
  13864. "text default\r\n"
  13865. "----------\r\n"
  13866. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13867. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13868. "Content-Type: text/plain\r\n"
  13869. "\r\n"
  13870. "Content of a.txt.\r\n"
  13871. "\r\n"
  13872. "----------\r\n"
  13873. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13874. "\"a.html\"\r\n"
  13875. "Content-Type: text/html\r\n"
  13876. "\r\n"
  13877. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13878. "\r\n"
  13879. "------------\r\n";
  13880. ASSERT_TRUE(send_request(1, req));
  13881. }
  13882. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13883. auto handled = false;
  13884. Server svr;
  13885. svr.Post("/test", [&](const Request &req, Response &res) {
  13886. // Case-insensitive "utf-8''" prefix with a long value
  13887. const auto &file = req.form.get_file("file1");
  13888. ASSERT_EQ("file1", file.name);
  13889. // 8000 chars exercises both the Content-Disposition parser and the
  13890. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13891. // Prior to the fix, std::regex_match on this header would cause O(N)
  13892. // stack recursion in libstdc++, leading to SIGSEGV.
  13893. std::string expected_filename(8000, 'A');
  13894. ASSERT_EQ(expected_filename, file.filename);
  13895. res.set_content("ok", "text/plain");
  13896. handled = true;
  13897. });
  13898. thread t = thread([&] { svr.listen(HOST, PORT); });
  13899. auto se = detail::scope_exit([&] {
  13900. svr.stop();
  13901. t.join();
  13902. ASSERT_FALSE(svr.is_running());
  13903. ASSERT_TRUE(handled);
  13904. });
  13905. svr.wait_until_ready();
  13906. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13907. // Regression test for GHSA-qq6v-r583-3h69
  13908. std::string long_filename(8000, 'A');
  13909. std::string body = "----------\r\n"
  13910. "Content-Disposition: form-data; name=\"file1\"; "
  13911. "filename*=\"Utf-8''" +
  13912. long_filename +
  13913. "\"\r\n"
  13914. "\r\n"
  13915. "hello\r\n"
  13916. "------------\r\n";
  13917. auto req = "POST /test HTTP/1.1\r\n"
  13918. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13919. "Content-Length: " +
  13920. std::to_string(body.size()) + "\r\n\r\n" + body;
  13921. ASSERT_TRUE(send_request(1, req));
  13922. }
  13923. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13924. auto handled = false;
  13925. Server svr;
  13926. svr.Post("/test", [&](const Request &req, Response &) {
  13927. ASSERT_EQ(2u, req.form.fields.size());
  13928. const auto &text1 = req.form.get_field("text1");
  13929. ASSERT_EQ("text1", text1);
  13930. const auto &text2 = req.form.get_field("text2");
  13931. ASSERT_EQ("text2", text2);
  13932. handled = true;
  13933. });
  13934. thread t = thread([&] { svr.listen(HOST, PORT); });
  13935. auto se = detail::scope_exit([&] {
  13936. svr.stop();
  13937. t.join();
  13938. ASSERT_FALSE(svr.is_running());
  13939. ASSERT_TRUE(handled);
  13940. });
  13941. svr.wait_until_ready();
  13942. auto req = "POST /test HTTP/1.1\r\n"
  13943. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13944. "Content-Length: 146\r\n"
  13945. "\r\n----------\r\n"
  13946. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13947. "\r\n"
  13948. "text1"
  13949. "\r\n----------\r\n"
  13950. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13951. "\r\n"
  13952. "text2"
  13953. "\r\n------------";
  13954. std::string response;
  13955. ASSERT_TRUE(send_request(1, req, &response));
  13956. ASSERT_EQ("200", response.substr(9, 3));
  13957. }
  13958. TEST(MultipartFormDataTest, ContentLength) {
  13959. auto handled = false;
  13960. Server svr;
  13961. svr.Post("/test", [&](const Request &req, Response &) {
  13962. ASSERT_EQ(2u, req.form.fields.size());
  13963. const auto &text1 = req.form.get_field("text1");
  13964. ASSERT_EQ("text1", text1);
  13965. const auto &text2 = req.form.get_field("text2");
  13966. ASSERT_EQ("text2", text2);
  13967. handled = true;
  13968. });
  13969. thread t = thread([&] { svr.listen(HOST, PORT); });
  13970. auto se = detail::scope_exit([&] {
  13971. svr.stop();
  13972. t.join();
  13973. ASSERT_FALSE(svr.is_running());
  13974. ASSERT_TRUE(handled);
  13975. });
  13976. svr.wait_until_ready();
  13977. auto req = "POST /test HTTP/1.1\r\n"
  13978. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13979. "Content-Length: 167\r\n"
  13980. "\r\n----------\r\n"
  13981. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13982. "Content-Length: 5\r\n"
  13983. "\r\n"
  13984. "text1"
  13985. "\r\n----------\r\n"
  13986. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13987. "\r\n"
  13988. "text2"
  13989. "\r\n------------\r\n";
  13990. std::string response;
  13991. ASSERT_TRUE(send_request(1, req, &response));
  13992. ASSERT_EQ("200", response.substr(9, 3));
  13993. }
  13994. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13995. auto handled = false;
  13996. Server svr;
  13997. svr.Post("/test", [&](const Request &req, Response &) {
  13998. ASSERT_EQ(2u, req.form.fields.size());
  13999. const auto &text1 = req.form.get_field("text1");
  14000. ASSERT_EQ("text1", text1);
  14001. // TODO: Add header access for text fields if needed
  14002. const auto &text2 = req.form.get_field("text2");
  14003. ASSERT_EQ("text2", text2);
  14004. // TODO: Header access for text fields needs to be implemented
  14005. // auto &headers = it->second.headers;
  14006. // ASSERT_EQ(3U, headers.size());
  14007. // auto custom_header = headers.find("x-whatever");
  14008. // ASSERT_TRUE(custom_header != headers.end());
  14009. // ASSERT_NE("customvalue", custom_header->second);
  14010. // ASSERT_EQ("CustomValue", custom_header->second);
  14011. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14012. handled = true;
  14013. });
  14014. thread t = thread([&] { svr.listen(HOST, PORT); });
  14015. auto se = detail::scope_exit([&] {
  14016. svr.stop();
  14017. t.join();
  14018. ASSERT_FALSE(svr.is_running());
  14019. ASSERT_TRUE(handled);
  14020. });
  14021. svr.wait_until_ready();
  14022. auto req = "POST /test HTTP/1.1\r\n"
  14023. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14024. "Content-Length: 232\r\n"
  14025. "\r\n----------\r\n"
  14026. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14027. "Content-Length: 5\r\n"
  14028. "X-Test: 1\r\n"
  14029. "\r\n"
  14030. "text1"
  14031. "\r\n----------\r\n"
  14032. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14033. "Content-Type: text/plain\r\n"
  14034. "X-Whatever: CustomValue\r\n"
  14035. "\r\n"
  14036. "text2"
  14037. "\r\n------------\r\n"
  14038. "That should be disregarded. Not even read";
  14039. std::string response;
  14040. ASSERT_TRUE(send_request(1, req, &response));
  14041. ASSERT_EQ("200", response.substr(9, 3));
  14042. }
  14043. TEST(MultipartFormDataTest, LargeHeader) {
  14044. auto handled = false;
  14045. Server svr;
  14046. svr.Post("/test", [&](const Request &req, Response &) {
  14047. ASSERT_EQ(1u, req.form.fields.size());
  14048. const auto &text = req.form.get_field("name1");
  14049. ASSERT_EQ("text1", text);
  14050. handled = true;
  14051. });
  14052. thread t = thread([&] { svr.listen(HOST, PORT); });
  14053. auto se = detail::scope_exit([&] {
  14054. svr.stop();
  14055. t.join();
  14056. ASSERT_FALSE(svr.is_running());
  14057. ASSERT_TRUE(handled);
  14058. });
  14059. svr.wait_until_ready();
  14060. auto boundary = std::string("cpp-httplib-multipart-data");
  14061. std::string content = "--" + boundary +
  14062. "\r\n"
  14063. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14064. "\r\n"
  14065. "text1\r\n"
  14066. "--" +
  14067. boundary + "--\r\n";
  14068. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14069. "Content-Type: multipart/form-data;boundary=" +
  14070. boundary +
  14071. "\r\n"
  14072. "Content-Length: " +
  14073. std::to_string(content.size()) +
  14074. "\r\n"
  14075. "Dummy-Header: ";
  14076. std::string header_suffix = "\r\n"
  14077. "\r\n";
  14078. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14079. size_t header_dummy_size =
  14080. read_buff_size -
  14081. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14082. auto header_dummy = std::string(header_dummy_size, '@');
  14083. auto req = header_prefix + header_dummy + header_suffix + content;
  14084. std::string response;
  14085. ASSERT_TRUE(send_request(1, req, &response));
  14086. ASSERT_EQ("200", response.substr(9, 3));
  14087. }
  14088. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14089. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14090. // (not chunked Transfer-Encoding) after the streaming refactor.
  14091. auto handled = false;
  14092. Server svr;
  14093. svr.Post("/upload", [&](const Request &req, Response &res) {
  14094. auto cl_it = req.headers.find("Content-Length");
  14095. EXPECT_TRUE(cl_it != req.headers.end());
  14096. auto te_it = req.headers.find("Transfer-Encoding");
  14097. EXPECT_TRUE(te_it == req.headers.end());
  14098. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14099. res.set_content("ok", "text/plain");
  14100. handled = true;
  14101. });
  14102. auto port = svr.bind_to_any_port(HOST);
  14103. auto t = thread([&] { svr.listen_after_bind(); });
  14104. auto se = detail::scope_exit([&] {
  14105. svr.stop();
  14106. t.join();
  14107. ASSERT_FALSE(svr.is_running());
  14108. ASSERT_TRUE(handled);
  14109. });
  14110. svr.wait_until_ready();
  14111. UploadFormDataItems items = {
  14112. {"field1", "hello", "", "text/plain"},
  14113. {"file1", "world", "test.txt", "application/octet-stream"},
  14114. };
  14115. Client cli(HOST, port);
  14116. auto res = cli.Post("/upload", {}, items);
  14117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14118. EXPECT_EQ(StatusCode::OK_200, res->status);
  14119. }
  14120. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14121. // Verify that make_multipart_content_provider coalesces many small segments
  14122. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14123. constexpr size_t kItemCount = 1000;
  14124. UploadFormDataItems items;
  14125. items.reserve(kItemCount);
  14126. for (size_t i = 0; i < kItemCount; i++) {
  14127. items.push_back(
  14128. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14129. }
  14130. const std::string boundary = "----test-boundary";
  14131. auto content_length = detail::get_multipart_content_length(items, boundary);
  14132. auto provider = detail::make_multipart_content_provider(items, boundary);
  14133. // Drive the provider the same way write_content_with_progress does
  14134. size_t write_count = 0;
  14135. size_t total_bytes = 0;
  14136. DataSink sink;
  14137. size_t offset = 0;
  14138. sink.write = [&](const char *d, size_t l) -> bool {
  14139. (void)d;
  14140. write_count++;
  14141. total_bytes += l;
  14142. offset += l;
  14143. return true;
  14144. };
  14145. sink.is_writable = []() -> bool { return true; };
  14146. while (offset < content_length) {
  14147. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14148. }
  14149. EXPECT_EQ(content_length, total_bytes);
  14150. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14151. // With buffering into 64KB blocks, write_count should be much smaller.
  14152. auto segment_count = 3 * kItemCount + 1;
  14153. EXPECT_LT(write_count, segment_count / 10);
  14154. }
  14155. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14156. // Integration test: send many UploadFormDataItems and verify the server
  14157. // receives all of them correctly (#2410).
  14158. constexpr size_t kItemCount = 500;
  14159. auto handled = false;
  14160. Server svr;
  14161. svr.Post("/upload", [&](const Request &req, Response &res) {
  14162. EXPECT_EQ(kItemCount, req.form.fields.size());
  14163. for (size_t i = 0; i < kItemCount; i++) {
  14164. auto key = "field" + std::to_string(i);
  14165. auto val = "value" + std::to_string(i);
  14166. auto it = req.form.fields.find(key);
  14167. if (it != req.form.fields.end()) {
  14168. EXPECT_EQ(val, it->second.content);
  14169. } else {
  14170. ADD_FAILURE() << "Missing field: " << key;
  14171. }
  14172. }
  14173. res.set_content("ok", "text/plain");
  14174. handled = true;
  14175. });
  14176. auto port = svr.bind_to_any_port(HOST);
  14177. auto t = thread([&] { svr.listen_after_bind(); });
  14178. auto se = detail::scope_exit([&] {
  14179. svr.stop();
  14180. t.join();
  14181. ASSERT_FALSE(svr.is_running());
  14182. ASSERT_TRUE(handled);
  14183. });
  14184. svr.wait_until_ready();
  14185. UploadFormDataItems items;
  14186. items.reserve(kItemCount);
  14187. for (size_t i = 0; i < kItemCount; i++) {
  14188. items.push_back(
  14189. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14190. }
  14191. Client cli(HOST, port);
  14192. auto res = cli.Post("/upload", items);
  14193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14194. EXPECT_EQ(StatusCode::OK_200, res->status);
  14195. }
  14196. TEST(MultipartFormDataTest, MakeFileProvider) {
  14197. // Verify make_file_provider sends a file's contents correctly.
  14198. const std::string file_content(4096, 'Z');
  14199. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14200. {
  14201. std::ofstream ofs(tmp_path, std::ios::binary);
  14202. ofs.write(file_content.data(),
  14203. static_cast<std::streamsize>(file_content.size()));
  14204. }
  14205. auto handled = false;
  14206. Server svr;
  14207. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14208. const ContentReader &content_reader) {
  14209. ASSERT_TRUE(req.is_multipart_form_data());
  14210. std::vector<FormData> items;
  14211. content_reader(
  14212. [&](const FormData &file) {
  14213. items.push_back(file);
  14214. return true;
  14215. },
  14216. [&](const char *data, size_t data_length) {
  14217. items.back().content.append(data, data_length);
  14218. return true;
  14219. });
  14220. ASSERT_EQ(1u, items.size());
  14221. EXPECT_EQ("myfile", items[0].name);
  14222. EXPECT_EQ("data.bin", items[0].filename);
  14223. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14224. EXPECT_EQ(file_content, items[0].content);
  14225. handled = true;
  14226. });
  14227. auto port = svr.bind_to_any_port(HOST);
  14228. auto t = thread([&] { svr.listen_after_bind(); });
  14229. auto se = detail::scope_exit([&] {
  14230. svr.stop();
  14231. t.join();
  14232. ASSERT_FALSE(svr.is_running());
  14233. ASSERT_TRUE(handled);
  14234. std::remove(tmp_path.c_str());
  14235. });
  14236. svr.wait_until_ready();
  14237. FormDataProviderItems providers;
  14238. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14239. "application/octet-stream"));
  14240. Client cli(HOST, port);
  14241. auto res = cli.Post("/upload", {}, {}, providers);
  14242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14243. EXPECT_EQ(StatusCode::OK_200, res->status);
  14244. }
  14245. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14246. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14247. // (100) headers is rejected with a 400 Bad Request response.
  14248. Server svr;
  14249. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14250. res.set_content("ok", "text/plain");
  14251. });
  14252. thread t = thread([&] { svr.listen(HOST, PORT); });
  14253. auto se = detail::scope_exit([&] {
  14254. svr.stop();
  14255. t.join();
  14256. ASSERT_FALSE(svr.is_running());
  14257. });
  14258. svr.wait_until_ready();
  14259. // Build a multipart part with 101 custom headers (exceeding
  14260. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14261. std::stringstream body;
  14262. body << "--simpleboundary\r\n"
  14263. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14264. for (int i = 0; i < 101; i++) {
  14265. body << "X-Custom-Header-" << i << ": value\r\n";
  14266. }
  14267. body << "\r\n"
  14268. << "value1\r\n"
  14269. << "--simpleboundary--\r\n";
  14270. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14271. Client cli(HOST, PORT);
  14272. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14274. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14275. }
  14276. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14277. // A body that never contains the declared boundary must not be accumulated
  14278. // while the parser waits for it. Buffering it would also make every read
  14279. // rescan everything seen so far, which is quadratic in the body size.
  14280. Server svr;
  14281. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14282. res.set_content("ok", "text/plain");
  14283. });
  14284. auto port = svr.bind_to_any_port(HOST);
  14285. thread t = thread([&] { svr.listen_after_bind(); });
  14286. auto se = detail::scope_exit([&] {
  14287. svr.stop();
  14288. t.join();
  14289. ASSERT_FALSE(svr.is_running());
  14290. });
  14291. svr.wait_until_ready();
  14292. Client cli(HOST, port);
  14293. cli.set_read_timeout(60, 0);
  14294. cli.set_write_timeout(60, 0);
  14295. // '-' is the worst case: it matches the first character of the boundary, so
  14296. // every position has to be checked against it.
  14297. auto post_dashes = [&](size_t size) {
  14298. const std::string body(size, '-');
  14299. auto start = std::chrono::steady_clock::now();
  14300. auto res =
  14301. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14302. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14303. std::chrono::steady_clock::now() - start)
  14304. .count();
  14305. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14306. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14307. return ms;
  14308. };
  14309. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14310. // Windows.
  14311. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14312. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14313. // Comparing the two sizes rather than checking an absolute duration keeps
  14314. // this meaningful across build types and CI load, both of which move the
  14315. // absolute numbers by more than an order of magnitude. Four times the bytes
  14316. // costs about four times the time when parsing is linear, and about sixteen
  14317. // times when the body is buffered and rescanned.
  14318. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14319. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14320. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14321. << "ms, which suggests the body is being buffered and rescanned";
  14322. }
  14323. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14324. // A boundary can only be followed by CRLF or by "--", so anything else is
  14325. // malformed no matter what comes next. The parser must say so right away
  14326. // instead of buffering the rest of the declared body.
  14327. Server svr;
  14328. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14329. res.set_content("ok", "text/plain");
  14330. });
  14331. auto port = svr.bind_to_any_port(HOST);
  14332. thread t = thread([&] { svr.listen_after_bind(); });
  14333. auto se = detail::scope_exit([&] {
  14334. svr.stop();
  14335. t.join();
  14336. ASSERT_FALSE(svr.is_running());
  14337. });
  14338. svr.wait_until_ready();
  14339. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14340. // buffers instead of failing would still be waiting for the remaining bytes.
  14341. const std::string body = "--zzzz\r\n"
  14342. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14343. "\r\n"
  14344. "text1"
  14345. "\r\n--zzzzXX";
  14346. const std::string req = "POST /post HTTP/1.1\r\n"
  14347. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14348. "Content-Length: 1048576\r\n"
  14349. "\r\n" +
  14350. body;
  14351. std::string response;
  14352. ASSERT_TRUE(send_request(3, req, &response, port));
  14353. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14354. EXPECT_EQ("400", response.substr(9, 3));
  14355. }
  14356. // Posts a multipart body split into two writes, so that the server sees the
  14357. // split at whatever offset the caller chose, and expects the single "text1"
  14358. // field to come through.
  14359. static void expect_split_multipart_ok(const std::string &body1,
  14360. const std::string &body2) {
  14361. auto handled = false;
  14362. Server svr;
  14363. svr.Post("/post", [&](const Request &req, Response &) {
  14364. EXPECT_EQ(1u, req.form.fields.size());
  14365. EXPECT_EQ("text1", req.form.get_field("text1"));
  14366. handled = true;
  14367. });
  14368. auto port = svr.bind_to_any_port(HOST);
  14369. thread t = thread([&] { svr.listen_after_bind(); });
  14370. auto se = detail::scope_exit([&] {
  14371. svr.stop();
  14372. t.join();
  14373. ASSERT_FALSE(svr.is_running());
  14374. ASSERT_TRUE(handled);
  14375. });
  14376. svr.wait_until_ready();
  14377. // "Connection: close" makes the server close once it has answered, so the
  14378. // response drain ends immediately instead of idling until the read timeout.
  14379. const std::string head =
  14380. "POST /post HTTP/1.1\r\n"
  14381. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14382. "Connection: close\r\n"
  14383. "Content-Length: " +
  14384. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14385. std::string response;
  14386. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14387. ASSERT_GE(response.size(), 12u) << "no response";
  14388. EXPECT_EQ("200", response.substr(9, 3));
  14389. }
  14390. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14391. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14392. // ignored, including when it does not arrive in the same read as the
  14393. // close-delimiter itself.
  14394. expect_split_multipart_ok("--zzzz\r\n"
  14395. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14396. "\r\n"
  14397. "text1"
  14398. "\r\n--zzzz--",
  14399. "\r\nthis epilogue must be ignored\r\n");
  14400. }
  14401. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14402. // The initial boundary may be preceded by a preamble of any length and may
  14403. // straddle a read boundary. Discarding data while waiting for it must not
  14404. // throw away a partial boundary sitting at the end of the buffer.
  14405. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14406. "zz\r\n"
  14407. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14408. "\r\n"
  14409. "text1"
  14410. "\r\n--zzzz--\r\n");
  14411. }
  14412. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14413. // The received boundary was only checked for being non-empty, so it could be
  14414. // as long as a header is allowed to be. The parser scans the body for
  14415. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14416. // costs a nearly full comparison at nearly every position, making the
  14417. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14418. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14419. Server svr;
  14420. svr.Post("/post", [](const Request &req, Response &res) {
  14421. EXPECT_EQ(1u, req.form.fields.size());
  14422. EXPECT_EQ("text1", req.form.get_field("text1"));
  14423. res.set_content("ok", "text/plain");
  14424. });
  14425. auto port = svr.bind_to_any_port(HOST);
  14426. thread t = thread([&] { svr.listen_after_bind(); });
  14427. auto se = detail::scope_exit([&] {
  14428. svr.stop();
  14429. t.join();
  14430. ASSERT_FALSE(svr.is_running());
  14431. });
  14432. svr.wait_until_ready();
  14433. Client cli(HOST, port);
  14434. auto post_with_boundary_of_length = [&](size_t len) {
  14435. const std::string boundary(len, 'a');
  14436. const std::string body =
  14437. "--" + boundary +
  14438. "\r\n"
  14439. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14440. "\r\n"
  14441. "text1"
  14442. "\r\n--" +
  14443. boundary + "--\r\n";
  14444. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14445. };
  14446. auto res = post_with_boundary_of_length(70);
  14447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14448. EXPECT_EQ(StatusCode::OK_200, res->status);
  14449. res = post_with_boundary_of_length(71);
  14450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14451. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14452. }
  14453. TEST(MakeFileBodyTest, Basic) {
  14454. const std::string file_content(4096, 'Z');
  14455. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14456. {
  14457. std::ofstream ofs(tmp_path, std::ios::binary);
  14458. ofs.write(file_content.data(),
  14459. static_cast<std::streamsize>(file_content.size()));
  14460. }
  14461. auto handled = false;
  14462. Server svr;
  14463. svr.Post("/upload", [&](const Request &req, Response &res) {
  14464. EXPECT_EQ(file_content, req.body);
  14465. handled = true;
  14466. res.status = StatusCode::OK_200;
  14467. });
  14468. auto port = svr.bind_to_any_port(HOST);
  14469. auto t = thread([&] { svr.listen_after_bind(); });
  14470. auto se = detail::scope_exit([&] {
  14471. svr.stop();
  14472. t.join();
  14473. ASSERT_FALSE(svr.is_running());
  14474. ASSERT_TRUE(handled);
  14475. std::remove(tmp_path.c_str());
  14476. });
  14477. svr.wait_until_ready();
  14478. auto fb = make_file_body(tmp_path);
  14479. ASSERT_GT(fb.first, 0u);
  14480. Client cli(HOST, port);
  14481. auto res =
  14482. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14484. EXPECT_EQ(StatusCode::OK_200, res->status);
  14485. }
  14486. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14487. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14488. {
  14489. std::ofstream ofs(path, std::ios::binary);
  14490. const std::string content(100, 'A');
  14491. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14492. }
  14493. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14494. auto body = make_file_body(path);
  14495. ASSERT_EQ(100u, body.first);
  14496. ASSERT_TRUE(static_cast<bool>(body.second));
  14497. // Rewritten shorter after its length was measured - and, on a server, after
  14498. // that length has already gone out as Content-Length.
  14499. {
  14500. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14501. const std::string content(10, 'A');
  14502. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14503. }
  14504. std::string written;
  14505. DataSink sink;
  14506. sink.write = [&](const char *d, size_t l) {
  14507. written.append(d, l);
  14508. return true;
  14509. };
  14510. // The provider has to report failure. write_content_with_progress() advances
  14511. // its offset only by what was written, so a provider that returns true
  14512. // without completing the length it promised is called again straight away,
  14513. // and again.
  14514. EXPECT_FALSE(body.second(0, body.first, sink));
  14515. EXPECT_EQ(std::string(10, 'A'), written);
  14516. }
  14517. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14518. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14519. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14520. {
  14521. std::ofstream ofs(path, std::ios::binary);
  14522. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14523. }
  14524. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14525. auto body = make_file_body(path);
  14526. ASSERT_EQ(content.size(), body.first);
  14527. ASSERT_TRUE(static_cast<bool>(body.second));
  14528. std::string written;
  14529. DataSink sink;
  14530. sink.write = [&](const char *d, size_t l) {
  14531. written.append(d, l);
  14532. return true;
  14533. };
  14534. EXPECT_TRUE(body.second(0, body.first, sink));
  14535. EXPECT_EQ(content, written);
  14536. }
  14537. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14538. static constexpr unsigned int number_of_tasks{1000000};
  14539. std::atomic_uint count{0};
  14540. std::unique_ptr<TaskQueue> task_queue{
  14541. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14542. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14543. auto queued = task_queue->enqueue(
  14544. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14545. EXPECT_TRUE(queued);
  14546. }
  14547. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14548. task_queue->shutdown();
  14549. #else
  14550. EXPECT_NO_THROW(task_queue->shutdown());
  14551. #endif
  14552. EXPECT_EQ(number_of_tasks, count.load());
  14553. }
  14554. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14555. static constexpr unsigned int number_of_tasks{1000000};
  14556. static constexpr unsigned int qlimit{2};
  14557. unsigned int queued_count{0};
  14558. std::atomic_uint count{0};
  14559. std::unique_ptr<TaskQueue> task_queue{
  14560. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14561. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14562. if (task_queue->enqueue(
  14563. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14564. queued_count++;
  14565. }
  14566. }
  14567. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14568. task_queue->shutdown();
  14569. #else
  14570. EXPECT_NO_THROW(task_queue->shutdown());
  14571. #endif
  14572. EXPECT_EQ(queued_count, count.load());
  14573. EXPECT_TRUE(queued_count <= number_of_tasks);
  14574. EXPECT_TRUE(queued_count >= qlimit);
  14575. }
  14576. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14577. // Use a short idle timeout so a dynamic thread spawns, times out and
  14578. // exits during the test, and the pool keeps working afterwards.
  14579. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14580. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14581. /*idle_timeout_sec=*/1}};
  14582. std::atomic_uint count{0};
  14583. std::condition_variable cv;
  14584. std::mutex mtx;
  14585. bool release = false;
  14586. // Block the base thread so the second task spawns a dynamic thread.
  14587. EXPECT_TRUE(task_queue->enqueue([&] {
  14588. std::unique_lock<std::mutex> lock(mtx);
  14589. while (!release) {
  14590. cv.wait(lock);
  14591. }
  14592. count++;
  14593. }));
  14594. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14595. // Let the dynamic thread finish its task and exceed the idle timeout.
  14596. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14597. {
  14598. std::unique_lock<std::mutex> lock(mtx);
  14599. release = true;
  14600. }
  14601. cv.notify_all();
  14602. // The pool must still accept and run tasks after the dynamic thread exited.
  14603. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14604. task_queue->shutdown();
  14605. EXPECT_EQ(3u, count.load());
  14606. }
  14607. TEST(TaskQueueTest, MaxQueuedRequests) {
  14608. static constexpr unsigned int qlimit{3};
  14609. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14610. std::condition_variable sem_cv;
  14611. std::mutex sem_mtx;
  14612. int credits = 0;
  14613. bool queued;
  14614. /* Fill up the queue with tasks that will block until we give them credits to
  14615. * complete. */
  14616. for (unsigned int n = 0; n <= qlimit;) {
  14617. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14618. std::unique_lock<std::mutex> lock(sem_mtx);
  14619. while (credits <= 0) {
  14620. sem_cv.wait(lock);
  14621. }
  14622. /* Consume the credit and signal the test code if they are all gone. */
  14623. if (--credits == 0) { sem_cv.notify_one(); }
  14624. });
  14625. if (n < qlimit) {
  14626. /* The first qlimit enqueues must succeed. */
  14627. EXPECT_TRUE(queued);
  14628. } else {
  14629. /* The last one will succeed only when the worker thread
  14630. * starts and dequeues the first blocking task. Although
  14631. * not necessary for the correctness of this test, we sleep for
  14632. * a short while to avoid busy waiting. */
  14633. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14634. }
  14635. if (queued) { n++; }
  14636. }
  14637. /* Further enqueues must fail since the queue is full. */
  14638. for (auto i = 0; i < 4; i++) {
  14639. queued = task_queue->enqueue([] {});
  14640. EXPECT_FALSE(queued);
  14641. }
  14642. /* Give the credits to allow the previous tasks to complete. */
  14643. {
  14644. std::unique_lock<std::mutex> lock(sem_mtx);
  14645. credits += qlimit + 1;
  14646. }
  14647. sem_cv.notify_all();
  14648. /* Wait for all the credits to be consumed. */
  14649. {
  14650. std::unique_lock<std::mutex> lock(sem_mtx);
  14651. while (credits > 0) {
  14652. sem_cv.wait(lock);
  14653. }
  14654. }
  14655. /* Check that we are able again to enqueue at least qlimit tasks. */
  14656. for (unsigned int i = 0; i < qlimit; i++) {
  14657. queued = task_queue->enqueue([] {});
  14658. EXPECT_TRUE(queued);
  14659. }
  14660. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14661. task_queue->shutdown();
  14662. #else
  14663. EXPECT_NO_THROW(task_queue->shutdown());
  14664. #endif
  14665. }
  14666. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  14667. Server svr;
  14668. std::string method;
  14669. std::string body;
  14670. auto has_content_length = false;
  14671. auto has_transfer_encoding = false;
  14672. std::atomic<int> bad_requests{0};
  14673. // Leftover body bytes get parsed as a malformed request and answered with
  14674. // 400
  14675. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  14676. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  14677. });
  14678. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  14679. res.set_redirect("/down", StatusCode::SeeOther_303);
  14680. });
  14681. svr.Get("/down", [&](const Request &req, Response &res) {
  14682. method = req.method;
  14683. body = req.body;
  14684. has_content_length = req.has_header("Content-Length");
  14685. has_transfer_encoding = req.has_header("Transfer-Encoding");
  14686. res.set_content("ok", "text/plain");
  14687. });
  14688. auto port = svr.bind_to_any_port(HOST);
  14689. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14690. auto se = detail::scope_exit([&] {
  14691. svr.stop();
  14692. thread.join();
  14693. ASSERT_FALSE(svr.is_running());
  14694. });
  14695. svr.wait_until_ready();
  14696. const std::string payload = "SECRET-BODY";
  14697. auto check = [&](Client &cli, const Result &res) {
  14698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14699. EXPECT_EQ(StatusCode::OK_200, res->status);
  14700. EXPECT_EQ("ok", res->body);
  14701. EXPECT_EQ("GET", method);
  14702. EXPECT_TRUE(body.empty());
  14703. EXPECT_FALSE(has_content_length);
  14704. EXPECT_FALSE(has_transfer_encoding);
  14705. // Nothing of the original body may be left on the connection
  14706. auto res2 = cli.Get("/down");
  14707. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  14708. EXPECT_EQ(StatusCode::OK_200, res2->status);
  14709. EXPECT_EQ("ok", res2->body);
  14710. EXPECT_EQ(0, bad_requests);
  14711. };
  14712. // With content length
  14713. {
  14714. Client cli(HOST, port);
  14715. cli.set_keep_alive(true);
  14716. cli.set_follow_location(true);
  14717. auto res = cli.Post(
  14718. "/up", payload.size(),
  14719. [&](size_t offset, size_t length, DataSink &sink) {
  14720. return sink.write(payload.data() + offset, length);
  14721. },
  14722. "text/plain");
  14723. check(cli, res);
  14724. }
  14725. // Without content length (chunked)
  14726. {
  14727. Client cli(HOST, port);
  14728. cli.set_keep_alive(true);
  14729. cli.set_follow_location(true);
  14730. auto res = cli.Post(
  14731. "/up",
  14732. [&](size_t /*offset*/, DataSink &sink) {
  14733. sink.write(payload.data(), payload.size());
  14734. sink.done();
  14735. return true;
  14736. },
  14737. "text/plain");
  14738. check(cli, res);
  14739. }
  14740. }
  14741. TEST(RedirectTest, LocationPathIsNotDecoded) {
  14742. Server svr;
  14743. std::string target;
  14744. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  14745. // Echo the still-encoded name back in the Location
  14746. const std::string prefix = "/start/";
  14747. res.status = StatusCode::Found_302;
  14748. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  14749. });
  14750. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  14751. target = req.target;
  14752. res.set_content("ok", "text/plain");
  14753. });
  14754. auto port = svr.bind_to_any_port(HOST);
  14755. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14756. auto se = detail::scope_exit([&] {
  14757. svr.stop();
  14758. thread.join();
  14759. ASSERT_FALSE(svr.is_running());
  14760. });
  14761. svr.wait_until_ready();
  14762. // Decoding the Location path would turn the first four into a path
  14763. // separator, a query delimiter, a fragment delimiter and a different
  14764. // percent-encoded octet. The rest must keep reaching the server as they are.
  14765. const std::vector<std::string> names = {
  14766. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  14767. };
  14768. for (auto path_encode : {true, false}) {
  14769. Client cli(HOST, port);
  14770. cli.set_follow_location(true);
  14771. cli.set_path_encode(path_encode);
  14772. for (const auto &name : names) {
  14773. target.clear();
  14774. auto res = cli.Get("/start/" + name);
  14775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14776. EXPECT_EQ(StatusCode::OK_200, res->status);
  14777. EXPECT_EQ("/dest/" + name, target);
  14778. }
  14779. }
  14780. }
  14781. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14782. Server svr;
  14783. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14784. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14785. });
  14786. svr.Get("/hello", [](const Request &req, Response &res) {
  14787. res.set_content(req.get_param_value("key"), "text/plain");
  14788. });
  14789. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14790. auto se = detail::scope_exit([&] {
  14791. svr.stop();
  14792. thread.join();
  14793. ASSERT_FALSE(svr.is_running());
  14794. });
  14795. svr.wait_until_ready();
  14796. {
  14797. Client cli(HOST, PORT);
  14798. cli.set_follow_location(true);
  14799. auto res = cli.Get("/");
  14800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14801. EXPECT_EQ(StatusCode::OK_200, res->status);
  14802. EXPECT_EQ("val&key2=val2", res->body);
  14803. }
  14804. }
  14805. #endif
  14806. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14807. Server svr;
  14808. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14809. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14810. });
  14811. svr.Get("/hello", [](const Request &req, Response &res) {
  14812. res.set_content(req.get_param_value("key"), "text/plain");
  14813. });
  14814. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14815. auto se = detail::scope_exit([&] {
  14816. svr.stop();
  14817. thread.join();
  14818. ASSERT_FALSE(svr.is_running());
  14819. });
  14820. svr.wait_until_ready();
  14821. {
  14822. Client cli(HOST, PORT);
  14823. cli.set_follow_location(true);
  14824. auto res = cli.Get("/");
  14825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14826. EXPECT_EQ(StatusCode::OK_200, res->status);
  14827. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14828. }
  14829. }
  14830. TEST(RedirectTest, RedirectWithPlusInPath) {
  14831. Server svr;
  14832. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14833. res.set_redirect("/a+b");
  14834. });
  14835. // Route pattern uses regex; escape + as \\+
  14836. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14837. res.set_content(req.path, "text/plain");
  14838. });
  14839. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14840. auto se = detail::scope_exit([&] {
  14841. svr.stop();
  14842. thread.join();
  14843. ASSERT_FALSE(svr.is_running());
  14844. });
  14845. svr.wait_until_ready();
  14846. {
  14847. Client cli(HOST, PORT);
  14848. cli.set_follow_location(true);
  14849. auto res = cli.Get("/");
  14850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14851. EXPECT_EQ(StatusCode::OK_200, res->status);
  14852. EXPECT_EQ("/a+b", res->body);
  14853. }
  14854. }
  14855. TEST(RedirectTest, ResolveRelativeLocation) {
  14856. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  14857. const std::vector<std::pair<std::string, std::string>> cases = {
  14858. {"g", "/b/c/g"},
  14859. {"./g", "/b/c/g"},
  14860. {"g/", "/b/c/g/"},
  14861. {"?y", "/b/c/d;p?y"},
  14862. {"g?y", "/b/c/g?y"},
  14863. {"#s", "/b/c/d;p?q#s"},
  14864. {"g#s", "/b/c/g#s"},
  14865. {"g?y#s", "/b/c/g?y#s"},
  14866. {";x", "/b/c/;x"},
  14867. {"g;x", "/b/c/g;x"},
  14868. {".", "/b/c/"},
  14869. {"./", "/b/c/"},
  14870. {"..", "/b/"},
  14871. {"../", "/b/"},
  14872. {"../g", "/b/g"},
  14873. {"../..", "/"},
  14874. {"../../", "/"},
  14875. {"../../g", "/g"},
  14876. {"../../../g", "/g"},
  14877. {"g.", "/b/c/g."},
  14878. {".g", "/b/c/.g"},
  14879. {"g..", "/b/c/g.."},
  14880. {"..g", "/b/c/..g"},
  14881. {"./../g", "/b/g"},
  14882. {"./g/.", "/b/c/g/"},
  14883. {"g/./h", "/b/c/g/h"},
  14884. {"g/../h", "/b/c/h"},
  14885. {"g;x=1/./y", "/b/c/g;x=1/y"},
  14886. {"g;x=1/../y", "/b/c/y"},
  14887. {"g?y/./x", "/b/c/g?y/./x"},
  14888. {"g#s/../x", "/b/c/g#s/../x"},
  14889. // Not relative-path references, so left for parse_url.
  14890. {"/g", "/g"},
  14891. {"//g", "//g"},
  14892. {"http://g/x", "http://g/x"},
  14893. {"g:h", "g:h"},
  14894. };
  14895. for (const auto &c : cases) {
  14896. EXPECT_EQ(c.second,
  14897. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  14898. << c.first;
  14899. }
  14900. }
  14901. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  14902. Server svr;
  14903. svr.Get("/dir/page", [](const Request &req, Response &res) {
  14904. res.set_redirect(req.get_param_value("to"));
  14905. });
  14906. svr.Get("/dir/next", [](const Request &req, Response &res) {
  14907. res.set_content(req.target, "text/plain");
  14908. });
  14909. svr.Get("/other", [](const Request &req, Response &res) {
  14910. res.set_content(req.target, "text/plain");
  14911. });
  14912. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14913. auto se = detail::scope_exit([&] {
  14914. svr.stop();
  14915. thread.join();
  14916. ASSERT_FALSE(svr.is_running());
  14917. });
  14918. svr.wait_until_ready();
  14919. const std::vector<std::pair<std::string, std::string>> cases = {
  14920. {"next", "/dir/next"},
  14921. {"./next?x=1", "/dir/next?x=1"},
  14922. {"../other", "/other"},
  14923. };
  14924. for (const auto &c : cases) {
  14925. Client cli(HOST, PORT);
  14926. cli.set_follow_location(true);
  14927. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  14928. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  14929. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  14930. EXPECT_EQ(c.second, res->body) << c.first;
  14931. }
  14932. }
  14933. #ifdef CPPHTTPLIB_SSL_ENABLED
  14934. TEST(RedirectTest, Issue2185_Online) {
  14935. SSLClient client("github.com");
  14936. client.set_follow_location(true);
  14937. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14938. "Coollab-Windows.zip");
  14939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14940. EXPECT_EQ(StatusCode::OK_200, res->status);
  14941. EXPECT_EQ(9920427U, res->body.size());
  14942. }
  14943. #endif
  14944. TEST(VulnerabilityTest, CRLFInjection) {
  14945. Server svr;
  14946. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14947. res.set_content("Hello 1", "text/plain");
  14948. });
  14949. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14950. res.set_content("Hello 2", "text/plain");
  14951. });
  14952. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14953. res.set_content("Hello 3", "text/plain");
  14954. });
  14955. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14956. res.set_content("Hello 4", "text/plain");
  14957. });
  14958. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14959. for (const auto &x : req.headers) {
  14960. auto key = x.first;
  14961. EXPECT_STRNE("evil", key.c_str());
  14962. }
  14963. });
  14964. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14965. auto se = detail::scope_exit([&] {
  14966. svr.stop();
  14967. thread.join();
  14968. ASSERT_FALSE(svr.is_running());
  14969. });
  14970. svr.wait_until_ready();
  14971. {
  14972. Client cli(HOST, PORT);
  14973. cli.Post("/test1", "A=B",
  14974. "application/x-www-form-urlencoded\r\nevil: hello1");
  14975. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14976. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14977. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14978. }
  14979. }
  14980. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14981. auto server_thread = std::thread([] {
  14982. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14983. default_socket_options(srv);
  14984. sockaddr_in addr{};
  14985. addr.sin_family = AF_INET;
  14986. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14987. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14988. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14989. ::listen(srv, 1);
  14990. sockaddr_in cli_addr{};
  14991. socklen_t cli_len = sizeof(cli_addr);
  14992. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14993. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14994. std::string buf_all;
  14995. char buf[2048];
  14996. ssize_t n;
  14997. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14998. buf_all.append(buf, static_cast<size_t>(n));
  14999. size_t pos;
  15000. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15001. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15002. auto e = request_block.find("\r\n");
  15003. if (e != std::string::npos) {
  15004. auto request_line = request_block.substr(0, e);
  15005. std::string msg =
  15006. "CRLF injection detected in request line: '" + request_line + "'";
  15007. EXPECT_FALSE(true) << msg;
  15008. }
  15009. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15010. ::send(cli,
  15011. #ifdef _WIN32
  15012. static_cast<const char *>(resp.c_str()),
  15013. static_cast<int>(resp.size()),
  15014. #else
  15015. resp.c_str(), resp.size(),
  15016. #endif
  15017. 0);
  15018. buf_all.erase(0, pos + 4);
  15019. }
  15020. }
  15021. detail::close_socket(cli);
  15022. detail::close_socket(srv);
  15023. });
  15024. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15025. auto cli = Client("127.0.0.1", PORT + 1);
  15026. auto headers = Headers{
  15027. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15028. {"Connection", "keep-alive"}};
  15029. auto res = cli.Get("/hi", headers);
  15030. EXPECT_FALSE(res);
  15031. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15032. server_thread.join();
  15033. }
  15034. // A request rejected before any byte reaches the socket must fail right away
  15035. // instead of waiting for a response the server will never send.
  15036. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15037. // The kernel completes the TCP handshake from the listen backlog, so the
  15038. // client connects, but nothing ever reads, responds or closes.
  15039. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15040. default_socket_options(srv);
  15041. sockaddr_in addr{};
  15042. addr.sin_family = AF_INET;
  15043. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15044. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15045. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15046. ASSERT_EQ(0, ::listen(srv, 8));
  15047. auto cli = Client("127.0.0.1", PORT + 1);
  15048. cli.set_read_timeout(10, 0);
  15049. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15050. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15051. std::chrono::steady_clock::now() - start)
  15052. .count();
  15053. };
  15054. {
  15055. Request req;
  15056. req.method = "GE T";
  15057. req.path = "/";
  15058. auto start = std::chrono::steady_clock::now();
  15059. auto res = cli.send(req);
  15060. EXPECT_FALSE(res);
  15061. EXPECT_EQ(Error::Write, res.error());
  15062. EXPECT_LT(elapsed_ms(start), 1000);
  15063. }
  15064. {
  15065. auto start = std::chrono::steady_clock::now();
  15066. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15067. EXPECT_FALSE(res);
  15068. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15069. EXPECT_LT(elapsed_ms(start), 1000);
  15070. }
  15071. EXPECT_FALSE(cli.is_socket_open());
  15072. detail::close_socket(srv);
  15073. }
  15074. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15075. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15076. default_socket_options(srv);
  15077. sockaddr_in addr{};
  15078. addr.sin_family = AF_INET;
  15079. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15080. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15081. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15082. ASSERT_EQ(0, ::listen(srv, 1));
  15083. std::string received;
  15084. auto server_thread = std::thread([&] {
  15085. auto sock = ::accept(srv, nullptr, nullptr);
  15086. if (sock == INVALID_SOCKET) { return; }
  15087. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15088. char buf[2048];
  15089. ssize_t n;
  15090. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15091. received.append(buf, static_cast<size_t>(n));
  15092. }
  15093. detail::close_socket(sock);
  15094. });
  15095. {
  15096. auto cli = Client("127.0.0.1", PORT + 1);
  15097. // "Z" sorts after the default headers, so writing straight to the socket
  15098. // would have sent the request line and those headers before the rejection.
  15099. auto handle =
  15100. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15101. EXPECT_FALSE(handle.is_valid());
  15102. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15103. }
  15104. server_thread.join();
  15105. detail::close_socket(srv);
  15106. EXPECT_TRUE(received.empty()) << received;
  15107. }
  15108. TEST(PathParamsTest, StaticMatch) {
  15109. const auto pattern = "/users/all";
  15110. detail::PathParamsMatcher matcher(pattern);
  15111. Request request;
  15112. request.path = "/users/all";
  15113. ASSERT_TRUE(matcher.match(request));
  15114. std::unordered_map<std::string, std::string> expected_params = {};
  15115. EXPECT_EQ(request.path_params, expected_params);
  15116. }
  15117. TEST(PathParamsTest, StaticMismatch) {
  15118. const auto pattern = "/users/all";
  15119. detail::PathParamsMatcher matcher(pattern);
  15120. Request request;
  15121. request.path = "/users/1";
  15122. ASSERT_FALSE(matcher.match(request));
  15123. }
  15124. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15125. const auto pattern = "/users/:id/subscriptions";
  15126. detail::PathParamsMatcher matcher(pattern);
  15127. Request request;
  15128. request.path = "/users/42/subscriptions";
  15129. ASSERT_TRUE(matcher.match(request));
  15130. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15131. EXPECT_EQ(request.path_params, expected_params);
  15132. }
  15133. TEST(PathParamsTest, SingleParamInTheEnd) {
  15134. const auto pattern = "/users/:id";
  15135. detail::PathParamsMatcher matcher(pattern);
  15136. Request request;
  15137. request.path = "/users/24";
  15138. ASSERT_TRUE(matcher.match(request));
  15139. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15140. EXPECT_EQ(request.path_params, expected_params);
  15141. }
  15142. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15143. const auto pattern = "/users/:id/";
  15144. detail::PathParamsMatcher matcher(pattern);
  15145. Request request;
  15146. request.path = "/users/42/";
  15147. ASSERT_TRUE(matcher.match(request));
  15148. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15149. EXPECT_EQ(request.path_params, expected_params);
  15150. }
  15151. TEST(PathParamsTest, EmptyParam) {
  15152. const auto pattern = "/users/:id/";
  15153. detail::PathParamsMatcher matcher(pattern);
  15154. Request request;
  15155. request.path = "/users//";
  15156. ASSERT_TRUE(matcher.match(request));
  15157. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15158. EXPECT_EQ(request.path_params, expected_params);
  15159. }
  15160. TEST(PathParamsTest, FragmentMismatch) {
  15161. const auto pattern = "/users/:id/";
  15162. detail::PathParamsMatcher matcher(pattern);
  15163. Request request;
  15164. request.path = "/admins/24/";
  15165. ASSERT_FALSE(matcher.match(request));
  15166. }
  15167. TEST(PathParamsTest, ExtraFragments) {
  15168. const auto pattern = "/users/:id";
  15169. detail::PathParamsMatcher matcher(pattern);
  15170. Request request;
  15171. request.path = "/users/42/subscriptions";
  15172. ASSERT_FALSE(matcher.match(request));
  15173. }
  15174. TEST(PathParamsTest, MissingTrailingParam) {
  15175. const auto pattern = "/users/:id";
  15176. detail::PathParamsMatcher matcher(pattern);
  15177. Request request;
  15178. request.path = "/users";
  15179. ASSERT_FALSE(matcher.match(request));
  15180. }
  15181. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15182. const auto pattern = "/users/:id/subscriptions";
  15183. detail::PathParamsMatcher matcher(pattern);
  15184. Request request;
  15185. request.path = "/users/subscriptions";
  15186. ASSERT_FALSE(matcher.match(request));
  15187. }
  15188. TEST(PathParamsTest, MultipleParams) {
  15189. const auto pattern = "/users/:userid/subscriptions/:subid";
  15190. detail::PathParamsMatcher matcher(pattern);
  15191. Request request;
  15192. request.path = "/users/42/subscriptions/2";
  15193. ASSERT_TRUE(matcher.match(request));
  15194. std::unordered_map<std::string, std::string> expected_params = {
  15195. {"userid", "42"}, {"subid", "2"}};
  15196. EXPECT_EQ(request.path_params, expected_params);
  15197. }
  15198. TEST(PathParamsTest, SequenceOfParams) {
  15199. const auto pattern = "/values/:x/:y/:z";
  15200. detail::PathParamsMatcher matcher(pattern);
  15201. Request request;
  15202. request.path = "/values/1/2/3";
  15203. ASSERT_TRUE(matcher.match(request));
  15204. std::unordered_map<std::string, std::string> expected_params = {
  15205. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15206. EXPECT_EQ(request.path_params, expected_params);
  15207. }
  15208. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15209. const auto pattern = "/prefix:suffix";
  15210. detail::PathParamsMatcher matcher(pattern);
  15211. Request request;
  15212. request.path = "/prefix:suffix";
  15213. ASSERT_TRUE(matcher.match(request));
  15214. const std::unordered_map<std::string, std::string> expected_params = {};
  15215. EXPECT_EQ(request.path_params, expected_params);
  15216. }
  15217. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15218. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15219. // calling thread's stack on a long enough path for a quantified pattern;
  15220. // RegexMatcher must refuse to run regex matching on paths beyond
  15221. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15222. detail::RegexMatcher matcher("/files/(.*)");
  15223. Request within_limit;
  15224. within_limit.path = "/files/" + std::string(10, 'A');
  15225. EXPECT_TRUE(matcher.match(within_limit));
  15226. Request over_limit;
  15227. over_limit.path =
  15228. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15229. EXPECT_FALSE(matcher.match(over_limit));
  15230. }
  15231. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15232. Server svr;
  15233. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15234. res.set_content("ok", "text/plain");
  15235. });
  15236. auto port = svr.bind_to_any_port(HOST);
  15237. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15238. auto se = detail::scope_exit([&] {
  15239. svr.stop();
  15240. thread.join();
  15241. ASSERT_FALSE(svr.is_running());
  15242. });
  15243. svr.wait_until_ready();
  15244. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15245. // request URI limit; this used to be able to crash the process.
  15246. std::string path =
  15247. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15248. std::string req = "GET " + path +
  15249. " HTTP/1.1\r\n"
  15250. "Host: " +
  15251. std::string(HOST) + ":" + std::to_string(port) +
  15252. "\r\n"
  15253. "Connection: close\r\n"
  15254. "\r\n";
  15255. std::string response;
  15256. ASSERT_TRUE(send_request(5, req, &response, port));
  15257. EXPECT_NE(std::string::npos, response.find("404"));
  15258. }
  15259. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15260. Server svr;
  15261. auto handler = [](const Request & /*req*/, Response &res) {
  15262. res.set_content("hit", "text/plain");
  15263. };
  15264. // No regex metacharacter, so this one is compared literally
  15265. svr.Get("/literal/route", handler);
  15266. // '.' is a regex metacharacter, so this one must keep regex semantics
  15267. svr.Get("/a.c", handler);
  15268. auto port = svr.bind_to_any_port(HOST);
  15269. std::thread t([&]() { svr.listen_after_bind(); });
  15270. auto se = detail::scope_exit([&] {
  15271. svr.stop();
  15272. t.join();
  15273. ASSERT_FALSE(svr.is_running());
  15274. });
  15275. svr.wait_until_ready();
  15276. Client cli(HOST, port);
  15277. struct {
  15278. const char *path;
  15279. int status;
  15280. } cases[] = {
  15281. {"/literal/route", StatusCode::OK_200},
  15282. {"/literal/routes", StatusCode::NotFound_404},
  15283. {"/literal/rout", StatusCode::NotFound_404},
  15284. {"/abc", StatusCode::OK_200},
  15285. {"/a.c", StatusCode::OK_200},
  15286. };
  15287. for (const auto &x : cases) {
  15288. auto res = cli.Get(x.path);
  15289. ASSERT_TRUE(res) << x.path;
  15290. EXPECT_EQ(x.status, res->status) << x.path;
  15291. }
  15292. }
  15293. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15294. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15295. // from exhausting the stack, so it must only constrain routes that actually
  15296. // run a regular expression. A literal route is matched by comparison and
  15297. // stays usable at any length.
  15298. Server svr;
  15299. const std::string pattern =
  15300. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15301. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15302. res.set_content("hit", "text/plain");
  15303. });
  15304. auto port = svr.bind_to_any_port(HOST);
  15305. std::thread t([&]() { svr.listen_after_bind(); });
  15306. auto se = detail::scope_exit([&] {
  15307. svr.stop();
  15308. t.join();
  15309. ASSERT_FALSE(svr.is_running());
  15310. });
  15311. svr.wait_until_ready();
  15312. Client cli(HOST, port);
  15313. auto res = cli.Get(pattern);
  15314. ASSERT_TRUE(res);
  15315. EXPECT_EQ(StatusCode::OK_200, res->status);
  15316. }
  15317. TEST(ParseUrlTest, VariousPatterns) {
  15318. {
  15319. detail::UrlComponents uc;
  15320. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15321. EXPECT_EQ("http", uc.scheme);
  15322. EXPECT_EQ("example.com", uc.host);
  15323. EXPECT_EQ("8080", uc.port);
  15324. EXPECT_EQ("/path", uc.path);
  15325. EXPECT_EQ("?q=1", uc.query);
  15326. }
  15327. {
  15328. detail::UrlComponents uc;
  15329. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15330. EXPECT_EQ("https", uc.scheme);
  15331. EXPECT_EQ("example.com", uc.host);
  15332. EXPECT_TRUE(uc.port.empty());
  15333. EXPECT_EQ("/path", uc.path);
  15334. }
  15335. {
  15336. detail::UrlComponents uc;
  15337. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15338. EXPECT_EQ("::1", uc.host);
  15339. EXPECT_EQ("8080", uc.port);
  15340. EXPECT_EQ("/path", uc.path);
  15341. }
  15342. {
  15343. detail::UrlComponents uc;
  15344. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15345. }
  15346. {
  15347. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15348. // the path while the connection still targets the bracketed host.
  15349. detail::UrlComponents uc;
  15350. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15351. }
  15352. {
  15353. detail::UrlComponents uc;
  15354. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15355. }
  15356. {
  15357. detail::UrlComponents uc;
  15358. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15359. EXPECT_EQ("::1", uc.host);
  15360. EXPECT_TRUE(uc.port.empty());
  15361. EXPECT_EQ("/path", uc.path);
  15362. }
  15363. {
  15364. detail::UrlComponents uc;
  15365. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15366. EXPECT_TRUE(uc.scheme.empty());
  15367. EXPECT_EQ("example.com", uc.host);
  15368. EXPECT_EQ("/path", uc.path);
  15369. EXPECT_EQ("?q=1", uc.query);
  15370. }
  15371. {
  15372. detail::UrlComponents uc;
  15373. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15374. EXPECT_TRUE(uc.host.empty());
  15375. EXPECT_EQ("/path", uc.path);
  15376. EXPECT_EQ("?q=1", uc.query);
  15377. }
  15378. {
  15379. detail::UrlComponents uc;
  15380. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15381. EXPECT_EQ("example.com", uc.host);
  15382. EXPECT_EQ("8080", uc.port);
  15383. }
  15384. {
  15385. // Unix socket path — must not be parsed as host
  15386. detail::UrlComponents uc;
  15387. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15388. EXPECT_TRUE(uc.host.empty());
  15389. }
  15390. {
  15391. detail::UrlComponents uc;
  15392. ASSERT_TRUE(detail::parse_url("", uc));
  15393. EXPECT_TRUE(uc.host.empty());
  15394. EXPECT_TRUE(uc.path.empty());
  15395. }
  15396. {
  15397. detail::UrlComponents uc;
  15398. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15399. }
  15400. {
  15401. detail::UrlComponents uc;
  15402. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15403. }
  15404. {
  15405. // Accepted by parse_url; callers restrict to http/https
  15406. detail::UrlComponents uc;
  15407. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15408. EXPECT_EQ("ftp", uc.scheme);
  15409. }
  15410. {
  15411. detail::UrlComponents uc;
  15412. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15413. }
  15414. {
  15415. detail::UrlComponents uc;
  15416. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15417. }
  15418. }
  15419. TEST(ParseUrlTest, FragmentHandling) {
  15420. {
  15421. detail::UrlComponents uc;
  15422. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15423. EXPECT_EQ("/path", uc.path);
  15424. EXPECT_TRUE(uc.query.empty());
  15425. }
  15426. {
  15427. detail::UrlComponents uc;
  15428. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15429. EXPECT_TRUE(uc.path.empty());
  15430. EXPECT_TRUE(uc.query.empty());
  15431. }
  15432. }
  15433. TEST(ParseUrlTest, UserinfoHandling) {
  15434. // Userinfo with @ but no colon — host includes @
  15435. detail::UrlComponents uc;
  15436. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15437. EXPECT_EQ("user@host.com", uc.host);
  15438. EXPECT_EQ("/path", uc.path);
  15439. }
  15440. TEST(ParseUrlTest, IPv6EdgeCases) {
  15441. {
  15442. detail::UrlComponents uc;
  15443. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15444. EXPECT_TRUE(uc.scheme.empty());
  15445. EXPECT_EQ("::1", uc.host);
  15446. EXPECT_EQ("8080", uc.port);
  15447. }
  15448. {
  15449. // Zone ID '%25' is not in [a-fA-F0-9:]
  15450. detail::UrlComponents uc;
  15451. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15452. }
  15453. }
  15454. TEST(ParseUrlTest, SchemeEdgeCases) {
  15455. {
  15456. detail::UrlComponents uc;
  15457. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15458. }
  15459. {
  15460. detail::UrlComponents uc;
  15461. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15462. }
  15463. {
  15464. detail::UrlComponents uc;
  15465. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15466. }
  15467. }
  15468. TEST(ParseUrlTest, PortEdgeCases) {
  15469. {
  15470. detail::UrlComponents uc;
  15471. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15472. EXPECT_TRUE(uc.port.empty());
  15473. EXPECT_EQ("/path", uc.path);
  15474. }
  15475. {
  15476. // parse_url accepts any port string; validation is done by parse_port
  15477. detail::UrlComponents uc;
  15478. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15479. EXPECT_EQ("abc", uc.port);
  15480. }
  15481. }
  15482. TEST(ParseUrlTest, WebSocketPatterns) {
  15483. {
  15484. detail::UrlComponents uc;
  15485. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15486. EXPECT_EQ("ws", uc.scheme);
  15487. EXPECT_EQ("echo.example.com", uc.host);
  15488. EXPECT_EQ("8080", uc.port);
  15489. EXPECT_EQ("/ws", uc.path);
  15490. }
  15491. {
  15492. detail::UrlComponents uc;
  15493. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15494. EXPECT_EQ("wss", uc.scheme);
  15495. EXPECT_EQ("echo.example.com", uc.host);
  15496. EXPECT_TRUE(uc.port.empty());
  15497. EXPECT_EQ("/ws", uc.path);
  15498. }
  15499. }
  15500. TEST(ParseUrlTest, QueryOnly) {
  15501. detail::UrlComponents uc;
  15502. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15503. EXPECT_TRUE(uc.host.empty());
  15504. EXPECT_TRUE(uc.path.empty());
  15505. EXPECT_EQ("?q=1&r=2", uc.query);
  15506. }
  15507. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15508. detail::UrlComponents uc;
  15509. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15510. EXPECT_TRUE(uc.scheme.empty());
  15511. EXPECT_EQ("example.com", uc.host);
  15512. EXPECT_EQ("443", uc.port);
  15513. EXPECT_EQ("/path", uc.path);
  15514. }
  15515. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15516. // If ipv6 regex working, regex match codepath is taken.
  15517. // else port will default to 80 in Client impl
  15518. int clientImplMagicPort = 80;
  15519. int port = 4321;
  15520. // above ports must be different to avoid false negative
  15521. EXPECT_NE(clientImplMagicPort, port);
  15522. std::string ipV6TestURL = "http://[ff06::c3]";
  15523. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15524. CLIENT_PRIVATE_KEY_FILE);
  15525. EXPECT_EQ(cli.port(), port);
  15526. }
  15527. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15528. auto file_path = "./www/dir/index.html";
  15529. auto dir_path = "./www/dir";
  15530. detail::FileStat stat_file(file_path);
  15531. EXPECT_TRUE(stat_file.is_file());
  15532. EXPECT_FALSE(stat_file.is_dir());
  15533. detail::FileStat stat_dir(dir_path);
  15534. EXPECT_FALSE(stat_dir.is_file());
  15535. EXPECT_TRUE(stat_dir.is_dir());
  15536. }
  15537. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15538. // IPv4 with default HTTP port (80)
  15539. EXPECT_EQ("example.com",
  15540. detail::make_host_and_port_string("example.com", 80, false));
  15541. // IPv4 with default HTTPS port (443)
  15542. EXPECT_EQ("example.com",
  15543. detail::make_host_and_port_string("example.com", 443, true));
  15544. // IPv4 with non-default HTTP port
  15545. EXPECT_EQ("example.com:8080",
  15546. detail::make_host_and_port_string("example.com", 8080, false));
  15547. // IPv4 with non-default HTTPS port
  15548. EXPECT_EQ("example.com:8443",
  15549. detail::make_host_and_port_string("example.com", 8443, true));
  15550. // IPv6 with default HTTP port (80)
  15551. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15552. // IPv6 with default HTTPS port (443)
  15553. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15554. // IPv6 with non-default HTTP port
  15555. EXPECT_EQ("[::1]:8080",
  15556. detail::make_host_and_port_string("::1", 8080, false));
  15557. // IPv6 with non-default HTTPS port
  15558. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15559. // IPv6 full address with default port
  15560. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15561. detail::make_host_and_port_string(
  15562. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15563. // IPv6 full address with non-default port
  15564. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15565. detail::make_host_and_port_string(
  15566. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15567. // IPv6 localhost with non-default port
  15568. EXPECT_EQ("[::1]:3000",
  15569. detail::make_host_and_port_string("::1", 3000, false));
  15570. // IPv6 with zone ID (link-local address) with default port
  15571. EXPECT_EQ("[fe80::1%eth0]",
  15572. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15573. // IPv6 with zone ID (link-local address) with non-default port
  15574. EXPECT_EQ("[fe80::1%eth0]:8080",
  15575. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15576. // Edge case: Port 443 with is_ssl=false (should add port)
  15577. EXPECT_EQ("example.com:443",
  15578. detail::make_host_and_port_string("example.com", 443, false));
  15579. // Edge case: Port 80 with is_ssl=true (should add port)
  15580. EXPECT_EQ("example.com:80",
  15581. detail::make_host_and_port_string("example.com", 80, true));
  15582. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15583. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15584. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15585. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15586. // Security fix: Already bracketed IPv6 should not get double brackets
  15587. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15588. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15589. EXPECT_EQ("[::1]:8080",
  15590. detail::make_host_and_port_string("[::1]", 8080, false));
  15591. EXPECT_EQ("[2001:db8::1]:8080",
  15592. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15593. EXPECT_EQ("[fe80::1%eth0]",
  15594. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15595. EXPECT_EQ("[fe80::1%eth0]:8080",
  15596. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15597. // Edge case: Empty host (should return as-is)
  15598. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15599. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15600. // This is a known limitation but shouldn't crash
  15601. EXPECT_EQ("[host:name]",
  15602. detail::make_host_and_port_string("host:name", 80, false));
  15603. // Port number edge cases (no validation, but should not crash)
  15604. EXPECT_EQ("example.com:0",
  15605. detail::make_host_and_port_string("example.com", 0, false));
  15606. EXPECT_EQ("example.com:-1",
  15607. detail::make_host_and_port_string("example.com", -1, false));
  15608. EXPECT_EQ("example.com:65535",
  15609. detail::make_host_and_port_string("example.com", 65535, false));
  15610. EXPECT_EQ("example.com:65536",
  15611. detail::make_host_and_port_string("example.com", 65536, false));
  15612. }
  15613. #ifdef CPPHTTPLIB_SSL_ENABLED
  15614. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15615. httplib::SSLClient cli("roblox.com", 443);
  15616. cli.set_follow_location(true);
  15617. auto res = cli.Get("/");
  15618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15619. EXPECT_EQ(StatusCode::OK_200, res->status);
  15620. }
  15621. #endif
  15622. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15623. Server svr;
  15624. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15625. EXPECT_EQ(res.status, 400);
  15626. });
  15627. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15628. auto se = detail::scope_exit([&] {
  15629. svr.stop();
  15630. thread.join();
  15631. ASSERT_FALSE(svr.is_running());
  15632. });
  15633. svr.wait_until_ready();
  15634. Client cli(HOST, PORT);
  15635. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15636. }
  15637. TEST(InvalidHeaderCharsTest, is_field_name) {
  15638. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15639. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15640. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15641. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15642. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15643. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15644. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15645. EXPECT_FALSE(detail::fields::is_field_name(""));
  15646. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15647. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15648. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15649. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15650. }
  15651. TEST(InvalidHeaderCharsTest, is_field_value) {
  15652. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15653. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15654. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15655. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15656. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15657. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15658. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15659. EXPECT_TRUE(detail::fields::is_field_value(""));
  15660. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15661. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15662. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15663. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15664. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15665. }
  15666. TEST(InvalidHeaderCharsTest, OnServer) {
  15667. Server svr;
  15668. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15669. std::string header = "Not Set";
  15670. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15671. res.set_header(header, "value");
  15672. res.set_content("Page Content Page Content", "text/plain");
  15673. });
  15674. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15675. std::string header = "Not Set";
  15676. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15677. res.set_header("X-Test", header);
  15678. res.set_content("Page Content Page Content", "text/plain");
  15679. });
  15680. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15681. auto se = detail::scope_exit([&] {
  15682. svr.stop();
  15683. thread.join();
  15684. ASSERT_FALSE(svr.is_running());
  15685. });
  15686. svr.wait_until_ready();
  15687. Client cli(HOST, PORT);
  15688. {
  15689. auto res = cli.Get(
  15690. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15692. EXPECT_EQ("Page Content Page Content", res->body);
  15693. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15694. }
  15695. {
  15696. auto res = cli.Get(
  15697. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15699. EXPECT_EQ("Page Content Page Content", res->body);
  15700. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15701. }
  15702. }
  15703. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15704. auto handled = false;
  15705. Server svr;
  15706. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15707. thread t = thread([&] { svr.listen(HOST, PORT); });
  15708. auto se = detail::scope_exit([&] {
  15709. svr.stop();
  15710. t.join();
  15711. ASSERT_FALSE(svr.is_running());
  15712. ASSERT_FALSE(handled);
  15713. });
  15714. svr.wait_until_ready();
  15715. auto req = "POST /test HTTP/1.1\r\n"
  15716. "Content-Length: x\r\n"
  15717. "\r\n";
  15718. std::string response;
  15719. ASSERT_TRUE(send_request(1, req, &response));
  15720. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15721. response.substr(0, response.find("\r\n")));
  15722. }
  15723. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15724. // case-insensitive, and a server that receives a 100-continue expectation in
  15725. // an HTTP/1.0 request MUST ignore it.
  15726. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15727. std::string response;
  15728. ASSERT_TRUE(send_request(1, req, &response, port));
  15729. *got_100 = response.find("100 Continue") != std::string::npos;
  15730. }
  15731. class ExpectTokenTest : public ::testing::Test {
  15732. protected:
  15733. void SetUp() override {
  15734. svr_.Post("/p", [](const Request &, Response &res) {
  15735. res.set_content("ok", "text/plain");
  15736. });
  15737. port_ = svr_.bind_to_any_port(HOST);
  15738. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15739. svr_.wait_until_ready();
  15740. }
  15741. void TearDown() override {
  15742. svr_.stop();
  15743. if (thread_.joinable()) { thread_.join(); }
  15744. }
  15745. std::string request(const char *version, const char *expect_value) const {
  15746. return std::string("POST /p ") + version +
  15747. "\r\n"
  15748. "Host: localhost\r\n"
  15749. "Content-Length: 2\r\n"
  15750. "Connection: close\r\n"
  15751. "Expect: " +
  15752. expect_value +
  15753. "\r\n"
  15754. "\r\n"
  15755. "hi";
  15756. }
  15757. Server svr_;
  15758. int port_ = 0;
  15759. thread thread_;
  15760. };
  15761. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15762. bool got_100 = false;
  15763. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15764. EXPECT_TRUE(got_100);
  15765. }
  15766. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15767. bool got_100 = true;
  15768. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15769. EXPECT_FALSE(got_100);
  15770. }
  15771. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15772. bool got_100 = false;
  15773. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15774. EXPECT_TRUE(got_100);
  15775. }
  15776. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15777. bool got_100 = false;
  15778. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15779. EXPECT_TRUE(got_100);
  15780. }
  15781. // `100 Continue` is sent only when the server starts reading the body, so a
  15782. // request rejected before that never invites the client to send it. The
  15783. // requests below carry the expectation but withhold the body, as a client
  15784. // waiting for `100 Continue` would.
  15785. // A POST that expects `100 Continue` and withholds its two-byte body.
  15786. static std::string expect_headers_only(const std::string &path) {
  15787. return "POST " + path +
  15788. " HTTP/1.1\r\n"
  15789. "Host: localhost\r\n"
  15790. "Content-Length: 2\r\n"
  15791. "Expect: 100-continue\r\n"
  15792. "\r\n";
  15793. }
  15794. class ExpectLazyContinueTest : public ::testing::Test {
  15795. protected:
  15796. void SetUp() override {
  15797. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15798. if (req.path == "/pre-routing") {
  15799. res.status = StatusCode::Unauthorized_401;
  15800. return Server::HandlerResponse::Handled;
  15801. }
  15802. return Server::HandlerResponse::Unhandled;
  15803. });
  15804. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15805. if (req.matched_route == "/pre-request") {
  15806. res.status = StatusCode::Forbidden_403;
  15807. return Server::HandlerResponse::Handled;
  15808. }
  15809. return Server::HandlerResponse::Unhandled;
  15810. });
  15811. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15812. res.set_content("ok", "text/plain");
  15813. });
  15814. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15815. res.set_content("ok", "text/plain");
  15816. });
  15817. svr_.Post("/reader-used", [](const Request &, Response &res,
  15818. const ContentReader &content_reader) {
  15819. std::string body;
  15820. content_reader([&](const char *data, size_t len) {
  15821. body.append(data, len);
  15822. return true;
  15823. });
  15824. res.set_content(body, "text/plain");
  15825. });
  15826. svr_.Post("/reader-unused",
  15827. [](const Request &, Response &res, const ContentReader &) {
  15828. res.set_content("ignored", "text/plain");
  15829. });
  15830. port_ = svr_.bind_to_any_port(HOST);
  15831. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15832. svr_.wait_until_ready();
  15833. }
  15834. void TearDown() override {
  15835. svr_.stop();
  15836. if (thread_.joinable()) { thread_.join(); }
  15837. }
  15838. // Sends `req` and reads until the server closes the connection. Returns
  15839. // false if the read had to wait for the client-side timeout instead.
  15840. bool send_until_closed(const std::string &req, std::string *resp) const {
  15841. auto start = std::chrono::steady_clock::now();
  15842. if (!send_request(3, req, resp, port_)) { return false; }
  15843. auto elapsed = std::chrono::steady_clock::now() - start;
  15844. return elapsed < std::chrono::seconds(2);
  15845. }
  15846. // The final response comes without `100 Continue`, and the server closes
  15847. // the connection since the body may or may not follow.
  15848. void expect_final_without_interim(const std::string &path,
  15849. const char *status_line) const {
  15850. std::string resp;
  15851. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15852. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15853. EXPECT_EQ(0u, resp.find(status_line));
  15854. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15855. }
  15856. Server svr_;
  15857. int port_ = 0;
  15858. thread thread_;
  15859. };
  15860. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15861. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15862. }
  15863. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15864. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15865. }
  15866. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15867. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15868. }
  15869. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15870. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15871. }
  15872. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15873. // The body follows once `100 Continue` has had time to arrive.
  15874. auto req = expect_headers_only("/reader-used");
  15875. req.insert(req.size() - 2, "Connection: close\r\n");
  15876. std::string resp;
  15877. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15878. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15879. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15880. EXPECT_NE(std::string::npos, resp.find("hi"));
  15881. }
  15882. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15883. // Large enough for the client to add `Expect: 100-continue` itself.
  15884. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15885. std::atomic<bool> body_sent{false};
  15886. Client cli(HOST, port_);
  15887. auto res = cli.Post(
  15888. "/pre-request", length,
  15889. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15890. body_sent = true;
  15891. std::string chunk(len, 'x');
  15892. sink.write(chunk.data(), chunk.size());
  15893. return true;
  15894. },
  15895. "application/octet-stream");
  15896. ASSERT_TRUE(res);
  15897. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15898. EXPECT_FALSE(body_sent);
  15899. }
  15900. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  15901. Server svr;
  15902. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  15903. return StatusCode::ExpectationFailed_417;
  15904. });
  15905. svr.Post("/p", [](const Request &, Response &res) {
  15906. res.set_content("ok", "text/plain");
  15907. });
  15908. auto port = svr.bind_to_any_port(HOST);
  15909. thread t = thread([&] { svr.listen_after_bind(); });
  15910. auto se = detail::scope_exit([&] {
  15911. svr.stop();
  15912. t.join();
  15913. });
  15914. svr.wait_until_ready();
  15915. std::string resp;
  15916. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  15917. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  15918. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15919. // Exactly one response: the route handler must not run after the 417.
  15920. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  15921. }
  15922. #ifndef _WIN32
  15923. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15924. static constexpr char reject[] = "Unauthorized";
  15925. static constexpr char accept[] = "Upload accepted";
  15926. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15927. Server svr;
  15928. svr.set_expect_100_continue_handler(
  15929. [](const Request & /*req*/, Response &res) {
  15930. res.status = StatusCode::Unauthorized_401;
  15931. res.set_content(reject, "text/plain");
  15932. return res.status;
  15933. });
  15934. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15935. res.set_content(accept, "text/plain");
  15936. });
  15937. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15938. auto se = detail::scope_exit([&] {
  15939. svr.stop();
  15940. thread.join();
  15941. ASSERT_FALSE(svr.is_running());
  15942. });
  15943. svr.wait_until_ready();
  15944. {
  15945. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15946. curl_easy_init(), &curl_easy_cleanup};
  15947. ASSERT_NE(curl, nullptr);
  15948. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15949. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15950. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15951. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15952. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15953. &curl_slist_free_all};
  15954. ASSERT_NE(list, nullptr);
  15955. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15956. struct read_data {
  15957. size_t read_size;
  15958. size_t total_size;
  15959. } data = {0, total_size};
  15960. using read_callback_t =
  15961. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15962. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15963. void *userdata) -> size_t {
  15964. read_data *d = (read_data *)userdata;
  15965. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15966. std::fill_n(ptr, size * nmemb, 'A');
  15967. d->read_size += size * nmemb;
  15968. return size * nmemb;
  15969. };
  15970. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15971. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15972. std::vector<char> buffer;
  15973. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15974. using write_callback_t =
  15975. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15976. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15977. void *userdata) -> size_t {
  15978. std::vector<char> *buf = (std::vector<char> *)userdata;
  15979. buf->reserve(buf->size() + size * nmemb + 1);
  15980. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15981. return size * nmemb;
  15982. };
  15983. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15984. {
  15985. const auto res = curl_easy_perform(curl.get());
  15986. ASSERT_EQ(res, CURLE_OK);
  15987. }
  15988. {
  15989. auto response_code = long{};
  15990. const auto res =
  15991. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15992. ASSERT_EQ(res, CURLE_OK);
  15993. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15994. }
  15995. {
  15996. auto dl = curl_off_t{};
  15997. const auto res =
  15998. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15999. ASSERT_EQ(res, CURLE_OK);
  16000. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16001. }
  16002. {
  16003. buffer.push_back('\0');
  16004. ASSERT_STRCASEEQ(buffer.data(), reject);
  16005. }
  16006. }
  16007. }
  16008. #endif
  16009. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16010. // Regression test for #2458.
  16011. //
  16012. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16013. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16014. // ticket can make the client socket spuriously readable during the
  16015. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16016. // the client withholds the body and then blocks reading a response that never
  16017. // comes, failing with `Failed to read connection`.
  16018. //
  16019. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16020. // within the timeout. This raw OpenSSL server deliberately never sends
  16021. // `100 Continue`; the client must still deliver the body and receive 200.
  16022. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16023. signal(SIGPIPE, SIG_IGN);
  16024. const auto port = PORT + 4;
  16025. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16026. ASSERT_NE(srv, INVALID_SOCKET);
  16027. int opt = 1;
  16028. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16029. sockaddr_in addr{};
  16030. addr.sin_family = AF_INET;
  16031. addr.sin_port = htons(static_cast<uint16_t>(port));
  16032. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16033. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16034. ASSERT_EQ(0, ::listen(srv, 1));
  16035. std::atomic<size_t> server_body_bytes{0};
  16036. auto server_thread = std::thread([&] {
  16037. sockaddr_in cli_addr{};
  16038. socklen_t cli_len = sizeof(cli_addr);
  16039. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16040. if (cli == INVALID_SOCKET) { return; }
  16041. // Bound the lifetime of the server side so a buggy client (which never
  16042. // sends the body) cannot make this thread block forever on join.
  16043. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16044. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16045. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16046. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16047. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16048. SSL *ssl = SSL_new(ctx);
  16049. SSL_set_fd(ssl, static_cast<int>(cli));
  16050. if (SSL_accept(ssl) > 0) {
  16051. // Read the request headers. Reading here also flushes the TLS 1.3
  16052. // session tickets to the client. Deliberately do NOT send
  16053. // `100 Continue`.
  16054. std::string buf;
  16055. char tmp[1024];
  16056. while (buf.find("\r\n\r\n") == std::string::npos) {
  16057. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16058. if (n <= 0) { break; }
  16059. buf.append(tmp, static_cast<size_t>(n));
  16060. }
  16061. // A correct client sends the body now; count what arrives.
  16062. auto pos = buf.find("\r\n\r\n");
  16063. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16064. while (body < 4096) {
  16065. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16066. if (n <= 0) { break; }
  16067. body += static_cast<size_t>(n);
  16068. }
  16069. server_body_bytes = body;
  16070. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16071. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16072. SSL_shutdown(ssl);
  16073. }
  16074. SSL_free(ssl);
  16075. detail::close_socket(cli);
  16076. SSL_CTX_free(ctx);
  16077. });
  16078. auto se = detail::scope_exit([&] {
  16079. server_thread.join();
  16080. detail::close_socket(srv);
  16081. });
  16082. SSLClient cli("127.0.0.1", port);
  16083. cli.enable_server_certificate_verification(false);
  16084. cli.set_connection_timeout(5, 0);
  16085. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16086. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16087. std::string body(4096, 'A');
  16088. auto res = cli.Put("/api/test", body, "application/json");
  16089. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16090. EXPECT_EQ(StatusCode::OK_200, res->status);
  16091. EXPECT_EQ(body.size(), server_body_bytes.load());
  16092. }
  16093. #endif
  16094. template <typename S, typename C>
  16095. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16096. svr.Get("/stream", [&](const Request &, Response &res) {
  16097. auto data = new std::string("01234567890123456789");
  16098. res.set_content_provider(
  16099. data->size(), "text/plain",
  16100. [&, data](size_t offset, size_t length, DataSink &sink) {
  16101. const size_t DATA_CHUNK_SIZE = 4;
  16102. const auto &d = *data;
  16103. std::this_thread::sleep_for(std::chrono::seconds(1));
  16104. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16105. return true;
  16106. },
  16107. [data](bool success) {
  16108. EXPECT_FALSE(success);
  16109. delete data;
  16110. });
  16111. });
  16112. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16113. auto i = new size_t(0);
  16114. res.set_content_provider(
  16115. "text/plain",
  16116. [i](size_t, DataSink &sink) {
  16117. if (*i < 5) {
  16118. std::this_thread::sleep_for(std::chrono::seconds(1));
  16119. sink.write("abcd", 4);
  16120. (*i)++;
  16121. } else {
  16122. sink.done();
  16123. }
  16124. return true;
  16125. },
  16126. [i](bool success) {
  16127. EXPECT_FALSE(success);
  16128. delete i;
  16129. });
  16130. });
  16131. svr.Get("/chunked", [&](const Request &, Response &res) {
  16132. auto i = new size_t(0);
  16133. res.set_chunked_content_provider(
  16134. "text/plain",
  16135. [i](size_t, DataSink &sink) {
  16136. if (*i < 5) {
  16137. std::this_thread::sleep_for(std::chrono::seconds(1));
  16138. sink.os << "abcd";
  16139. (*i)++;
  16140. } else {
  16141. sink.done();
  16142. }
  16143. return true;
  16144. },
  16145. [i](bool success) {
  16146. EXPECT_FALSE(success);
  16147. delete i;
  16148. });
  16149. });
  16150. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16151. auto se = detail::scope_exit([&] {
  16152. svr.stop();
  16153. listen_thread.join();
  16154. ASSERT_FALSE(svr.is_running());
  16155. });
  16156. svr.wait_until_ready();
  16157. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16158. {
  16159. auto start = std::chrono::steady_clock::now();
  16160. auto res = cli.Get("/stream");
  16161. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16162. std::chrono::steady_clock::now() - start)
  16163. .count();
  16164. ASSERT_FALSE(res);
  16165. EXPECT_EQ(Error::Read, res.error());
  16166. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16167. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16168. }
  16169. {
  16170. auto start = std::chrono::steady_clock::now();
  16171. auto res = cli.Get("/stream_without_length");
  16172. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16173. std::chrono::steady_clock::now() - start)
  16174. .count();
  16175. ASSERT_FALSE(res);
  16176. EXPECT_EQ(Error::Read, res.error());
  16177. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16178. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16179. }
  16180. {
  16181. auto start = std::chrono::steady_clock::now();
  16182. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16183. EXPECT_EQ("abcd", string(data, data_length));
  16184. return true;
  16185. });
  16186. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16187. std::chrono::steady_clock::now() - start)
  16188. .count();
  16189. ASSERT_FALSE(res);
  16190. EXPECT_EQ(Error::Read, res.error());
  16191. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16192. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16193. }
  16194. }
  16195. TEST(MaxTimeoutTest, ContentStream) {
  16196. time_t timeout = 2000;
  16197. time_t threshold = 200;
  16198. Server svr;
  16199. Client cli("localhost", PORT);
  16200. max_timeout_test(svr, cli, timeout, threshold);
  16201. }
  16202. #ifdef CPPHTTPLIB_SSL_ENABLED
  16203. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16204. time_t timeout = 2000;
  16205. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16206. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16207. SSLClient cli("localhost", PORT);
  16208. cli.enable_server_certificate_verification(false);
  16209. max_timeout_test(svr, cli, timeout, threshold);
  16210. }
  16211. #endif
  16212. class EventDispatcher {
  16213. public:
  16214. EventDispatcher() {}
  16215. bool wait_event(DataSink *sink) {
  16216. unique_lock<mutex> lk(m_);
  16217. int id = id_;
  16218. // Wait with timeout to prevent hanging if client disconnects
  16219. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16220. [&] { return cid_ == id; })) {
  16221. return false; // Timeout occurred
  16222. }
  16223. sink->write(message_.data(), message_.size());
  16224. return true;
  16225. }
  16226. void send_event(const string &message) {
  16227. lock_guard<mutex> lk(m_);
  16228. cid_ = id_++;
  16229. message_ = message;
  16230. cv_.notify_all();
  16231. }
  16232. private:
  16233. mutex m_;
  16234. condition_variable cv_;
  16235. atomic_int id_{0};
  16236. atomic_int cid_{-1};
  16237. string message_;
  16238. };
  16239. TEST(ClientInThreadTest, Issue2068) {
  16240. EventDispatcher ed;
  16241. Server svr;
  16242. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16243. res.set_chunked_content_provider("text/event-stream",
  16244. [&](size_t /*offset*/, DataSink &sink) {
  16245. return ed.wait_event(&sink);
  16246. });
  16247. });
  16248. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16249. svr.wait_until_ready();
  16250. thread event_thread([&] {
  16251. int id = 0;
  16252. while (svr.is_running()) {
  16253. this_thread::sleep_for(chrono::milliseconds(500));
  16254. std::stringstream ss;
  16255. ss << "data: " << id << "\n\n";
  16256. ed.send_event(ss.str());
  16257. id++;
  16258. }
  16259. });
  16260. auto se = detail::scope_exit([&] {
  16261. svr.stop();
  16262. listen_thread.join();
  16263. event_thread.join();
  16264. ASSERT_FALSE(svr.is_running());
  16265. });
  16266. {
  16267. auto client = detail::make_unique<Client>(HOST, PORT);
  16268. client->set_read_timeout(std::chrono::minutes(10));
  16269. std::atomic<bool> stop{false};
  16270. std::thread t([&] {
  16271. client->Get("/event1",
  16272. [&](const char *, size_t) -> bool { return !stop; });
  16273. });
  16274. std::this_thread::sleep_for(std::chrono::seconds(2));
  16275. stop = true;
  16276. client->stop();
  16277. t.join();
  16278. // Reset client after thread has finished
  16279. client.reset();
  16280. }
  16281. }
  16282. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16283. auto handled = false;
  16284. Server svr;
  16285. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16286. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16287. auto se = detail::scope_exit([&] {
  16288. svr.stop();
  16289. t.join();
  16290. ASSERT_FALSE(svr.is_running());
  16291. ASSERT_FALSE(handled);
  16292. });
  16293. svr.wait_until_ready();
  16294. // Two Content-Length headers with different values — must be rejected
  16295. auto req = "POST /test HTTP/1.1\r\n"
  16296. "Content-Length: 5\r\n"
  16297. "Content-Length: 10\r\n"
  16298. "\r\n"
  16299. "hello";
  16300. std::string response;
  16301. ASSERT_TRUE(send_request(1, req, &response));
  16302. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16303. response.substr(0, response.find("\r\n")));
  16304. }
  16305. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16306. auto handled = false;
  16307. Server svr;
  16308. svr.Post("/test", [&](const Request &, Response &res) {
  16309. handled = true;
  16310. res.set_content("ok", "text/plain");
  16311. });
  16312. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16313. auto se = detail::scope_exit([&] {
  16314. svr.stop();
  16315. t.join();
  16316. ASSERT_FALSE(svr.is_running());
  16317. ASSERT_TRUE(handled);
  16318. });
  16319. svr.wait_until_ready();
  16320. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16321. auto req = "POST /test HTTP/1.1\r\n"
  16322. "Content-Length: 5\r\n"
  16323. "Content-Length: 5\r\n"
  16324. "\r\n"
  16325. "hello";
  16326. std::string response;
  16327. ASSERT_TRUE(send_request(1, req, &response));
  16328. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16329. }
  16330. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16331. Server svr;
  16332. svr.Get("/", [](const Request &req, Response &res) {
  16333. EXPECT_EQ(2U, req.trailers.size());
  16334. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16335. // Denied
  16336. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16337. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16338. // Accepted
  16339. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16340. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16341. EXPECT_TRUE(req.has_trailer("X-World"));
  16342. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16343. res.set_content("ok", "text/plain");
  16344. });
  16345. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16346. auto se = detail::scope_exit([&] {
  16347. svr.stop();
  16348. t.join();
  16349. ASSERT_FALSE(svr.is_running());
  16350. });
  16351. svr.wait_until_ready();
  16352. const std::string req = "GET / HTTP/1.1\r\n"
  16353. "Transfer-Encoding: chunked\r\n"
  16354. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16355. "\r\n"
  16356. "0\r\n"
  16357. "Content-Length: 10\r\n"
  16358. "Host: internal.local\r\n"
  16359. "Content-Type: malicious/content\r\n"
  16360. "Cookie: any\r\n"
  16361. "Set-Cookie: any\r\n"
  16362. "X-Forwarded-For: attacker.com\r\n"
  16363. "X-Real-Ip: 1.1.1.1\r\n"
  16364. "X-Hello: hello\r\n"
  16365. "X-World: world\r\n"
  16366. "\r\n";
  16367. std::string res;
  16368. ASSERT_TRUE(send_request(1, req, &res));
  16369. }
  16370. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16371. // several field lines, and the combined value is what has to be parsed. A
  16372. // Trailer field split across lines therefore declares every name it lists;
  16373. // reading only the first line silently drops the trailers the later lines
  16374. // declare. The prohibited-trailer filter still applies to every line.
  16375. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16376. Server svr;
  16377. size_t observed_trailer_count = 0;
  16378. std::string observed_hello;
  16379. std::string observed_world;
  16380. bool observed_content_length = true;
  16381. svr.Get("/", [&](const Request &req, Response &res) {
  16382. observed_trailer_count = req.trailers.size();
  16383. observed_hello = req.get_trailer_value("X-Hello");
  16384. observed_world = req.get_trailer_value("X-World");
  16385. observed_content_length = req.has_trailer("Content-Length");
  16386. res.set_content("ok", "text/plain");
  16387. });
  16388. auto port = svr.bind_to_any_port(HOST);
  16389. thread t = thread([&]() { svr.listen_after_bind(); });
  16390. auto se = detail::scope_exit([&] {
  16391. svr.stop();
  16392. t.join();
  16393. ASSERT_FALSE(svr.is_running());
  16394. });
  16395. svr.wait_until_ready();
  16396. const std::string req = "GET / HTTP/1.1\r\n"
  16397. "Transfer-Encoding: chunked\r\n"
  16398. "Trailer: X-Hello\r\n"
  16399. "Trailer: X-World, Content-Length\r\n"
  16400. "\r\n"
  16401. "0\r\n"
  16402. "X-Hello: hello\r\n"
  16403. "X-World: world\r\n"
  16404. "Content-Length: 10\r\n"
  16405. "\r\n";
  16406. std::string res;
  16407. ASSERT_TRUE(send_request(1, req, &res, port));
  16408. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16409. // Accepted: both field lines contribute to the declared set
  16410. EXPECT_EQ(2U, observed_trailer_count);
  16411. EXPECT_EQ(observed_hello, "hello");
  16412. EXPECT_EQ(observed_world, "world");
  16413. // Denied: a prohibited name stays prohibited on a later field line
  16414. EXPECT_FALSE(observed_content_length);
  16415. }
  16416. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16417. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16418. // unbounded run of fields that are never declared, because the counter would
  16419. // only advance for declared fields.
  16420. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16421. Server svr;
  16422. bool handler_called = false;
  16423. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16424. handler_called = true;
  16425. res.set_content("ok", "text/plain");
  16426. });
  16427. auto port = svr.bind_to_any_port(HOST);
  16428. thread t = thread([&]() { svr.listen_after_bind(); });
  16429. auto se = detail::scope_exit([&] {
  16430. svr.stop();
  16431. t.join();
  16432. ASSERT_FALSE(svr.is_running());
  16433. });
  16434. svr.wait_until_ready();
  16435. // Declare nothing, then send far more undeclared trailer fields than the
  16436. // header-count limit. Parsing must stop and reject the request rather than
  16437. // read every line.
  16438. std::string req = "GET / HTTP/1.1\r\n"
  16439. "Transfer-Encoding: chunked\r\n"
  16440. "\r\n"
  16441. "0\r\n";
  16442. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16443. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16444. }
  16445. req += "\r\n";
  16446. std::string res;
  16447. ASSERT_TRUE(send_request(1, req, &res, port));
  16448. // The request is rejected before the handler runs.
  16449. EXPECT_FALSE(handler_called);
  16450. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16451. }
  16452. // The set of declared trailer names is capped so a peer cannot grow it without
  16453. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16454. // declared past the cap is not honored, even if the field is actually sent.
  16455. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16456. Server svr;
  16457. // One name inside the cap and one past it, so the test tracks the cap rather
  16458. // than a fixed count.
  16459. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16460. const std::string within_cap_name = "X-T-0";
  16461. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16462. bool observed_within_cap = false;
  16463. bool observed_past_cap = false;
  16464. svr.Get("/", [&](const Request &req, Response &res) {
  16465. observed_within_cap = req.has_trailer(within_cap_name);
  16466. observed_past_cap = req.has_trailer(past_cap_name);
  16467. res.set_content("ok", "text/plain");
  16468. });
  16469. auto port = svr.bind_to_any_port(HOST);
  16470. thread t = thread([&]() { svr.listen_after_bind(); });
  16471. auto se = detail::scope_exit([&] {
  16472. svr.stop();
  16473. t.join();
  16474. ASSERT_FALSE(svr.is_running());
  16475. });
  16476. svr.wait_until_ready();
  16477. // Declare more trailer names than the cap in a single Trailer field, then
  16478. // actually send the first (within the cap) and the last (past it).
  16479. std::string trailer_decl = "Trailer: ";
  16480. for (int i = 0; i < declared_count; i++) {
  16481. if (i != 0) { trailer_decl += ", "; }
  16482. trailer_decl += "X-T-" + std::to_string(i);
  16483. }
  16484. trailer_decl += "\r\n";
  16485. const std::string req = "GET / HTTP/1.1\r\n"
  16486. "Transfer-Encoding: chunked\r\n" +
  16487. trailer_decl +
  16488. "\r\n"
  16489. "0\r\n" +
  16490. within_cap_name + ": a\r\n" + past_cap_name +
  16491. ": b\r\n"
  16492. "\r\n";
  16493. std::string res;
  16494. ASSERT_TRUE(send_request(1, req, &res, port));
  16495. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16496. // A name within the cap is honored; one declared past the cap is dropped.
  16497. EXPECT_TRUE(observed_within_cap);
  16498. EXPECT_FALSE(observed_past_cap);
  16499. }
  16500. // A direct client that is not listed in trusted_proxies must not be able to
  16501. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16502. // the peer address on the actual TCP connection determines whether the
  16503. // header is honored.
  16504. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16505. Server svr;
  16506. // Deliberately does NOT include the loopback address the test client
  16507. // actually connects from, so the direct connection is not a trusted proxy.
  16508. svr.set_trusted_proxies({"203.0.113.66"});
  16509. std::string observed_remote_addr;
  16510. svr.Get("/ip", [&](const Request &req, Response &res) {
  16511. observed_remote_addr = req.remote_addr;
  16512. res.set_content("ok", "text/plain");
  16513. });
  16514. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16515. auto se = detail::scope_exit([&] {
  16516. svr.stop();
  16517. t.join();
  16518. ASSERT_FALSE(svr.is_running());
  16519. });
  16520. svr.wait_until_ready();
  16521. Client cli(HOST, PORT);
  16522. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16524. EXPECT_EQ(StatusCode::OK_200, res->status);
  16525. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16526. // ignored entirely and the real connection-level address retained.
  16527. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16528. observed_remote_addr == "127.0.0.1");
  16529. }
  16530. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16531. Server svr;
  16532. std::string observed_remote_addr;
  16533. std::string observed_xff;
  16534. svr.Get("/ip", [&](const Request &req, Response &res) {
  16535. observed_remote_addr = req.remote_addr;
  16536. observed_xff = req.get_header_value("X-Forwarded-For");
  16537. res.set_content("ok", "text/plain");
  16538. });
  16539. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16540. auto se = detail::scope_exit([&] {
  16541. svr.stop();
  16542. t.join();
  16543. ASSERT_FALSE(svr.is_running());
  16544. });
  16545. svr.wait_until_ready();
  16546. Client cli(HOST, PORT);
  16547. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16549. EXPECT_EQ(StatusCode::OK_200, res->status);
  16550. EXPECT_EQ(observed_xff, "203.0.113.66");
  16551. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16552. observed_remote_addr == "127.0.0.1");
  16553. }
  16554. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16555. Server svr;
  16556. svr.set_trusted_proxies({"203.0.113.66"});
  16557. std::string observed_remote_addr;
  16558. std::string observed_xff;
  16559. svr.Get("/ip", [&](const Request &req, Response &res) {
  16560. observed_remote_addr = req.remote_addr;
  16561. observed_xff = req.get_header_value("X-Forwarded-For");
  16562. res.set_content("ok", "text/plain");
  16563. });
  16564. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16565. auto se = detail::scope_exit([&] {
  16566. svr.stop();
  16567. t.join();
  16568. ASSERT_FALSE(svr.is_running());
  16569. });
  16570. svr.wait_until_ready();
  16571. Client cli(HOST, PORT);
  16572. auto res = cli.Get("/ip");
  16573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16574. EXPECT_EQ(StatusCode::OK_200, res->status);
  16575. EXPECT_EQ(observed_xff, "");
  16576. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16577. observed_remote_addr == "127.0.0.1");
  16578. }
  16579. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16580. Server svr;
  16581. // Include the loopback address the test client actually connects from, so
  16582. // the direct connection itself is recognized as the trusted proxy hop.
  16583. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16584. std::string observed_remote_addr;
  16585. std::string observed_xff;
  16586. svr.Get("/ip", [&](const Request &req, Response &res) {
  16587. observed_remote_addr = req.remote_addr;
  16588. observed_xff = req.get_header_value("X-Forwarded-For");
  16589. res.set_content("ok", "text/plain");
  16590. });
  16591. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16592. auto se = detail::scope_exit([&] {
  16593. svr.stop();
  16594. t.join();
  16595. ASSERT_FALSE(svr.is_running());
  16596. });
  16597. svr.wait_until_ready();
  16598. Client cli(HOST, PORT);
  16599. auto res = cli.Get(
  16600. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16602. EXPECT_EQ(StatusCode::OK_200, res->status);
  16603. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16604. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16605. }
  16606. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16607. Server svr;
  16608. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16609. std::string observed_remote_addr;
  16610. std::string observed_xff;
  16611. svr.Get("/ip", [&](const Request &req, Response &res) {
  16612. observed_remote_addr = req.remote_addr;
  16613. observed_xff = req.get_header_value("X-Forwarded-For");
  16614. res.set_content("ok", "text/plain");
  16615. });
  16616. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16617. auto se = detail::scope_exit([&] {
  16618. svr.stop();
  16619. t.join();
  16620. ASSERT_FALSE(svr.is_running());
  16621. });
  16622. svr.wait_until_ready();
  16623. Client cli(HOST, PORT);
  16624. auto res = cli.Get(
  16625. "/ip",
  16626. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16628. EXPECT_EQ(StatusCode::OK_200, res->status);
  16629. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16630. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16631. }
  16632. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16633. Server svr;
  16634. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16635. std::string observed_remote_addr;
  16636. std::string observed_xff;
  16637. svr.Get("/ip", [&](const Request &req, Response &res) {
  16638. observed_remote_addr = req.remote_addr;
  16639. observed_xff = req.get_header_value("X-Forwarded-For");
  16640. res.set_content("ok", "text/plain");
  16641. });
  16642. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16643. auto se = detail::scope_exit([&] {
  16644. svr.stop();
  16645. t.join();
  16646. ASSERT_FALSE(svr.is_running());
  16647. });
  16648. svr.wait_until_ready();
  16649. Client cli(HOST, PORT);
  16650. auto res = cli.Get(
  16651. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16653. EXPECT_EQ(StatusCode::OK_200, res->status);
  16654. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16655. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16656. // and must not be selected.
  16657. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16658. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16659. }
  16660. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16661. Server svr;
  16662. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16663. std::string observed_remote_addr;
  16664. svr.Get("/ip", [&](const Request &req, Response &res) {
  16665. observed_remote_addr = req.remote_addr;
  16666. res.set_content("ok", "text/plain");
  16667. });
  16668. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16669. auto se = detail::scope_exit([&] {
  16670. svr.stop();
  16671. t.join();
  16672. ASSERT_FALSE(svr.is_running());
  16673. });
  16674. svr.wait_until_ready();
  16675. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16676. // a forged address and the trusted proxy's own address; the forged value must
  16677. // not win over the address the trusted proxy actually recorded.
  16678. Client cli(HOST, PORT);
  16679. auto res = cli.Get(
  16680. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16682. EXPECT_EQ(StatusCode::OK_200, res->status);
  16683. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16684. }
  16685. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16686. Server svr;
  16687. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16688. std::string observed_remote_addr;
  16689. std::string observed_xff;
  16690. svr.Get("/ip", [&](const Request &req, Response &res) {
  16691. observed_remote_addr = req.remote_addr;
  16692. observed_xff = req.get_header_value("X-Forwarded-For");
  16693. res.set_content("ok", "text/plain");
  16694. });
  16695. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16696. auto se = detail::scope_exit([&] {
  16697. svr.stop();
  16698. t.join();
  16699. ASSERT_FALSE(svr.is_running());
  16700. });
  16701. svr.wait_until_ready();
  16702. Client cli(HOST, PORT);
  16703. auto res = cli.Get(
  16704. "/ip",
  16705. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16707. EXPECT_EQ(StatusCode::OK_200, res->status);
  16708. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16709. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16710. }
  16711. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16712. Server svr;
  16713. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16714. std::string observed_remote_addr;
  16715. std::string observed_xff;
  16716. svr.Get("/ip", [&](const Request &req, Response &res) {
  16717. observed_remote_addr = req.remote_addr;
  16718. observed_xff = req.get_header_value("X-Forwarded-For");
  16719. res.set_content("ok", "text/plain");
  16720. });
  16721. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16722. auto se = detail::scope_exit([&] {
  16723. svr.stop();
  16724. t.join();
  16725. ASSERT_FALSE(svr.is_running());
  16726. });
  16727. svr.wait_until_ready();
  16728. std::string raw_req =
  16729. "GET /ip HTTP/1.1\r\n"
  16730. "Host: localhost\r\n"
  16731. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16732. "Connection: close\r\n"
  16733. "\r\n";
  16734. std::string out;
  16735. ASSERT_TRUE(send_request(5, raw_req, &out));
  16736. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16737. // Header parser trims surrounding whitespace of the header value
  16738. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16739. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16740. }
  16741. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16742. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16743. // their own X-Forwarded-For as a separate field line rather than extending the
  16744. // one the client sent, so every occurrence has to be taken into account.
  16745. // Reading only the first one hands back the address the client chose.
  16746. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16747. Server svr;
  16748. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16749. std::string observed_remote_addr;
  16750. size_t observed_xff_count = 0;
  16751. svr.Get("/ip", [&](const Request &req, Response &res) {
  16752. observed_remote_addr = req.remote_addr;
  16753. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16754. res.set_content("ok", "text/plain");
  16755. });
  16756. auto port = svr.bind_to_any_port(HOST);
  16757. thread t = thread([&]() { svr.listen_after_bind(); });
  16758. auto se = detail::scope_exit([&] {
  16759. svr.stop();
  16760. t.join();
  16761. ASSERT_FALSE(svr.is_running());
  16762. });
  16763. svr.wait_until_ready();
  16764. // The client supplies the first field line; the trusted proxy appends the
  16765. // address it observed as a second one.
  16766. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16767. "Host: localhost\r\n"
  16768. "X-Forwarded-For: 1.2.3.4\r\n"
  16769. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16770. "Connection: close\r\n"
  16771. "\r\n";
  16772. std::string out;
  16773. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16774. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16775. EXPECT_EQ(observed_xff_count, 2U);
  16776. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16777. // The same chain spread over one field line per hop derives the same client
  16778. // address, i.e. the split and the comma-joined representations agree.
  16779. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16780. "Host: localhost\r\n"
  16781. "X-Forwarded-For: 1.2.3.4\r\n"
  16782. "X-Forwarded-For: 198.51.100.23\r\n"
  16783. "X-Forwarded-For: 192.0.2.45\r\n"
  16784. "Connection: close\r\n"
  16785. "\r\n";
  16786. out.clear();
  16787. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16788. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16789. EXPECT_EQ(observed_xff_count, 3U);
  16790. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16791. }
  16792. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16793. // crash the server (it used to call front() on an empty vector inside
  16794. // get_client_ip). The connection-level remote address must be retained instead.
  16795. static void run_malformed_xff_test(const std::string &xff_value) {
  16796. Server svr;
  16797. svr.set_trusted_proxies({"192.0.2.45"});
  16798. std::string observed_remote_addr;
  16799. svr.Get("/ip", [&](const Request &req, Response &res) {
  16800. observed_remote_addr = req.remote_addr;
  16801. res.set_content("ok", "text/plain");
  16802. });
  16803. int port = 0;
  16804. thread t = thread([&]() {
  16805. port = svr.bind_to_any_port(HOST);
  16806. svr.listen_after_bind();
  16807. });
  16808. auto se = detail::scope_exit([&] {
  16809. svr.stop();
  16810. t.join();
  16811. ASSERT_FALSE(svr.is_running());
  16812. });
  16813. svr.wait_until_ready();
  16814. Client cli(HOST, port);
  16815. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16817. EXPECT_EQ(StatusCode::OK_200, res->status);
  16818. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16819. observed_remote_addr == "127.0.0.1");
  16820. }
  16821. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16822. run_malformed_xff_test("");
  16823. }
  16824. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16825. run_malformed_xff_test(",");
  16826. }
  16827. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16828. run_malformed_xff_test(", , ,");
  16829. }
  16830. // The same rule applies to Accept: a request whose acceptable types are spread
  16831. // over several field lines must be negotiated against all of them.
  16832. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16833. // case-insensitive connection options. Comparing the whole field value against
  16834. // one option misses a client that sends several of them, and misses every
  16835. // casing but the one written in the comparison.
  16836. //
  16837. // Sends req, reads the response, then reuses the same socket for a second
  16838. // request to find out whether the server kept the connection.
  16839. static void probe_connection_reuse(int port, const std::string &req,
  16840. bool *announced_close, bool *reusable) {
  16841. auto error = Error::Success;
  16842. auto sock = detail::create_client_socket(
  16843. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16844. /*connection_timeout_sec=*/5, 0,
  16845. /*read_timeout_sec=*/1, 0,
  16846. /*write_timeout_sec=*/5, 0, std::string(), error);
  16847. ASSERT_NE(sock, INVALID_SOCKET);
  16848. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16849. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16850. "Host: localhost\r\n"
  16851. "Connection: close\r\n"
  16852. "\r\n";
  16853. std::string first_response;
  16854. std::string second_response;
  16855. detail::process_client_socket(
  16856. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16857. [&](Stream &strm) {
  16858. if (strm.write(req.data(), req.size()) !=
  16859. static_cast<ssize_t>(req.size())) {
  16860. return false;
  16861. }
  16862. char buf[512];
  16863. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16864. // Headers plus the two-byte body of the handler below
  16865. while (reader.getline()) {
  16866. first_response += reader.ptr();
  16867. if (first_response.find("ok") != std::string::npos) { break; }
  16868. }
  16869. if (strm.write(second.data(), second.size()) !=
  16870. static_cast<ssize_t>(second.size())) {
  16871. return true;
  16872. }
  16873. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16874. while (reader2.getline()) {
  16875. second_response += reader2.ptr();
  16876. if (second_response.find("ok") != std::string::npos) { break; }
  16877. }
  16878. return true;
  16879. });
  16880. *announced_close =
  16881. first_response.find("Connection: close") != std::string::npos;
  16882. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16883. }
  16884. class ConnectionTokenTest : public ::testing::Test {
  16885. protected:
  16886. void SetUp() override {
  16887. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16888. res.set_content("ok", "text/plain");
  16889. });
  16890. port_ = svr_.bind_to_any_port(HOST);
  16891. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16892. svr_.wait_until_ready();
  16893. }
  16894. void TearDown() override {
  16895. svr_.stop();
  16896. if (thread_.joinable()) { thread_.join(); }
  16897. }
  16898. Server svr_;
  16899. int port_ = 0;
  16900. thread thread_;
  16901. };
  16902. // "close" alongside another option still closes the connection, and the
  16903. // response says so rather than leaving the peer to discover it.
  16904. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  16905. bool announced_close = false;
  16906. bool reusable = true;
  16907. probe_connection_reuse(port_,
  16908. "GET /keepalive HTTP/1.1\r\n"
  16909. "Host: localhost\r\n"
  16910. "Connection: keep-alive, close\r\n"
  16911. "\r\n",
  16912. &announced_close, &reusable);
  16913. EXPECT_TRUE(announced_close);
  16914. EXPECT_FALSE(reusable);
  16915. }
  16916. // "close" split over two field lines is the same list, so it is honored too.
  16917. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16918. bool announced_close = false;
  16919. bool reusable = true;
  16920. probe_connection_reuse(port_,
  16921. "GET /keepalive HTTP/1.1\r\n"
  16922. "Host: localhost\r\n"
  16923. "Connection: keep-alive\r\n"
  16924. "Connection: close\r\n"
  16925. "\r\n",
  16926. &announced_close, &reusable);
  16927. EXPECT_TRUE(announced_close);
  16928. EXPECT_FALSE(reusable);
  16929. }
  16930. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16931. // keep-alive in the spelling everyone actually sends keeps its connection.
  16932. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16933. bool announced_close = false;
  16934. bool reusable = false;
  16935. probe_connection_reuse(port_,
  16936. "GET /keepalive HTTP/1.0\r\n"
  16937. "Host: localhost\r\n"
  16938. "Connection: keep-alive\r\n"
  16939. "\r\n",
  16940. &announced_close, &reusable);
  16941. EXPECT_FALSE(announced_close);
  16942. EXPECT_TRUE(reusable);
  16943. }
  16944. // A token the value merely contains is not the token itself.
  16945. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16946. bool announced_close = false;
  16947. bool reusable = false;
  16948. probe_connection_reuse(port_,
  16949. "GET /keepalive HTTP/1.1\r\n"
  16950. "Host: localhost\r\n"
  16951. "Connection: notclose\r\n"
  16952. "\r\n",
  16953. &announced_close, &reusable);
  16954. EXPECT_FALSE(announced_close);
  16955. EXPECT_TRUE(reusable);
  16956. }
  16957. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16958. Server svr;
  16959. std::vector<std::string> observed_types;
  16960. svr.Get("/", [&](const Request &req, Response &res) {
  16961. observed_types = req.accept_content_types;
  16962. res.set_content("ok", "text/plain");
  16963. });
  16964. auto port = svr.bind_to_any_port(HOST);
  16965. thread t = thread([&]() { svr.listen_after_bind(); });
  16966. auto se = detail::scope_exit([&] {
  16967. svr.stop();
  16968. t.join();
  16969. ASSERT_FALSE(svr.is_running());
  16970. });
  16971. svr.wait_until_ready();
  16972. Client cli(HOST, port);
  16973. Headers headers;
  16974. headers.emplace("Accept", "text/plain;q=0.5");
  16975. headers.emplace("Accept", "application/json");
  16976. auto res = cli.Get("/", headers);
  16977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16978. EXPECT_EQ(StatusCode::OK_200, res->status);
  16979. // Sorted by q-value, so the second field line's type comes first
  16980. ASSERT_EQ(2U, observed_types.size());
  16981. EXPECT_EQ("application/json", observed_types[0]);
  16982. EXPECT_EQ("text/plain", observed_types[1]);
  16983. }
  16984. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16985. // empty field line must not contribute a bare comma to the combined value.
  16986. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16987. Server svr;
  16988. std::vector<std::string> observed_types;
  16989. svr.Get("/", [&](const Request &req, Response &res) {
  16990. observed_types = req.accept_content_types;
  16991. res.set_content("ok", "text/plain");
  16992. });
  16993. auto port = svr.bind_to_any_port(HOST);
  16994. thread t = thread([&]() { svr.listen_after_bind(); });
  16995. auto se = detail::scope_exit([&] {
  16996. svr.stop();
  16997. t.join();
  16998. ASSERT_FALSE(svr.is_running());
  16999. });
  17000. svr.wait_until_ready();
  17001. // Empty first field line, then a real one
  17002. std::string raw_req = "GET / HTTP/1.1\r\n"
  17003. "Host: localhost\r\n"
  17004. "Accept:\r\n"
  17005. "Accept: application/json\r\n"
  17006. "Connection: close\r\n"
  17007. "\r\n";
  17008. std::string out;
  17009. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17010. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17011. ASSERT_EQ(1U, observed_types.size());
  17012. EXPECT_EQ("application/json", observed_types[0]);
  17013. }
  17014. // The skip in get_combined_header_value() is what keeps an empty field line
  17015. // from contributing a bare comma. Only a trailing empty field line exercises
  17016. // it: a leading one is already covered by the "combined is still empty" check,
  17017. // and parse_accept_header() now ignores the empty element either way, so the
  17018. // request-level test above can no longer tell the two apart.
  17019. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17020. Headers headers;
  17021. headers.emplace("Accept", "text/html");
  17022. headers.emplace("Accept", "");
  17023. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17024. headers.clear();
  17025. headers.emplace("Accept", "");
  17026. headers.emplace("Accept", "application/json");
  17027. EXPECT_EQ("application/json",
  17028. detail::get_combined_header_value(headers, "Accept"));
  17029. }
  17030. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17031. // An encoding offered on a later Accept-Encoding field line is still offered.
  17032. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17033. Server svr;
  17034. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17035. res.set_content(std::string(1024, 'x'), "text/plain");
  17036. });
  17037. auto port = svr.bind_to_any_port(HOST);
  17038. thread t = thread([&]() { svr.listen_after_bind(); });
  17039. auto se = detail::scope_exit([&] {
  17040. svr.stop();
  17041. t.join();
  17042. ASSERT_FALSE(svr.is_running());
  17043. });
  17044. svr.wait_until_ready();
  17045. Client cli(HOST, port);
  17046. cli.set_decompress(false);
  17047. Headers headers;
  17048. headers.emplace("Accept-Encoding", "identity");
  17049. headers.emplace("Accept-Encoding", "gzip");
  17050. auto res = cli.Get("/", headers);
  17051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17052. EXPECT_EQ(StatusCode::OK_200, res->status);
  17053. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17054. }
  17055. #endif
  17056. #ifndef _WIN32
  17057. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17058. Server svr;
  17059. svr.Post("/post", [&](const Request &req, Response &res) {
  17060. res.set_content(req.body, "text/plain");
  17061. });
  17062. svr.Put("/put", [&](const Request &req, Response &res) {
  17063. res.set_content(req.body, "text/plain");
  17064. });
  17065. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17066. res.set_content(req.body, "text/plain");
  17067. });
  17068. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17069. res.set_content(req.body, "text/plain");
  17070. });
  17071. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17072. auto se = detail::scope_exit([&] {
  17073. svr.stop();
  17074. t.join();
  17075. ASSERT_FALSE(svr.is_running());
  17076. });
  17077. svr.wait_until_ready();
  17078. std::string resp;
  17079. // POST without Content-Length
  17080. ASSERT_TRUE(send_request(5,
  17081. "POST /post HTTP/1.1\r\n"
  17082. "Host: localhost\r\n"
  17083. "Connection: close\r\n"
  17084. "\r\n",
  17085. &resp));
  17086. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17087. // PUT without Content-Length
  17088. resp.clear();
  17089. ASSERT_TRUE(send_request(5,
  17090. "PUT /put HTTP/1.1\r\n"
  17091. "Host: localhost\r\n"
  17092. "Connection: close\r\n"
  17093. "\r\n",
  17094. &resp));
  17095. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17096. // PATCH without Content-Length
  17097. resp.clear();
  17098. ASSERT_TRUE(send_request(5,
  17099. "PATCH /patch HTTP/1.1\r\n"
  17100. "Host: localhost\r\n"
  17101. "Connection: close\r\n"
  17102. "\r\n",
  17103. &resp));
  17104. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17105. // DELETE without Content-Length
  17106. resp.clear();
  17107. ASSERT_TRUE(send_request(5,
  17108. "DELETE /delete HTTP/1.1\r\n"
  17109. "Host: localhost\r\n"
  17110. "Connection: close\r\n"
  17111. "\r\n",
  17112. &resp));
  17113. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17114. }
  17115. #endif
  17116. //==============================================================================
  17117. // open_stream() Tests
  17118. //==============================================================================
  17119. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17120. std::string result;
  17121. char buf[8192];
  17122. ssize_t n;
  17123. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17124. result.append(buf, static_cast<size_t>(n));
  17125. }
  17126. return result;
  17127. }
  17128. // Mock stream for unit tests
  17129. class MockStream : public Stream {
  17130. public:
  17131. std::string data;
  17132. size_t pos = 0;
  17133. ssize_t error_after = -1; // -1 = no error
  17134. explicit MockStream(const std::string &d, ssize_t err = -1)
  17135. : data(d), error_after(err) {}
  17136. bool is_readable() const override { return true; }
  17137. bool wait_readable() const override { return true; }
  17138. bool wait_writable() const override { return true; }
  17139. ssize_t read(char *ptr, size_t size) override {
  17140. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17141. if (pos >= data.size()) return 0;
  17142. size_t limit =
  17143. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17144. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17145. std::memcpy(ptr, data.data() + pos, to_read);
  17146. pos += to_read;
  17147. return static_cast<ssize_t>(to_read);
  17148. }
  17149. ssize_t write(const char *, size_t) override { return -1; }
  17150. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17151. ip = "127.0.0.1";
  17152. port = 0;
  17153. }
  17154. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17155. ip = "127.0.0.1";
  17156. port = 0;
  17157. }
  17158. socket_t socket() const override { return INVALID_SOCKET; }
  17159. time_t duration() const override { return 0; }
  17160. };
  17161. TEST(StreamHandleTest, Basic) {
  17162. ClientImpl::StreamHandle handle;
  17163. EXPECT_FALSE(handle.is_valid());
  17164. handle.response = detail::make_unique<Response>();
  17165. handle.error = Error::Connection;
  17166. EXPECT_FALSE(handle.is_valid());
  17167. handle.error = Error::Success;
  17168. EXPECT_TRUE(handle.is_valid());
  17169. }
  17170. TEST(BodyReaderTest, Basic) {
  17171. MockStream stream("Hello, World!");
  17172. detail::BodyReader reader;
  17173. reader.stream = &stream;
  17174. reader.content_length = 13;
  17175. char buf[32];
  17176. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17177. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17178. EXPECT_TRUE(reader.eof);
  17179. }
  17180. TEST(BodyReaderTest, NoStream) {
  17181. detail::BodyReader reader;
  17182. char buf[32];
  17183. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17184. EXPECT_EQ(Error::Connection, reader.last_error);
  17185. }
  17186. TEST(BodyReaderTest, Error) {
  17187. MockStream stream("Hello, World!", 5);
  17188. detail::BodyReader reader;
  17189. reader.stream = &stream;
  17190. reader.content_length = 13;
  17191. char buf[32];
  17192. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17193. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17194. EXPECT_EQ(Error::Read, reader.last_error);
  17195. }
  17196. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17197. // Mock-based StreamHandle tests relying on private internals are removed.
  17198. class OpenStreamTest : public ::testing::Test {
  17199. protected:
  17200. void SetUp() override {
  17201. svr_.Get("/hello", [](const Request &, Response &res) {
  17202. res.set_content("Hello World!", "text/plain");
  17203. });
  17204. svr_.Get("/large", [](const Request &, Response &res) {
  17205. res.set_content(std::string(10000, 'X'), "text/plain");
  17206. });
  17207. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17208. res.set_content("Hello World!", "image/jpeg");
  17209. res.set_header("Content-Encoding", "UTF-8");
  17210. });
  17211. svr_.Get("/chunked", [](const Request &, Response &res) {
  17212. res.set_chunked_content_provider("text/plain",
  17213. [](size_t offset, DataSink &sink) {
  17214. if (offset < 15) {
  17215. sink.write("chunk", 5);
  17216. return true;
  17217. }
  17218. sink.done();
  17219. return true;
  17220. });
  17221. });
  17222. svr_.Get("/compressible", [](const Request &, Response &res) {
  17223. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17224. DataSink &sink) {
  17225. if (offset < 100 * 1024) {
  17226. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17227. sink.write(chunk.data(), chunk.size());
  17228. return true;
  17229. }
  17230. sink.done();
  17231. return true;
  17232. });
  17233. });
  17234. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17235. [](const Request & /*req*/, Response &res) {
  17236. auto i = new int(0);
  17237. res.set_header("Trailer", "Content-Length, X-Allowed");
  17238. res.set_chunked_content_provider(
  17239. "text/plain",
  17240. [i](size_t /*offset*/, DataSink &sink) {
  17241. switch (*i) {
  17242. case 0: sink.os << "123"; break;
  17243. case 1: sink.os << "456"; break;
  17244. case 2: sink.os << "789"; break;
  17245. case 3: {
  17246. sink.done_with_trailer(
  17247. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17248. } break;
  17249. }
  17250. (*i)++;
  17251. return true;
  17252. },
  17253. [i](bool success) {
  17254. EXPECT_TRUE(success);
  17255. delete i;
  17256. });
  17257. });
  17258. // Echo headers endpoint for header-related tests
  17259. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17260. std::string body;
  17261. for (const auto &h : req.headers) {
  17262. body.append(h.first);
  17263. body.push_back(':');
  17264. body.append(h.second);
  17265. body.push_back('\n');
  17266. }
  17267. res.set_content(body, "text/plain");
  17268. });
  17269. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17270. std::string body;
  17271. for (const auto &h : req.headers) {
  17272. body.append(h.first);
  17273. body.push_back(':');
  17274. body.append(h.second);
  17275. body.push_back('\n');
  17276. }
  17277. res.set_content(body, "text/plain");
  17278. });
  17279. port_ = svr_.bind_to_any_port("127.0.0.1");
  17280. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17281. svr_.wait_until_ready();
  17282. }
  17283. void TearDown() override {
  17284. svr_.stop();
  17285. if (thread_.joinable()) thread_.join();
  17286. }
  17287. Server svr_;
  17288. std::thread thread_;
  17289. int port_ = 0;
  17290. };
  17291. TEST_F(OpenStreamTest, Basic) {
  17292. Client cli("127.0.0.1", port_);
  17293. auto handle = cli.open_stream("GET", "/hello");
  17294. EXPECT_TRUE(handle.is_valid());
  17295. EXPECT_EQ("Hello World!", read_all(handle));
  17296. }
  17297. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17298. Client cli("127.0.0.1", port_);
  17299. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17300. ASSERT_TRUE(handle.is_valid());
  17301. EXPECT_EQ("Hello World!", read_all(handle));
  17302. }
  17303. TEST_F(OpenStreamTest, SmallBuffer) {
  17304. Client cli("127.0.0.1", port_);
  17305. auto handle = cli.open_stream("GET", "/hello");
  17306. std::string result;
  17307. char buf[4];
  17308. ssize_t n;
  17309. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17310. result.append(buf, static_cast<size_t>(n));
  17311. EXPECT_EQ("Hello World!", result);
  17312. }
  17313. TEST_F(OpenStreamTest, DefaultHeaders) {
  17314. Client cli("127.0.0.1", port_);
  17315. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17316. {
  17317. auto handle = cli.open_stream("GET", "/echo-headers");
  17318. ASSERT_TRUE(handle.is_valid());
  17319. auto body = read_all(handle);
  17320. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17321. std::string::npos);
  17322. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17323. std::string::npos);
  17324. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17325. }
  17326. // open_stream POST with body and no explicit content_type should NOT add
  17327. // text/plain Content-Type (behavior differs from non-streaming path), but
  17328. // should include Content-Length
  17329. {
  17330. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17331. ASSERT_TRUE(handle.is_valid());
  17332. auto body = read_all(handle);
  17333. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17334. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17335. }
  17336. // open_stream POST with explicit Content-Type should preserve it
  17337. {
  17338. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17339. {{"Content-Type", "application/custom"}},
  17340. "{}", "application/custom");
  17341. ASSERT_TRUE(handle.is_valid());
  17342. auto body = read_all(handle);
  17343. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17344. }
  17345. // User-specified User-Agent must not be overwritten for stream API
  17346. {
  17347. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17348. {{"User-Agent", "MyAgent/1.2"}});
  17349. ASSERT_TRUE(handle.is_valid());
  17350. auto body = read_all(handle);
  17351. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17352. }
  17353. }
  17354. TEST_F(OpenStreamTest, Large) {
  17355. Client cli("127.0.0.1", port_);
  17356. auto handle = cli.open_stream("GET", "/large");
  17357. EXPECT_EQ(10000u, read_all(handle).size());
  17358. }
  17359. TEST_F(OpenStreamTest, ConnectionError) {
  17360. Client cli("127.0.0.1", 9999);
  17361. auto handle = cli.open_stream("GET", "/hello");
  17362. EXPECT_FALSE(handle.is_valid());
  17363. }
  17364. TEST_F(OpenStreamTest, Chunked) {
  17365. Client cli("127.0.0.1", port_);
  17366. auto handle = cli.open_stream("GET", "/chunked");
  17367. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17368. "Transfer-Encoding") == "chunked");
  17369. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17370. }
  17371. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17372. Client cli("127.0.0.1", port_);
  17373. auto handle =
  17374. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17375. ASSERT_TRUE(handle.is_valid());
  17376. // Consume body to allow trailers to be received/parsed
  17377. auto body = read_all(handle);
  17378. // Explicitly parse trailers (ensure trailers are available for assertion)
  17379. handle.parse_trailers_if_needed();
  17380. EXPECT_EQ(std::string("123456789"), body);
  17381. // The response should include a Trailer header declaring both names
  17382. ASSERT_TRUE(handle.response);
  17383. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17384. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17385. handle.response->get_header_value("Trailer"));
  17386. // Prohibited trailer must not be present
  17387. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17388. // Allowed trailer should be present
  17389. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17390. EXPECT_EQ(std::string("yes"),
  17391. handle.response->get_trailer_value("X-Allowed"));
  17392. // Verify trailers are NOT present as regular headers
  17393. EXPECT_EQ(std::string(""),
  17394. handle.response->get_header_value("Content-Length"));
  17395. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17396. }
  17397. static std::thread serve_single_response(std::promise<int> &port_promise,
  17398. const std::string &response) {
  17399. return std::thread([&port_promise, response] {
  17400. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17401. default_socket_options(srv);
  17402. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17403. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17404. sockaddr_in addr{};
  17405. addr.sin_family = AF_INET;
  17406. addr.sin_port = htons(0); // Let OS assign a free port
  17407. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17408. int opt = 1;
  17409. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17410. #ifdef _WIN32
  17411. reinterpret_cast<const char *>(&opt),
  17412. #else
  17413. &opt,
  17414. #endif
  17415. sizeof(opt));
  17416. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17417. ::listen(srv, 1) != 0) {
  17418. port_promise.set_value(-1);
  17419. detail::close_socket(srv);
  17420. return;
  17421. }
  17422. socklen_t addr_len = sizeof(addr);
  17423. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17424. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17425. sockaddr_in cli_addr{};
  17426. socklen_t cli_len = sizeof(cli_addr);
  17427. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17428. if (cli != INVALID_SOCKET) {
  17429. // Read the complete HTTP request (until the blank line that terminates
  17430. // headers) before sending the response. If the server closes the socket
  17431. // while the client's request data is still unread in the kernel receive
  17432. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17433. // connection on both sides: it discards the client's receive buffer
  17434. // (which already holds our response) and causes any in-progress write on
  17435. // the client to fail with ECONNRESET. Reading all request data first
  17436. // ensures close() emits a graceful FIN.
  17437. {
  17438. char rbuf[256];
  17439. std::string req;
  17440. while (req.find("\r\n\r\n") == std::string::npos) {
  17441. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17442. if (n <= 0) { break; }
  17443. req.append(rbuf, static_cast<size_t>(n));
  17444. }
  17445. }
  17446. ::send(cli,
  17447. #ifdef _WIN32
  17448. static_cast<const char *>(response.c_str()),
  17449. static_cast<int>(response.size()),
  17450. #else
  17451. response.c_str(), response.size(),
  17452. #endif
  17453. 0);
  17454. detail::close_socket(cli);
  17455. }
  17456. detail::close_socket(srv);
  17457. });
  17458. }
  17459. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17460. #ifndef _WIN32
  17461. signal(SIGPIPE, SIG_IGN);
  17462. #endif
  17463. std::promise<int> port_promise;
  17464. auto port_future = port_promise.get_future();
  17465. auto server_thread =
  17466. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17467. "Content-Type: text/plain\r\n"
  17468. "Content-Length: not-a-number\r\n"
  17469. "Connection: close\r\n"
  17470. "\r\n"
  17471. "hello");
  17472. auto port = port_future.get();
  17473. ASSERT_GT(port, 0);
  17474. Client cli("127.0.0.1", port);
  17475. auto handle = cli.open_stream("GET", "/");
  17476. EXPECT_FALSE(handle.is_valid());
  17477. server_thread.join();
  17478. }
  17479. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17480. #ifndef _WIN32
  17481. signal(SIGPIPE, SIG_IGN);
  17482. #endif
  17483. std::promise<int> port_promise;
  17484. auto port_future = port_promise.get_future();
  17485. auto server_thread = serve_single_response(
  17486. port_promise, "HTTP/1.1 200 OK\r\n"
  17487. "Content-Type: text/plain\r\n"
  17488. "Content-Length: 99999999999999999999999999\r\n"
  17489. "Connection: close\r\n"
  17490. "\r\n"
  17491. "hello");
  17492. auto port = port_future.get();
  17493. ASSERT_GT(port, 0);
  17494. // Historically std::stoull would throw std::out_of_range here and crash
  17495. // the process, then parsing silently clamped to a bogus framing length and
  17496. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17497. // so the stream fails to open, matching the not-a-number case above. The
  17498. // process still must NOT terminate.
  17499. Client cli("127.0.0.1", port);
  17500. auto handle = cli.open_stream("GET", "/");
  17501. EXPECT_FALSE(handle.is_valid());
  17502. server_thread.join();
  17503. }
  17504. // Serves `response` to the single request `fn` makes with a fresh client.
  17505. template <typename Fn>
  17506. static void with_single_response(const std::string &response, Fn fn) {
  17507. #ifndef _WIN32
  17508. signal(SIGPIPE, SIG_IGN);
  17509. #endif
  17510. std::promise<int> port_promise;
  17511. auto port_future = port_promise.get_future();
  17512. auto server_thread = serve_single_response(port_promise, response);
  17513. auto se = detail::scope_exit([&] { server_thread.join(); });
  17514. auto port = port_future.get();
  17515. ASSERT_GT(port, 0);
  17516. Client cli("127.0.0.1", port);
  17517. fn(cli);
  17518. }
  17519. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17520. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17521. // the chunked coding and drop Content-Length, so a front-end that trusts
  17522. // Content-Length would disagree about where the body ends (response
  17523. // smuggling). The client must reject such a response.
  17524. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17525. for (const char *te : {"chunked", "gzip, chunked"}) {
  17526. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17527. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17528. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17529. "5\r\nhello\r\n0\r\n\r\n";
  17530. with_single_response(response, [&](Client &cli) {
  17531. auto res = cli.Get("/");
  17532. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17533. EXPECT_EQ(Error::Read, res.error()) << te;
  17534. });
  17535. with_single_response(response, [&](Client &cli) {
  17536. auto handle = cli.open_stream("GET", "/");
  17537. EXPECT_FALSE(handle.is_valid()) << te;
  17538. EXPECT_EQ(Error::Read, handle.error) << te;
  17539. });
  17540. }
  17541. }
  17542. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17543. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17544. // closing the connection (unlike a request, which must be rejected).
  17545. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17546. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17547. "Transfer-Encoding: chunked\r\n"
  17548. "Connection: close\r\n"
  17549. "\r\n"
  17550. "5\r\nhello\r\n0\r\n\r\n",
  17551. "HTTP/1.1 200 OK\r\n"
  17552. "Transfer-Encoding: gzip\r\n"
  17553. "Connection: close\r\n"
  17554. "\r\n"
  17555. "hello"}) {
  17556. with_single_response(response, [&](Client &cli) {
  17557. auto res = cli.Get("/");
  17558. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17559. EXPECT_EQ("hello", res->body);
  17560. });
  17561. with_single_response(response, [&](Client &cli) {
  17562. auto handle = cli.open_stream("GET", "/");
  17563. ASSERT_TRUE(handle.is_valid()) << response;
  17564. EXPECT_EQ("hello", read_all(handle));
  17565. });
  17566. }
  17567. }
  17568. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17569. // framing headers describe nothing to read and must not be rejected.
  17570. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17571. const std::string framing = "Content-Length: 5\r\n"
  17572. "Transfer-Encoding: chunked\r\n"
  17573. "Connection: close\r\n"
  17574. "\r\n";
  17575. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17576. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17577. });
  17578. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17579. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17580. });
  17581. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17582. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17583. with_single_response(response, [&](Client &cli) {
  17584. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17585. });
  17586. with_single_response(response, [&](Client &cli) {
  17587. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17588. });
  17589. }
  17590. }
  17591. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17592. TEST_F(OpenStreamTest, Gzip) {
  17593. Client cli("127.0.0.1", port_);
  17594. auto handle = cli.open_stream("GET", "/compressible", {},
  17595. {{"Accept-Encoding", "gzip"}});
  17596. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17597. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17598. }
  17599. #endif
  17600. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17601. TEST_F(OpenStreamTest, Brotli) {
  17602. Client cli("127.0.0.1", port_);
  17603. auto handle =
  17604. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17605. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17606. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17607. }
  17608. #endif
  17609. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17610. TEST_F(OpenStreamTest, Zstd) {
  17611. Client cli("127.0.0.1", port_);
  17612. auto handle = cli.open_stream("GET", "/compressible", {},
  17613. {{"Accept-Encoding", "zstd"}});
  17614. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17615. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17616. }
  17617. #endif
  17618. #ifdef CPPHTTPLIB_SSL_ENABLED
  17619. class SSLOpenStreamTest : public ::testing::Test {
  17620. protected:
  17621. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17622. void SetUp() override {
  17623. svr_.Get("/hello", [](const Request &, Response &res) {
  17624. res.set_content("Hello SSL World!", "text/plain");
  17625. });
  17626. svr_.Get("/chunked", [](const Request &, Response &res) {
  17627. res.set_chunked_content_provider("text/plain",
  17628. [](size_t offset, DataSink &sink) {
  17629. if (offset < 15) {
  17630. sink.write("chunk", 5);
  17631. return true;
  17632. }
  17633. sink.done();
  17634. return true;
  17635. });
  17636. });
  17637. svr_.Post("/echo", [](const Request &req, Response &res) {
  17638. res.set_content(req.body, req.get_header_value("Content-Type"));
  17639. });
  17640. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17641. std::string body = req.body;
  17642. res.set_chunked_content_provider(
  17643. "text/plain", [body](size_t offset, DataSink &sink) {
  17644. if (offset < body.size()) {
  17645. sink.write(body.data() + offset, body.size() - offset);
  17646. }
  17647. sink.done();
  17648. return true;
  17649. });
  17650. });
  17651. port_ = svr_.bind_to_any_port("127.0.0.1");
  17652. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17653. svr_.wait_until_ready();
  17654. }
  17655. void TearDown() override {
  17656. svr_.stop();
  17657. if (thread_.joinable()) thread_.join();
  17658. }
  17659. SSLServer svr_;
  17660. std::thread thread_;
  17661. int port_ = 0;
  17662. };
  17663. TEST_F(SSLOpenStreamTest, Basic) {
  17664. SSLClient cli("127.0.0.1", port_);
  17665. cli.enable_server_certificate_verification(false);
  17666. auto handle = cli.open_stream("GET", "/hello");
  17667. ASSERT_TRUE(handle.is_valid());
  17668. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17669. }
  17670. TEST_F(SSLOpenStreamTest, Chunked) {
  17671. SSLClient cli("127.0.0.1", port_);
  17672. cli.enable_server_certificate_verification(false);
  17673. auto handle = cli.open_stream("GET", "/chunked");
  17674. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17675. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17676. "Transfer-Encoding") == "chunked");
  17677. auto body = read_all(handle);
  17678. EXPECT_EQ("chunkchunkchunk", body);
  17679. }
  17680. TEST_F(SSLOpenStreamTest, Post) {
  17681. SSLClient cli("127.0.0.1", port_);
  17682. cli.enable_server_certificate_verification(false);
  17683. auto handle =
  17684. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17685. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17686. EXPECT_EQ(200, handle.response->status);
  17687. auto body = read_all(handle);
  17688. EXPECT_EQ("Hello SSL POST", body);
  17689. }
  17690. TEST_F(SSLOpenStreamTest, PostChunked) {
  17691. SSLClient cli("127.0.0.1", port_);
  17692. cli.enable_server_certificate_verification(false);
  17693. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17694. "Chunked SSL Data", "text/plain");
  17695. ASSERT_TRUE(handle.is_valid());
  17696. EXPECT_EQ(200, handle.response->status);
  17697. auto body = read_all(handle);
  17698. EXPECT_EQ("Chunked SSL Data", body);
  17699. }
  17700. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17701. // Content-Length is terminated by the server closing the connection. When the
  17702. // SSL peer sends a close_notify after the body, the client must treat it as a
  17703. // clean EOF and return a successful response rather than an error.
  17704. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17706. ASSERT_TRUE(svr.is_valid());
  17707. svr.set_keep_alive_max_count(1);
  17708. const std::string expected_body = "Hello from connection-close response!";
  17709. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17710. res.set_content_provider("text/plain",
  17711. [&](size_t offset, DataSink &sink) -> bool {
  17712. if (offset < expected_body.size()) {
  17713. sink.write(expected_body.data() + offset,
  17714. expected_body.size() - offset);
  17715. }
  17716. sink.done();
  17717. return true;
  17718. });
  17719. });
  17720. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17721. auto se = detail::scope_exit([&] {
  17722. svr.stop();
  17723. listen_thread.join();
  17724. ASSERT_FALSE(svr.is_running());
  17725. });
  17726. svr.wait_until_ready();
  17727. SSLClient cli(HOST, PORT);
  17728. cli.enable_server_certificate_verification(false);
  17729. auto res = cli.Get("/no-content-length");
  17730. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17731. EXPECT_EQ(StatusCode::OK_200, res->status);
  17732. EXPECT_EQ(expected_body, res->body);
  17733. }
  17734. #endif // CPPHTTPLIB_SSL_ENABLED
  17735. //==============================================================================
  17736. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17737. // results for various scenarios.
  17738. //==============================================================================
  17739. TEST(ParityTest, GetVsOpenStream) {
  17740. Server svr;
  17741. const std::string path = "/parity";
  17742. const std::string content = "Parity test content: hello world";
  17743. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17744. res.set_content(content, "text/plain");
  17745. });
  17746. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17747. auto se = detail::scope_exit([&] {
  17748. svr.stop();
  17749. t.join();
  17750. ASSERT_FALSE(svr.is_running());
  17751. });
  17752. svr.wait_until_ready();
  17753. Client cli(HOST, PORT);
  17754. // Non-stream path
  17755. auto r1 = cli.Get(path);
  17756. ASSERT_TRUE(r1);
  17757. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17758. // Stream path
  17759. auto h = cli.open_stream("GET", path);
  17760. ASSERT_TRUE(h.is_valid());
  17761. EXPECT_EQ(r1->body, read_all(h));
  17762. }
  17763. // Helper to compress data with provided compressor type T
  17764. template <typename Compressor>
  17765. static std::string compress_payload_for_parity(const std::string &in) {
  17766. std::string out;
  17767. Compressor compressor;
  17768. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17769. [&](const char *data, size_t n) {
  17770. out.append(data, n);
  17771. return true;
  17772. });
  17773. EXPECT_TRUE(ok);
  17774. return out;
  17775. }
  17776. // Helper function for compression parity tests
  17777. template <typename Compressor>
  17778. static void test_compression_parity(const std::string &original,
  17779. const std::string &path,
  17780. const std::string &encoding) {
  17781. const std::string compressed =
  17782. compress_payload_for_parity<Compressor>(original);
  17783. Server svr;
  17784. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17785. res.set_content(compressed, "application/octet-stream");
  17786. res.set_header("Content-Encoding", encoding);
  17787. });
  17788. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17789. auto se = detail::scope_exit([&] {
  17790. svr.stop();
  17791. t.join();
  17792. ASSERT_FALSE(svr.is_running());
  17793. });
  17794. svr.wait_until_ready();
  17795. Client cli(HOST, PORT);
  17796. // Non-streaming
  17797. {
  17798. auto res = cli.Get(path);
  17799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17800. EXPECT_EQ(StatusCode::OK_200, res->status);
  17801. EXPECT_EQ(original, res->body);
  17802. }
  17803. // Streaming
  17804. {
  17805. auto h = cli.open_stream("GET", path);
  17806. ASSERT_TRUE(h.is_valid());
  17807. EXPECT_EQ(original, read_all(h));
  17808. }
  17809. }
  17810. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17811. TEST(ParityTest, Gzip) {
  17812. test_compression_parity<detail::gzip_compressor>(
  17813. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17814. }
  17815. #endif
  17816. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17817. TEST(ParityTest, Brotli) {
  17818. test_compression_parity<detail::brotli_compressor>(
  17819. "Hello, brotli parity test payload", "/parity-br", "br");
  17820. }
  17821. #endif
  17822. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17823. TEST(ParityTest, Zstd) {
  17824. test_compression_parity<detail::zstd_compressor>(
  17825. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17826. }
  17827. #endif
  17828. //==============================================================================
  17829. // New Stream API Tests
  17830. //==============================================================================
  17831. inline std::string read_body(httplib::stream::Result &result) {
  17832. std::string body;
  17833. while (result.next()) {
  17834. body.append(result.data(), result.size());
  17835. }
  17836. return body;
  17837. }
  17838. TEST(ClientConnectionTest, Basic) {
  17839. httplib::ClientConnection conn;
  17840. EXPECT_FALSE(conn.is_open());
  17841. conn.sock = 1;
  17842. EXPECT_TRUE(conn.is_open());
  17843. httplib::ClientConnection conn2(std::move(conn));
  17844. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17845. conn2.sock = INVALID_SOCKET;
  17846. }
  17847. // Unified test server for all stream::* tests
  17848. class StreamApiTest : public ::testing::Test {
  17849. protected:
  17850. void SetUp() override {
  17851. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17852. res.set_content("Hello World!", "text/plain");
  17853. });
  17854. svr_.Get("/echo-params",
  17855. [](const httplib::Request &req, httplib::Response &res) {
  17856. std::string r;
  17857. for (const auto &p : req.params) {
  17858. if (!r.empty()) r += "&";
  17859. r += p.first + "=" + p.second;
  17860. }
  17861. res.set_content(r, "text/plain");
  17862. });
  17863. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17864. res.set_content(req.body, req.get_header_value("Content-Type"));
  17865. });
  17866. svr_.Post("/echo-headers",
  17867. [](const httplib::Request &req, httplib::Response &res) {
  17868. std::string r;
  17869. for (const auto &h : req.headers)
  17870. r += h.first + ": " + h.second + "\n";
  17871. res.set_content(r, "text/plain");
  17872. });
  17873. svr_.Post("/echo-params",
  17874. [](const httplib::Request &req, httplib::Response &res) {
  17875. std::string r = "params:";
  17876. for (const auto &p : req.params)
  17877. r += p.first + "=" + p.second + ";";
  17878. res.set_content(r + " body:" + req.body, "text/plain");
  17879. });
  17880. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17881. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17882. });
  17883. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17884. res.set_content("PUT:" + req.body, "text/plain");
  17885. });
  17886. svr_.Patch("/echo",
  17887. [](const httplib::Request &req, httplib::Response &res) {
  17888. res.set_content("PATCH:" + req.body, "text/plain");
  17889. });
  17890. svr_.Delete(
  17891. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17892. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17893. "text/plain");
  17894. });
  17895. svr_.Get("/head-test",
  17896. [](const httplib::Request &, httplib::Response &res) {
  17897. res.set_content("body for HEAD", "text/plain");
  17898. });
  17899. svr_.Options("/options",
  17900. [](const httplib::Request &, httplib::Response &res) {
  17901. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  17902. });
  17903. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  17904. svr_.wait_until_ready();
  17905. }
  17906. void TearDown() override {
  17907. svr_.stop();
  17908. if (thread_.joinable()) thread_.join();
  17909. }
  17910. httplib::Server svr_;
  17911. std::thread thread_;
  17912. };
  17913. // stream::Get tests
  17914. TEST_F(StreamApiTest, GetBasic) {
  17915. httplib::Client cli(HOST, PORT);
  17916. auto result = httplib::stream::Get(cli, "/hello");
  17917. ASSERT_TRUE(result.is_valid());
  17918. EXPECT_EQ(200, result.status());
  17919. EXPECT_EQ("Hello World!", read_body(result));
  17920. }
  17921. TEST_F(StreamApiTest, GetWithParams) {
  17922. httplib::Client cli(HOST, PORT);
  17923. httplib::Params params{{"foo", "bar"}};
  17924. auto result = httplib::stream::Get(cli, "/echo-params", params);
  17925. ASSERT_TRUE(result.is_valid());
  17926. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  17927. }
  17928. TEST_F(StreamApiTest, GetConnectionError) {
  17929. httplib::Client cli(HOST, 9999);
  17930. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  17931. }
  17932. TEST_F(StreamApiTest, Get404) {
  17933. httplib::Client cli(HOST, PORT);
  17934. auto result = httplib::stream::Get(cli, "/nonexistent");
  17935. EXPECT_TRUE(result.is_valid());
  17936. EXPECT_EQ(404, result.status());
  17937. }
  17938. // stream::Post tests
  17939. TEST_F(StreamApiTest, PostBasic) {
  17940. httplib::Client cli(HOST, PORT);
  17941. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  17942. "application/json");
  17943. ASSERT_TRUE(result.is_valid());
  17944. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  17945. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  17946. }
  17947. TEST_F(StreamApiTest, PostWithHeaders) {
  17948. httplib::Client cli(HOST, PORT);
  17949. httplib::Headers headers{{"X-Custom", "value"}};
  17950. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  17951. "text/plain");
  17952. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  17953. }
  17954. TEST_F(StreamApiTest, PostWithParams) {
  17955. httplib::Client cli(HOST, PORT);
  17956. httplib::Params params{{"k", "v"}};
  17957. auto result =
  17958. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  17959. auto body = read_body(result);
  17960. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  17961. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  17962. }
  17963. TEST_F(StreamApiTest, PostLarge) {
  17964. httplib::Client cli(HOST, PORT);
  17965. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  17966. size_t total = 0;
  17967. while (result.next()) {
  17968. total += result.size();
  17969. }
  17970. EXPECT_EQ(100u * 1024u, total);
  17971. }
  17972. // stream::Put/Patch tests
  17973. TEST_F(StreamApiTest, PutAndPatch) {
  17974. httplib::Client cli(HOST, PORT);
  17975. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  17976. EXPECT_EQ("PUT:test", read_body(put));
  17977. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  17978. EXPECT_EQ("PATCH:test", read_body(patch));
  17979. }
  17980. // stream::Delete tests
  17981. TEST_F(StreamApiTest, Delete) {
  17982. httplib::Client cli(HOST, PORT);
  17983. auto del1 = httplib::stream::Delete(cli, "/resource");
  17984. EXPECT_EQ("Deleted", read_body(del1));
  17985. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  17986. EXPECT_EQ("Deleted:data", read_body(del2));
  17987. }
  17988. // stream::Head/Options tests
  17989. TEST_F(StreamApiTest, HeadAndOptions) {
  17990. httplib::Client cli(HOST, PORT);
  17991. auto head = httplib::stream::Head(cli, "/head-test");
  17992. EXPECT_TRUE(head.is_valid());
  17993. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  17994. auto opts = httplib::stream::Options(cli, "/options");
  17995. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  17996. }
  17997. // SSL stream::* tests
  17998. #ifdef CPPHTTPLIB_SSL_ENABLED
  17999. class SSLStreamApiTest : public ::testing::Test {
  18000. protected:
  18001. void SetUp() override {
  18002. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18003. res.set_content("Hello SSL!", "text/plain");
  18004. });
  18005. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18006. res.set_content(req.body, "text/plain");
  18007. });
  18008. port_ = svr_.bind_to_any_port("127.0.0.1");
  18009. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18010. svr_.wait_until_ready();
  18011. }
  18012. void TearDown() override {
  18013. svr_.stop();
  18014. if (thread_.joinable()) thread_.join();
  18015. }
  18016. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18017. std::thread thread_;
  18018. int port_ = 0;
  18019. };
  18020. TEST_F(SSLStreamApiTest, GetAndPost) {
  18021. httplib::SSLClient cli("127.0.0.1", port_);
  18022. cli.enable_server_certificate_verification(false);
  18023. auto get = httplib::stream::Get(cli, "/hello");
  18024. EXPECT_EQ("Hello SSL!", read_body(get));
  18025. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18026. EXPECT_EQ("test", read_body(post));
  18027. }
  18028. #endif
  18029. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18030. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18031. // BodyReader
  18032. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18033. // Test that read timeout during streaming is detected
  18034. // Use a large content-length response where server delays mid-stream
  18035. Server svr;
  18036. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18037. // Send a large response with delay in the middle
  18038. res.set_content_provider(
  18039. 1000, // content_length
  18040. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18041. if (offset < 100) {
  18042. // Send first 100 bytes immediately
  18043. std::string data(100, 'A');
  18044. sink.write(data.c_str(), data.size());
  18045. return true;
  18046. }
  18047. // Then delay longer than client timeout
  18048. std::this_thread::sleep_for(std::chrono::seconds(3));
  18049. std::string data(900, 'B');
  18050. sink.write(data.c_str(), data.size());
  18051. return true;
  18052. });
  18053. });
  18054. auto port = 8091;
  18055. std::thread t([&]() { svr.listen("localhost", port); });
  18056. svr.wait_until_ready();
  18057. Client cli("localhost", port);
  18058. cli.set_read_timeout(1, 0); // 1 second timeout
  18059. auto handle = cli.open_stream("GET", "/slow-stream");
  18060. ASSERT_TRUE(handle.is_valid());
  18061. char buf[256];
  18062. ssize_t total = 0;
  18063. ssize_t n;
  18064. bool got_error = false;
  18065. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18066. total += n;
  18067. }
  18068. if (n < 0) {
  18069. got_error = true;
  18070. // Should be timeout or read error
  18071. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18072. handle.get_read_error() == Error::Read)
  18073. << "Actual error: " << to_string(handle.get_read_error());
  18074. }
  18075. // Either we got an error, or we got less data than expected
  18076. EXPECT_TRUE(got_error || total < 1000)
  18077. << "Expected timeout but got all " << total << " bytes";
  18078. svr.stop();
  18079. t.join();
  18080. }
  18081. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18082. // Test connection closed detection via BodyReader
  18083. Server svr;
  18084. std::atomic<bool> close_now{false};
  18085. svr.Get("/will-close", [&](const Request &, Response &res) {
  18086. res.set_content_provider(
  18087. 10000, // Large content_length that we won't fully send
  18088. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18089. if (offset < 100) {
  18090. std::string data(100, 'X');
  18091. sink.write(data.c_str(), data.size());
  18092. return true;
  18093. }
  18094. // Wait for signal then abort
  18095. while (!close_now) {
  18096. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18097. }
  18098. return false; // Abort - server will close connection
  18099. });
  18100. });
  18101. auto port = 8092;
  18102. std::thread t([&]() { svr.listen("localhost", port); });
  18103. svr.wait_until_ready();
  18104. Client cli("localhost", port);
  18105. auto handle = cli.open_stream("GET", "/will-close");
  18106. ASSERT_TRUE(handle.is_valid());
  18107. char buf[256];
  18108. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18109. EXPECT_GT(n, 0) << "First read should succeed";
  18110. // Signal server to close
  18111. close_now = true;
  18112. // Keep reading until error or EOF
  18113. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18114. // Keep reading
  18115. }
  18116. // Should get an error since content_length wasn't satisfied
  18117. if (n < 0) {
  18118. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18119. handle.get_read_error() == Error::Read)
  18120. << "Actual error: " << to_string(handle.get_read_error());
  18121. }
  18122. svr.stop();
  18123. t.join();
  18124. }
  18125. #ifdef CPPHTTPLIB_SSL_ENABLED
  18126. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18127. // Test that read timeout during SSL streaming is detected
  18128. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18129. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18130. res.set_content_provider(
  18131. 1000, "text/plain",
  18132. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18133. if (offset < 100) {
  18134. std::string data(100, 'A');
  18135. sink.write(data.c_str(), data.size());
  18136. return true;
  18137. }
  18138. std::this_thread::sleep_for(std::chrono::seconds(3));
  18139. std::string data(900, 'B');
  18140. sink.write(data.c_str(), data.size());
  18141. return true;
  18142. });
  18143. });
  18144. auto port = 8093;
  18145. std::thread t([&]() { svr.listen("localhost", port); });
  18146. svr.wait_until_ready();
  18147. SSLClient cli("localhost", port);
  18148. cli.enable_server_certificate_verification(false);
  18149. cli.set_read_timeout(1, 0); // 1 second timeout
  18150. auto handle = cli.open_stream("GET", "/slow-stream");
  18151. ASSERT_TRUE(handle.is_valid());
  18152. char buf[256];
  18153. ssize_t total = 0;
  18154. ssize_t n;
  18155. bool got_error = false;
  18156. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18157. total += n;
  18158. }
  18159. if (n < 0) {
  18160. got_error = true;
  18161. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18162. handle.get_read_error() == Error::Read)
  18163. << "Actual error: " << to_string(handle.get_read_error());
  18164. }
  18165. EXPECT_TRUE(got_error || total < 1000)
  18166. << "Expected timeout but got all " << total << " bytes";
  18167. svr.stop();
  18168. t.join();
  18169. }
  18170. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18171. // Test SSL connection closed detection
  18172. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18173. std::atomic<bool> close_now{false};
  18174. svr.Get("/will-close", [&](const Request &, Response &res) {
  18175. res.set_content_provider(
  18176. 10000, "text/plain",
  18177. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18178. if (offset < 100) {
  18179. std::string data(100, 'X');
  18180. sink.write(data.c_str(), data.size());
  18181. return true;
  18182. }
  18183. while (!close_now) {
  18184. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18185. }
  18186. return false;
  18187. });
  18188. });
  18189. auto port = 8094;
  18190. std::thread t([&]() { svr.listen("localhost", port); });
  18191. svr.wait_until_ready();
  18192. SSLClient cli("localhost", port);
  18193. cli.enable_server_certificate_verification(false);
  18194. auto handle = cli.open_stream("GET", "/will-close");
  18195. ASSERT_TRUE(handle.is_valid());
  18196. char buf[256];
  18197. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18198. EXPECT_GT(n, 0);
  18199. // Signal server to close
  18200. close_now = true;
  18201. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18202. // Keep reading
  18203. }
  18204. if (n < 0) {
  18205. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18206. handle.get_read_error() == Error::Read)
  18207. << "Actual error: " << to_string(handle.get_read_error());
  18208. }
  18209. svr.stop();
  18210. t.join();
  18211. }
  18212. #endif
  18213. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18214. using namespace httplib;
  18215. // Create a test file
  18216. const char *fname = "etag_testfile.txt";
  18217. const char *content = "etag-content";
  18218. {
  18219. std::ofstream ofs(fname);
  18220. ofs << content;
  18221. ASSERT_TRUE(ofs.good());
  18222. }
  18223. Server svr;
  18224. svr.set_mount_point("/static", ".");
  18225. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18226. svr.wait_until_ready();
  18227. Client cli(HOST, PORT);
  18228. // First request: should get 200 with ETag header
  18229. auto res1 = cli.Get("/static/etag_testfile.txt");
  18230. ASSERT_TRUE(res1);
  18231. ASSERT_EQ(200, res1->status);
  18232. ASSERT_TRUE(res1->has_header("ETag"));
  18233. std::string etag = res1->get_header_value("ETag");
  18234. EXPECT_FALSE(etag.empty());
  18235. // Verify ETag format: W/"hex-hex"
  18236. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18237. EXPECT_EQ('W', etag[0]);
  18238. EXPECT_EQ('/', etag[1]);
  18239. EXPECT_EQ('"', etag[2]);
  18240. EXPECT_EQ('"', etag.back());
  18241. // Exact match: expect 304 Not Modified
  18242. Headers h2 = {{"If-None-Match", etag}};
  18243. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18244. ASSERT_TRUE(res2);
  18245. EXPECT_EQ(304, res2->status);
  18246. // Wildcard match: expect 304 Not Modified
  18247. Headers h3 = {{"If-None-Match", "*"}};
  18248. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18249. ASSERT_TRUE(res3);
  18250. EXPECT_EQ(304, res3->status);
  18251. // Non-matching ETag: expect 200
  18252. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18253. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18254. ASSERT_TRUE(res4);
  18255. EXPECT_EQ(200, res4->status);
  18256. // Multiple ETags with one matching: expect 304
  18257. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18258. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18259. ASSERT_TRUE(res5);
  18260. EXPECT_EQ(304, res5->status);
  18261. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18262. // that equivalent to the single comma-separated list above, so the match on
  18263. // the second line must still be found.
  18264. Headers h6;
  18265. h6.emplace("If-None-Match", "W/\"other\"");
  18266. h6.emplace("If-None-Match", etag);
  18267. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18268. ASSERT_TRUE(res6);
  18269. EXPECT_EQ(304, res6->status);
  18270. svr.stop();
  18271. t.join();
  18272. std::remove(fname);
  18273. }
  18274. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18275. using namespace httplib;
  18276. Server svr;
  18277. svr.set_mount_point("/static", ".");
  18278. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18279. svr.wait_until_ready();
  18280. Client cli(HOST, PORT);
  18281. // Send If-None-Match: * to a non-existent file
  18282. Headers h = {{"If-None-Match", "*"}};
  18283. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18285. EXPECT_EQ(404, res->status);
  18286. svr.stop();
  18287. t.join();
  18288. }
  18289. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18290. using namespace httplib;
  18291. // Create a test file
  18292. const char *fname = "etag_boundary_testfile.txt";
  18293. const char *content = "boundary-test";
  18294. {
  18295. std::ofstream ofs(fname);
  18296. ofs << content;
  18297. ASSERT_TRUE(ofs.good());
  18298. }
  18299. Server svr;
  18300. svr.set_mount_point("/static", ".");
  18301. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18302. svr.wait_until_ready();
  18303. Client cli(HOST, PORT);
  18304. // Get the actual ETag
  18305. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18306. ASSERT_TRUE(res1);
  18307. ASSERT_EQ(200, res1->status);
  18308. ASSERT_TRUE(res1->has_header("ETag"));
  18309. std::string etag = res1->get_header_value("ETag");
  18310. // Test 1: Very long ETag value (longer than actual ETag)
  18311. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18312. Headers h1 = {{"If-None-Match", "W/"
  18313. "\"very-long-etag-value-that-is-much-longer-"
  18314. "than-the-actual-etag-value\""}};
  18315. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18316. ASSERT_TRUE(res2);
  18317. EXPECT_EQ(200, res2->status); // Should not match
  18318. // Test 2: Long string followed by wildcard
  18319. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18320. // string)
  18321. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18322. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18323. ASSERT_TRUE(res3);
  18324. EXPECT_EQ(304, res3->status); // Should match on "*"
  18325. // Test 3: Wildcard followed by long string
  18326. // Should match on "*" immediately and return 304
  18327. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18328. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18329. ASSERT_TRUE(res4);
  18330. EXPECT_EQ(304, res4->status); // Should match on "*"
  18331. // Test 4: Multiple long non-matching values
  18332. // Should NOT match and return 200 (test that all comparisons are safe)
  18333. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18334. "W/\"second-long-non-matching-value\", "
  18335. "W/\"third-long-non-matching-value\""}};
  18336. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18337. ASSERT_TRUE(res5);
  18338. EXPECT_EQ(200, res5->status); // Should not match
  18339. // Test 5: Single character that is not "*" (edge case)
  18340. Headers h5 = {{"If-None-Match", "X"}};
  18341. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18342. ASSERT_TRUE(res6);
  18343. EXPECT_EQ(200, res6->status); // Should not match
  18344. svr.stop();
  18345. t.join();
  18346. std::remove(fname);
  18347. }
  18348. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18349. using namespace httplib;
  18350. // Create a test file
  18351. const char *fname = "ims_testfile.txt";
  18352. const char *content = "if-modified-since-test";
  18353. {
  18354. std::ofstream ofs(fname);
  18355. ofs << content;
  18356. ASSERT_TRUE(ofs.good());
  18357. }
  18358. Server svr;
  18359. svr.set_mount_point("/static", ".");
  18360. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18361. svr.wait_until_ready();
  18362. Client cli(HOST, PORT);
  18363. // First request: should get 200 with Last-Modified header
  18364. auto res1 = cli.Get("/static/ims_testfile.txt");
  18365. ASSERT_TRUE(res1);
  18366. ASSERT_EQ(200, res1->status);
  18367. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18368. std::string last_modified = res1->get_header_value("Last-Modified");
  18369. EXPECT_FALSE(last_modified.empty());
  18370. // If-Modified-Since with same time: expect 304
  18371. Headers h2 = {{"If-Modified-Since", last_modified}};
  18372. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18373. ASSERT_TRUE(res2);
  18374. EXPECT_EQ(304, res2->status);
  18375. // If-Modified-Since with future time: expect 304
  18376. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18377. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18378. ASSERT_TRUE(res3);
  18379. EXPECT_EQ(304, res3->status);
  18380. // If-Modified-Since with past time: expect 200
  18381. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18382. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18383. ASSERT_TRUE(res4);
  18384. EXPECT_EQ(200, res4->status);
  18385. // If-None-Match takes precedence over If-Modified-Since
  18386. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18387. ASSERT_TRUE(res1->has_header("ETag"));
  18388. std::string etag = res1->get_header_value("ETag");
  18389. Headers h5 = {{"If-None-Match", etag},
  18390. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18391. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18392. ASSERT_TRUE(res5);
  18393. EXPECT_EQ(304, res5->status);
  18394. svr.stop();
  18395. t.join();
  18396. std::remove(fname);
  18397. }
  18398. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18399. using namespace httplib;
  18400. Server svr;
  18401. // Endpoint that returns compressible content
  18402. svr.Get("/compressible", [](const Request &, Response &res) {
  18403. // Return a large enough body to trigger compression
  18404. std::string body(1000, 'a');
  18405. res.set_content(body, "text/plain");
  18406. });
  18407. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18408. svr.wait_until_ready();
  18409. Client cli(HOST, PORT);
  18410. // Request with gzip support: should get Vary header when compressed
  18411. cli.set_compress(true);
  18412. auto res1 = cli.Get("/compressible");
  18413. ASSERT_TRUE(res1);
  18414. EXPECT_EQ(200, res1->status);
  18415. // If Content-Encoding is set, Vary should also be set
  18416. if (res1->has_header("Content-Encoding")) {
  18417. EXPECT_TRUE(res1->has_header("Vary"));
  18418. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18419. }
  18420. // Request without Accept-Encoding header: should not have compression
  18421. Headers h_no_compress;
  18422. auto res2 = cli.Get("/compressible", h_no_compress);
  18423. ASSERT_TRUE(res2);
  18424. EXPECT_EQ(200, res2->status);
  18425. // Verify Vary header is present when compression is applied
  18426. // (the exact behavior depends on server configuration)
  18427. svr.stop();
  18428. t.join();
  18429. }
  18430. TEST(ETagTest, IfRangeWithETag) {
  18431. using namespace httplib;
  18432. // Create a test file with known content
  18433. const char *fname = "if_range_testfile.txt";
  18434. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18435. {
  18436. std::ofstream ofs(fname);
  18437. ofs << content;
  18438. ASSERT_TRUE(ofs.good());
  18439. }
  18440. Server svr;
  18441. svr.set_mount_point("/static", ".");
  18442. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18443. svr.wait_until_ready();
  18444. Client cli(HOST, PORT);
  18445. // First request: get ETag
  18446. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18447. ASSERT_TRUE(res1);
  18448. ASSERT_EQ(200, res1->status);
  18449. ASSERT_TRUE(res1->has_header("ETag"));
  18450. std::string etag = res1->get_header_value("ETag");
  18451. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18452. // Since our server generates weak ETags (W/"..."), If-Range with our
  18453. // ETag should NOT result in partial content - it should return full content.
  18454. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18455. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18456. ASSERT_TRUE(res2);
  18457. // Weak ETag in If-Range -> full content (200), not partial (206)
  18458. EXPECT_EQ(200, res2->status);
  18459. EXPECT_EQ(content, res2->body);
  18460. EXPECT_FALSE(res2->has_header("Content-Range"));
  18461. // Range request with non-matching If-Range (ETag): should get 200 (full
  18462. // content)
  18463. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18464. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18465. ASSERT_TRUE(res3);
  18466. EXPECT_EQ(200, res3->status);
  18467. EXPECT_EQ(content, res3->body);
  18468. EXPECT_FALSE(res3->has_header("Content-Range"));
  18469. // Range request with strong ETag (hypothetical - our server doesn't generate
  18470. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18471. // should return full content)
  18472. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18473. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18474. ASSERT_TRUE(res4);
  18475. EXPECT_EQ(200, res4->status);
  18476. EXPECT_EQ(content, res4->body);
  18477. EXPECT_FALSE(res4->has_header("Content-Range"));
  18478. svr.stop();
  18479. t.join();
  18480. std::remove(fname);
  18481. }
  18482. TEST(ETagTest, IfRangeWithDate) {
  18483. using namespace httplib;
  18484. // Create a test file
  18485. const char *fname = "if_range_date_testfile.txt";
  18486. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18487. {
  18488. std::ofstream ofs(fname);
  18489. ofs << content;
  18490. ASSERT_TRUE(ofs.good());
  18491. }
  18492. Server svr;
  18493. svr.set_mount_point("/static", ".");
  18494. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18495. svr.wait_until_ready();
  18496. Client cli(HOST, PORT);
  18497. // First request: get Last-Modified
  18498. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18499. ASSERT_TRUE(res1);
  18500. ASSERT_EQ(200, res1->status);
  18501. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18502. std::string last_modified = res1->get_header_value("Last-Modified");
  18503. // Range request with matching If-Range (date): should get 206
  18504. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18505. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18506. ASSERT_TRUE(res2);
  18507. EXPECT_EQ(206, res2->status);
  18508. EXPECT_EQ("FGHIJ", res2->body);
  18509. // Range request with old If-Range date: should get 200 (full content)
  18510. Headers h3 = {{"Range", "bytes=5-9"},
  18511. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18512. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18513. ASSERT_TRUE(res3);
  18514. EXPECT_EQ(200, res3->status);
  18515. EXPECT_EQ(content, res3->body);
  18516. // Range request with future If-Range date: should get 206
  18517. Headers h4 = {{"Range", "bytes=0-4"},
  18518. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18519. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18520. ASSERT_TRUE(res4);
  18521. EXPECT_EQ(206, res4->status);
  18522. EXPECT_EQ("ABCDE", res4->body);
  18523. svr.stop();
  18524. t.join();
  18525. std::remove(fname);
  18526. }
  18527. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18528. using namespace httplib;
  18529. const char *fname = "etag_malformed.txt";
  18530. const char *content = "malformed-etag";
  18531. {
  18532. std::ofstream ofs(fname);
  18533. ofs << content;
  18534. ASSERT_TRUE(ofs.good());
  18535. }
  18536. Server svr;
  18537. svr.set_mount_point("/static", ".");
  18538. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18539. svr.wait_until_ready();
  18540. Client cli(HOST, PORT);
  18541. // baseline: should get 200 and an ETag
  18542. auto res1 = cli.Get("/static/etag_malformed.txt");
  18543. ASSERT_TRUE(res1);
  18544. ASSERT_EQ(200, res1->status);
  18545. ASSERT_TRUE(res1->has_header("ETag"));
  18546. // Malformed ETag value (missing quotes) should be treated as non-matching
  18547. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18548. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18549. ASSERT_TRUE(res_bad);
  18550. EXPECT_EQ(200, res_bad->status);
  18551. // Whitespace-only header value should be considered invalid / non-matching
  18552. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18553. "Host: localhost\r\n"
  18554. "If-None-Match: \r\n"
  18555. "Connection: close\r\n"
  18556. "\r\n";
  18557. std::string out;
  18558. ASSERT_TRUE(send_request(5, raw_req, &out));
  18559. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18560. svr.stop();
  18561. t.join();
  18562. std::remove(fname);
  18563. }
  18564. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18565. using namespace httplib;
  18566. const char *fname = "ims_invalid_format.txt";
  18567. const char *content = "ims-bad-format";
  18568. {
  18569. std::ofstream ofs(fname);
  18570. ofs << content;
  18571. ASSERT_TRUE(ofs.good());
  18572. }
  18573. Server svr;
  18574. svr.set_mount_point("/static", ".");
  18575. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18576. svr.wait_until_ready();
  18577. Client cli(HOST, PORT);
  18578. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18579. ASSERT_TRUE(res1);
  18580. ASSERT_EQ(200, res1->status);
  18581. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18582. // If-Modified-Since with invalid format should not result in 304
  18583. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18584. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18585. ASSERT_TRUE(res_bad);
  18586. EXPECT_EQ(200, res_bad->status);
  18587. // If-Range with invalid date format should be treated as mismatch -> full
  18588. // content (200)
  18589. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18590. {"If-Range", "invalid-date"}};
  18591. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18592. ASSERT_TRUE(res_ifrange);
  18593. EXPECT_EQ(200, res_ifrange->status);
  18594. svr.stop();
  18595. t.join();
  18596. std::remove(fname);
  18597. }
  18598. TEST(ETagTest, IfRangeWithMalformedETag) {
  18599. using namespace httplib;
  18600. const char *fname = "ifrange_malformed.txt";
  18601. const std::string content = "0123456789";
  18602. {
  18603. std::ofstream ofs(fname);
  18604. ofs << content;
  18605. ASSERT_TRUE(ofs.good());
  18606. }
  18607. Server svr;
  18608. svr.set_mount_point("/static", ".");
  18609. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18610. svr.wait_until_ready();
  18611. Client cli(HOST, PORT);
  18612. // First request: get ETag
  18613. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18614. ASSERT_TRUE(res1);
  18615. ASSERT_EQ(200, res1->status);
  18616. ASSERT_TRUE(res1->has_header("ETag"));
  18617. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18618. // full content (200)
  18619. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18620. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18621. ASSERT_TRUE(res2);
  18622. EXPECT_EQ(200, res2->status);
  18623. EXPECT_EQ(content, res2->body);
  18624. svr.stop();
  18625. t.join();
  18626. std::remove(fname);
  18627. }
  18628. TEST(ETagTest, ExtremeLargeDateValues) {
  18629. using namespace httplib;
  18630. const char *fname = "ims_extreme_date.txt";
  18631. const char *content = "ims-extreme-date";
  18632. {
  18633. std::ofstream ofs(fname);
  18634. ofs << content;
  18635. ASSERT_TRUE(ofs.good());
  18636. }
  18637. Server svr;
  18638. svr.set_mount_point("/static", ".");
  18639. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18640. svr.wait_until_ready();
  18641. Client cli(HOST, PORT);
  18642. auto res1 = cli.Get(std::string("/static/") + fname);
  18643. ASSERT_TRUE(res1);
  18644. ASSERT_EQ(200, res1->status);
  18645. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18646. // Extremely large year that may overflow date parsing routines.
  18647. Headers h_large_date = {
  18648. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18649. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18650. ASSERT_TRUE(res_bad);
  18651. // Expect server to treat this as invalid/mismatch and return full content
  18652. EXPECT_EQ(200, res_bad->status);
  18653. // If-Range with extremely large date should be treated as mismatch -> full
  18654. // content (200)
  18655. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18656. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18657. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18658. ASSERT_TRUE(res_ifrange);
  18659. EXPECT_EQ(200, res_ifrange->status);
  18660. svr.stop();
  18661. t.join();
  18662. std::remove(fname);
  18663. }
  18664. TEST(ETagTest, NegativeFileModificationTime) {
  18665. using namespace httplib;
  18666. const char *fname = "ims_negative_mtime.txt";
  18667. const std::string content = "negative-mtime";
  18668. {
  18669. std::ofstream ofs(fname);
  18670. ofs << content;
  18671. ASSERT_TRUE(ofs.good());
  18672. }
  18673. // Try to set file mtime to a negative value. This may fail on some
  18674. // platforms/filesystems; if it fails, the test will still verify server
  18675. // behaves safely by performing a regular conditional request.
  18676. #if defined(__APPLE__) || defined(__linux__)
  18677. bool set_negative = false;
  18678. do {
  18679. struct timeval times[2];
  18680. // access time: now
  18681. times[0].tv_sec = time(nullptr);
  18682. times[0].tv_usec = 0;
  18683. // modification time: negative (e.g., -1)
  18684. times[1].tv_sec = -1;
  18685. times[1].tv_usec = 0;
  18686. if (utimes(fname, times) == 0) { set_negative = true; }
  18687. } while (0);
  18688. #else
  18689. bool set_negative = false;
  18690. #endif
  18691. Server svr;
  18692. svr.set_mount_point("/static", ".");
  18693. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18694. svr.wait_until_ready();
  18695. Client cli(HOST, PORT);
  18696. auto res1 = cli.Get(std::string("/static/") + fname);
  18697. ASSERT_TRUE(res1);
  18698. ASSERT_EQ(200, res1->status);
  18699. bool has_last_modified = res1->has_header("Last-Modified");
  18700. std::string last_modified;
  18701. if (has_last_modified) {
  18702. last_modified = res1->get_header_value("Last-Modified");
  18703. }
  18704. if (set_negative) {
  18705. // If we successfully set a negative mtime, ensure server returns a
  18706. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18707. // with an old date and ensure server handles it without crash.
  18708. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18709. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18710. ASSERT_TRUE(res2);
  18711. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18712. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18713. } else {
  18714. // Could not set negative mtime on this platform; fall back to verifying
  18715. // that normal invalid/malformed dates are treated safely (non-304).
  18716. Headers h_bad_date = {
  18717. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18718. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18719. ASSERT_TRUE(res_bad);
  18720. EXPECT_EQ(200, res_bad->status);
  18721. }
  18722. svr.stop();
  18723. t.join();
  18724. std::remove(fname);
  18725. }
  18726. //==============================================================================
  18727. // Integration Tests with Server
  18728. //==============================================================================
  18729. class SSEIntegrationTest : public ::testing::Test {
  18730. protected:
  18731. void SetUp() override {
  18732. stop_server_.store(false);
  18733. events_.clear();
  18734. server_ = httplib::detail::make_unique<Server>();
  18735. setup_server();
  18736. start_server();
  18737. }
  18738. void TearDown() override {
  18739. stop_server_.store(true);
  18740. event_cv_.notify_all();
  18741. server_->stop();
  18742. if (server_thread_.joinable()) { server_thread_.join(); }
  18743. }
  18744. void setup_server() {
  18745. // Simple SSE endpoint
  18746. server_->Get("/events", [this](const Request &req, Response &res) {
  18747. auto last_id = req.get_header_value("Last-Event-ID");
  18748. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18749. res.set_chunked_content_provider(
  18750. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18751. std::unique_lock<std::mutex> lock(event_mutex_);
  18752. if (event_cv_.wait_for(
  18753. lock, std::chrono::milliseconds(200), [this] {
  18754. return !events_.empty() || stop_server_.load();
  18755. })) {
  18756. if (stop_server_.load()) { return false; }
  18757. if (!events_.empty()) {
  18758. std::string event = events_.front();
  18759. events_.erase(events_.begin());
  18760. sink.write(event.data(), event.size());
  18761. return true;
  18762. }
  18763. }
  18764. return !stop_server_.load();
  18765. });
  18766. });
  18767. // Endpoint that returns error
  18768. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18769. res.status = 500;
  18770. res.set_content("Internal Server Error", "text/plain");
  18771. });
  18772. // Endpoint for custom event types
  18773. server_->Get("/custom-events", [](const Request &, Response &res) {
  18774. res.set_chunked_content_provider(
  18775. "text/event-stream", [](size_t offset, DataSink &sink) {
  18776. if (offset == 0) {
  18777. std::string event = "event: update\ndata: updated\n\n"
  18778. "event: delete\ndata: deleted\n\n";
  18779. sink.write(event.data(), event.size());
  18780. }
  18781. return false; // End stream after sending
  18782. });
  18783. });
  18784. }
  18785. void start_server() {
  18786. port_ = server_->bind_to_any_port(HOST);
  18787. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18788. // Wait for server to start
  18789. while (!server_->is_running()) {
  18790. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18791. }
  18792. }
  18793. int get_port() const { return port_; }
  18794. void send_event(const std::string &event) {
  18795. std::lock_guard<std::mutex> lock(event_mutex_);
  18796. events_.push_back(event);
  18797. event_cv_.notify_all();
  18798. }
  18799. std::unique_ptr<Server> server_;
  18800. std::thread server_thread_;
  18801. std::mutex event_mutex_;
  18802. std::condition_variable event_cv_;
  18803. std::vector<std::string> events_;
  18804. std::atomic<bool> stop_server_{false};
  18805. std::string last_received_event_id_;
  18806. int port_ = 0;
  18807. };
  18808. //==============================================================================
  18809. // SSE Parsing Tests
  18810. //==============================================================================
  18811. class SSEParsingTest : public SSEIntegrationTest {
  18812. protected:
  18813. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  18814. // A trailing sentinel event tells when the whole stream has been parsed.
  18815. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  18816. auto body = stream + "event: end\ndata: end\n\n";
  18817. server_->Get("/parse", [body](const Request &, Response &res) {
  18818. res.set_content(body, "text/event-stream");
  18819. });
  18820. return collect("/parse");
  18821. }
  18822. // Runs SSEClient against path until an "end" event arrives and returns the
  18823. // messages dispatched before it
  18824. std::vector<sse::SSEMessage> collect(const std::string &path) {
  18825. Client client(HOST, get_port());
  18826. sse::SSEClient sse(client, path);
  18827. std::mutex mutex;
  18828. std::condition_variable cv;
  18829. std::vector<sse::SSEMessage> messages;
  18830. auto done = false;
  18831. sse.on_message([&](const sse::SSEMessage &msg) {
  18832. std::lock_guard<std::mutex> lock(mutex);
  18833. // Ignore a replay from a reconnect that races with stop()
  18834. if (!done) { messages.push_back(msg); }
  18835. });
  18836. sse.on_event("end", [&](const sse::SSEMessage &) {
  18837. std::lock_guard<std::mutex> lock(mutex);
  18838. done = true;
  18839. cv.notify_all();
  18840. });
  18841. sse.set_reconnect_interval(100);
  18842. sse.start_async();
  18843. {
  18844. std::unique_lock<std::mutex> lock(mutex);
  18845. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  18846. }
  18847. sse.stop();
  18848. EXPECT_TRUE(done);
  18849. return messages;
  18850. }
  18851. };
  18852. TEST_F(SSEParsingTest, SingleLineData) {
  18853. auto msgs = parse("data: hello\n\n");
  18854. ASSERT_EQ(msgs.size(), 1u);
  18855. EXPECT_EQ(msgs[0].data, "hello");
  18856. EXPECT_EQ(msgs[0].event, "message");
  18857. }
  18858. TEST_F(SSEParsingTest, MultiLineData) {
  18859. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  18860. ASSERT_EQ(msgs.size(), 1u);
  18861. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  18862. }
  18863. TEST_F(SSEParsingTest, CustomEventType) {
  18864. auto msgs = parse("event: update\ndata: payload\n\n");
  18865. ASSERT_EQ(msgs.size(), 1u);
  18866. EXPECT_EQ(msgs[0].event, "update");
  18867. EXPECT_EQ(msgs[0].data, "payload");
  18868. }
  18869. TEST_F(SSEParsingTest, EventIdHandling) {
  18870. auto msgs = parse("id: 12345\ndata: test\n\n");
  18871. ASSERT_EQ(msgs.size(), 1u);
  18872. EXPECT_EQ(msgs[0].id, "12345");
  18873. }
  18874. TEST_F(SSEParsingTest, EmptyEventId) {
  18875. auto msgs = parse("id:\ndata: test\n\n");
  18876. ASSERT_EQ(msgs.size(), 1u);
  18877. EXPECT_EQ(msgs[0].id, "");
  18878. }
  18879. TEST_F(SSEParsingTest, CommentsIgnored) {
  18880. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  18881. ASSERT_EQ(msgs.size(), 1u);
  18882. EXPECT_EQ(msgs[0].data, "hello");
  18883. EXPECT_EQ(msgs[0].event, "message");
  18884. }
  18885. TEST_F(SSEParsingTest, ColonInValue) {
  18886. auto msgs = parse("data: hello:world:test\n\n");
  18887. ASSERT_EQ(msgs.size(), 1u);
  18888. EXPECT_EQ(msgs[0].data, "hello:world:test");
  18889. }
  18890. TEST_F(SSEParsingTest, FieldNameOnly) {
  18891. // A line without a colon is a field name with an empty value
  18892. auto msgs = parse("data\n\n");
  18893. ASSERT_EQ(msgs.size(), 1u);
  18894. EXPECT_EQ(msgs[0].data, "");
  18895. }
  18896. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18897. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  18898. ASSERT_EQ(msgs.size(), 1u);
  18899. EXPECT_EQ(msgs[0].event, "update");
  18900. EXPECT_EQ(msgs[0].data, "hello");
  18901. }
  18902. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  18903. auto msgs = parse("data\r\n\r\n");
  18904. ASSERT_EQ(msgs.size(), 1u);
  18905. EXPECT_EQ(msgs[0].data, "");
  18906. }
  18907. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  18908. auto msgs = parse("unknown: value\ndata: hello\n\n");
  18909. ASSERT_EQ(msgs.size(), 1u);
  18910. EXPECT_EQ(msgs[0].data, "hello");
  18911. EXPECT_EQ(msgs[0].event, "message");
  18912. }
  18913. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  18914. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  18915. ASSERT_EQ(msgs.size(), 2u);
  18916. EXPECT_EQ(msgs[0].data, "hello");
  18917. EXPECT_EQ(msgs[1].data, "hello");
  18918. }
  18919. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  18920. // An event without data is not dispatched, and its type must not leak
  18921. // into the next event
  18922. auto msgs = parse("event: update\n\ndata: hello\n\n");
  18923. ASSERT_EQ(msgs.size(), 1u);
  18924. EXPECT_EQ(msgs[0].event, "message");
  18925. EXPECT_EQ(msgs[0].data, "hello");
  18926. }
  18927. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  18928. // The first connection sends only an id; the second echoes back the
  18929. // Last-Event-ID it was reconnected with
  18930. std::atomic<int> connection_count{0};
  18931. server_->Get("/id-only", [&](const Request &req, Response &res) {
  18932. if (connection_count++ == 0) {
  18933. res.set_content("id: 42\n\n", "text/event-stream");
  18934. } else {
  18935. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  18936. "\n\nevent: end\ndata: end\n\n",
  18937. "text/event-stream");
  18938. }
  18939. });
  18940. auto msgs = collect("/id-only");
  18941. ASSERT_EQ(msgs.size(), 1u);
  18942. EXPECT_EQ(msgs[0].data, "42");
  18943. }
  18944. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  18945. // The first connection sets an id and then clears it with an empty one; the
  18946. // second reports whether it was reconnected with a Last-Event-ID
  18947. std::atomic<int> connection_count{0};
  18948. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  18949. if (connection_count++ == 0) {
  18950. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  18951. "text/event-stream");
  18952. } else {
  18953. res.set_content(
  18954. std::string("data: ") +
  18955. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  18956. "\n\nevent: end\ndata: end\n\n",
  18957. "text/event-stream");
  18958. }
  18959. });
  18960. auto msgs = collect("/id-clear");
  18961. ASSERT_EQ(msgs.size(), 3u);
  18962. EXPECT_EQ(msgs[0].id, "1");
  18963. EXPECT_EQ(msgs[1].id, "");
  18964. EXPECT_EQ(msgs[2].data, "not sent");
  18965. }
  18966. TEST_F(SSEParsingTest, CompleteEventParsing) {
  18967. auto msgs = parse("event: notification\nid: evt-42\n"
  18968. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  18969. ASSERT_EQ(msgs.size(), 1u);
  18970. EXPECT_EQ(msgs[0].event, "notification");
  18971. EXPECT_EQ(msgs[0].id, "evt-42");
  18972. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  18973. }
  18974. TEST(SSEMessageTest, Clear) {
  18975. sse::SSEMessage msg;
  18976. msg.event = "custom";
  18977. msg.data = "some data";
  18978. msg.id = "123";
  18979. msg.clear();
  18980. EXPECT_EQ(msg.event, "message");
  18981. EXPECT_EQ(msg.data, "");
  18982. EXPECT_EQ(msg.id, "");
  18983. }
  18984. //==============================================================================
  18985. // SSE Integration Tests
  18986. //==============================================================================
  18987. // Test: Successful connection and on_open callback
  18988. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  18989. // Add a simple endpoint that sends one event and closes
  18990. server_->Get("/simple-event", [](const Request &, Response &res) {
  18991. res.set_chunked_content_provider(
  18992. "text/event-stream", [](size_t offset, DataSink &sink) {
  18993. if (offset == 0) {
  18994. std::string event = "data: hello\n\n";
  18995. sink.write(event.data(), event.size());
  18996. }
  18997. return false; // Close stream after sending
  18998. });
  18999. });
  19000. Client client("localhost", get_port());
  19001. sse::SSEClient sse(client, "/simple-event");
  19002. std::atomic<bool> open_called{false};
  19003. std::atomic<bool> message_received{false};
  19004. sse.on_open([&open_called]() { open_called.store(true); });
  19005. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19006. if (msg.data == "hello") { message_received.store(true); }
  19007. });
  19008. sse.set_reconnect_interval(100);
  19009. sse.set_max_reconnect_attempts(1);
  19010. // Start async
  19011. sse.start_async();
  19012. // Wait for message to be processed
  19013. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19014. sse.stop();
  19015. EXPECT_TRUE(open_called.load());
  19016. EXPECT_TRUE(message_received.load());
  19017. }
  19018. // Test: on_message callback
  19019. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19020. // Endpoint that sends multiple events then closes
  19021. server_->Get("/multi-event", [](const Request &, Response &res) {
  19022. res.set_chunked_content_provider(
  19023. "text/event-stream", [](size_t offset, DataSink &sink) {
  19024. if (offset == 0) {
  19025. std::string events = "data: message1\n\ndata: message2\n\n";
  19026. sink.write(events.data(), events.size());
  19027. }
  19028. return false;
  19029. });
  19030. });
  19031. Client client("localhost", get_port());
  19032. sse::SSEClient sse(client, "/multi-event");
  19033. std::vector<std::string> received_messages;
  19034. std::mutex messages_mutex;
  19035. sse.on_message([&](const sse::SSEMessage &msg) {
  19036. std::lock_guard<std::mutex> lock(messages_mutex);
  19037. received_messages.push_back(msg.data);
  19038. });
  19039. sse.set_reconnect_interval(100);
  19040. sse.set_max_reconnect_attempts(1);
  19041. sse.start_async();
  19042. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19043. sse.stop();
  19044. std::lock_guard<std::mutex> lock(messages_mutex);
  19045. EXPECT_GE(received_messages.size(), 2u);
  19046. if (received_messages.size() >= 2) {
  19047. EXPECT_EQ(received_messages[0], "message1");
  19048. EXPECT_EQ(received_messages[1], "message2");
  19049. }
  19050. }
  19051. // Test: on_event for specific types
  19052. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19053. Client client("localhost", get_port());
  19054. sse::SSEClient sse(client, "/custom-events");
  19055. std::atomic<bool> update_received{false};
  19056. std::atomic<bool> delete_received{false};
  19057. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19058. if (msg.data == "updated") { update_received.store(true); }
  19059. });
  19060. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19061. if (msg.data == "deleted") { delete_received.store(true); }
  19062. });
  19063. sse.set_max_reconnect_attempts(1);
  19064. sse.start_async();
  19065. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19066. sse.stop();
  19067. EXPECT_TRUE(update_received.load());
  19068. EXPECT_TRUE(delete_received.load());
  19069. }
  19070. // Test: on_error callback on connection failure
  19071. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19072. // Connect to a non-existent port
  19073. Client client("localhost", 59999);
  19074. sse::SSEClient sse(client, "/events");
  19075. std::atomic<bool> error_called{false};
  19076. Error received_error = Error::Success;
  19077. sse.on_error([&](Error err) {
  19078. error_called.store(true);
  19079. received_error = err;
  19080. });
  19081. sse.set_reconnect_interval(50);
  19082. sse.set_max_reconnect_attempts(1);
  19083. sse.start_async();
  19084. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19085. sse.stop();
  19086. EXPECT_TRUE(error_called.load());
  19087. EXPECT_NE(received_error, Error::Success);
  19088. }
  19089. // Test: Last-Event-ID header sent on reconnect
  19090. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19091. // Endpoint that sends event with ID
  19092. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19093. res.set_chunked_content_provider(
  19094. "text/event-stream", [](size_t offset, DataSink &sink) {
  19095. if (offset == 0) {
  19096. std::string event = "id: evt-123\ndata: test\n\n";
  19097. sink.write(event.data(), event.size());
  19098. }
  19099. return false;
  19100. });
  19101. });
  19102. Client client("localhost", get_port());
  19103. sse::SSEClient sse(client, "/event-with-id");
  19104. std::atomic<bool> id_received{false};
  19105. sse.on_message([&](const sse::SSEMessage &msg) {
  19106. if (!msg.id.empty()) { id_received.store(true); }
  19107. });
  19108. sse.set_reconnect_interval(100);
  19109. sse.set_max_reconnect_attempts(1);
  19110. sse.start_async();
  19111. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19112. sse.stop();
  19113. EXPECT_TRUE(id_received.load());
  19114. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19115. }
  19116. // Test: Manual stop
  19117. TEST_F(SSEIntegrationTest, ManualStop) {
  19118. // Endpoint that sends one event and stays open briefly
  19119. std::atomic<bool> handler_running{true};
  19120. server_->Get("/stay-open", [&handler_running](const Request &,
  19121. Response &res) {
  19122. res.set_chunked_content_provider(
  19123. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19124. if (offset == 0) {
  19125. std::string event = "data: connected\n\n";
  19126. sink.write(event.data(), event.size());
  19127. }
  19128. // Keep connection open while handler_running is true
  19129. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19130. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19131. }
  19132. return false;
  19133. });
  19134. });
  19135. Client client("localhost", get_port());
  19136. sse::SSEClient sse(client, "/stay-open");
  19137. std::atomic<bool> connected{false};
  19138. sse.on_open([&connected]() { connected.store(true); });
  19139. sse.set_reconnect_interval(100);
  19140. sse.set_max_reconnect_attempts(1);
  19141. sse.start_async();
  19142. // Wait for connection to establish
  19143. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19144. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19145. }
  19146. EXPECT_TRUE(connected.load());
  19147. EXPECT_TRUE(sse.is_connected());
  19148. // Signal handler to stop
  19149. handler_running.store(false);
  19150. // Stop SSE client
  19151. sse.stop();
  19152. EXPECT_FALSE(sse.is_connected());
  19153. }
  19154. // Test: SSEClient with custom headers
  19155. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19156. // Setup a server endpoint that checks for custom header
  19157. std::atomic<bool> header_received{false};
  19158. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19159. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19160. header_received.store(true);
  19161. }
  19162. res.set_chunked_content_provider("text/event-stream",
  19163. [](size_t, DataSink &) { return false; });
  19164. });
  19165. Client client("localhost", get_port());
  19166. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19167. sse::SSEClient sse(client, "/header-check", headers);
  19168. sse.set_max_reconnect_attempts(1);
  19169. sse.start_async();
  19170. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19171. sse.stop();
  19172. EXPECT_TRUE(header_received.load());
  19173. }
  19174. // Test: Reconnect interval configuration
  19175. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19176. Client client("localhost", get_port());
  19177. sse::SSEClient sse(client, "/events");
  19178. auto &result = sse.set_reconnect_interval(500);
  19179. // Builder pattern should return reference to self
  19180. EXPECT_EQ(&result, &sse);
  19181. }
  19182. // Test: Max reconnect attempts
  19183. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19184. // Connect to non-existent port to force reconnects
  19185. Client client("localhost", 59998);
  19186. sse::SSEClient sse(client, "/events");
  19187. std::atomic<int> error_count{0};
  19188. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19189. sse.set_reconnect_interval(50);
  19190. sse.set_max_reconnect_attempts(2);
  19191. auto start = std::chrono::steady_clock::now();
  19192. sse.start(); // Blocking call
  19193. auto end = std::chrono::steady_clock::now();
  19194. // Should have stopped after 2 failed attempts
  19195. EXPECT_GE(error_count.load(), 2);
  19196. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19197. auto duration =
  19198. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19199. #ifdef _WIN32
  19200. // Windows is much slower for socket connection failures
  19201. EXPECT_LT(duration.count(), 7000);
  19202. #else
  19203. EXPECT_LT(duration.count(), 1000);
  19204. #endif
  19205. }
  19206. // Test: Multi-line data in integration
  19207. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19208. // Endpoint with multi-line data
  19209. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19210. res.set_chunked_content_provider(
  19211. "text/event-stream", [](size_t offset, DataSink &sink) {
  19212. if (offset == 0) {
  19213. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19214. sink.write(event.data(), event.size());
  19215. }
  19216. return false;
  19217. });
  19218. });
  19219. Client client("localhost", get_port());
  19220. sse::SSEClient sse(client, "/multiline-data");
  19221. std::string received_data;
  19222. std::mutex data_mutex;
  19223. sse.on_message([&](const sse::SSEMessage &msg) {
  19224. std::lock_guard<std::mutex> lock(data_mutex);
  19225. received_data = msg.data;
  19226. });
  19227. sse.set_reconnect_interval(100);
  19228. sse.set_max_reconnect_attempts(1);
  19229. sse.start_async();
  19230. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19231. sse.stop();
  19232. std::lock_guard<std::mutex> lock(data_mutex);
  19233. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19234. }
  19235. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19236. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19237. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19238. DataSink &sink) {
  19239. if (offset == 0) {
  19240. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19241. sink.write(events.data(), events.size());
  19242. }
  19243. return false;
  19244. });
  19245. });
  19246. Client client("localhost", get_port());
  19247. sse::SSEClient sse(client, "/empty-data-lines");
  19248. std::mutex mutex;
  19249. std::condition_variable cv;
  19250. std::vector<std::string> received;
  19251. sse.on_message([&](const sse::SSEMessage &msg) {
  19252. std::lock_guard<std::mutex> lock(mutex);
  19253. received.push_back(msg.data);
  19254. cv.notify_all();
  19255. });
  19256. sse.set_max_reconnect_attempts(1);
  19257. sse.start_async();
  19258. {
  19259. std::unique_lock<std::mutex> lock(mutex);
  19260. cv.wait_for(lock, std::chrono::seconds(2),
  19261. [&] { return received.size() >= 3; });
  19262. }
  19263. sse.stop();
  19264. ASSERT_GE(received.size(), 3u);
  19265. EXPECT_EQ(received[0], "");
  19266. EXPECT_EQ(received[1], "\nhello");
  19267. EXPECT_EQ(received[2], "");
  19268. }
  19269. // Test: Auto-reconnect after server disconnection
  19270. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19271. std::atomic<int> connection_count{0};
  19272. std::atomic<int> message_count{0};
  19273. // Endpoint that sends one event and closes, forcing reconnect
  19274. server_->Get("/reconnect-test",
  19275. [&connection_count](const Request &, Response &res) {
  19276. connection_count.fetch_add(1);
  19277. res.set_chunked_content_provider(
  19278. "text/event-stream", [](size_t offset, DataSink &sink) {
  19279. if (offset == 0) {
  19280. std::string event = "data: hello\n\n";
  19281. sink.write(event.data(), event.size());
  19282. }
  19283. return false; // Close connection after sending
  19284. });
  19285. });
  19286. Client client("localhost", get_port());
  19287. sse::SSEClient sse(client, "/reconnect-test");
  19288. sse.on_message([&message_count](const sse::SSEMessage &) {
  19289. message_count.fetch_add(1);
  19290. });
  19291. sse.set_reconnect_interval(100);
  19292. sse.set_max_reconnect_attempts(3);
  19293. sse.start_async();
  19294. // Wait long enough for multiple reconnects
  19295. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19296. sse.stop();
  19297. // Should have connected multiple times (initial + reconnects)
  19298. EXPECT_GE(connection_count.load(), 2);
  19299. // Should have received messages from multiple connections
  19300. EXPECT_GE(message_count.load(), 2);
  19301. }
  19302. // Test: A retry field that is not all ASCII digits is ignored
  19303. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19304. std::atomic<int> connection_count{0};
  19305. server_->Get("/bad-retry",
  19306. [&connection_count](const Request &, Response &res) {
  19307. connection_count.fetch_add(1);
  19308. res.set_chunked_content_provider(
  19309. "text/event-stream", [](size_t offset, DataSink &sink) {
  19310. if (offset == 0) {
  19311. std::string event = "retry: -1\ndata: hello\n\n";
  19312. sink.write(event.data(), event.size());
  19313. }
  19314. return false;
  19315. });
  19316. });
  19317. Client client("localhost", get_port());
  19318. sse::SSEClient sse(client, "/bad-retry");
  19319. sse.set_reconnect_interval(10000);
  19320. sse.start_async();
  19321. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19322. sse.stop();
  19323. EXPECT_EQ(connection_count.load(), 1);
  19324. }
  19325. // Test: A retry field of all ASCII digits sets the reconnection time
  19326. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19327. std::atomic<int> connection_count{0};
  19328. server_->Get("/zero-retry",
  19329. [&connection_count](const Request &, Response &res) {
  19330. connection_count.fetch_add(1);
  19331. res.set_chunked_content_provider(
  19332. "text/event-stream", [](size_t offset, DataSink &sink) {
  19333. if (offset == 0) {
  19334. std::string event = "retry: 0\ndata: hello\n\n";
  19335. sink.write(event.data(), event.size());
  19336. }
  19337. return false;
  19338. });
  19339. });
  19340. Client client("localhost", get_port());
  19341. sse::SSEClient sse(client, "/zero-retry");
  19342. sse.set_reconnect_interval(10000);
  19343. sse.start_async();
  19344. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19345. sse.stop();
  19346. // The server-supplied interval is applied, but never below 100ms, so
  19347. // "retry: 0" does not cause a busy reconnect loop
  19348. EXPECT_GE(connection_count.load(), 2);
  19349. EXPECT_LE(connection_count.load(), 10);
  19350. }
  19351. // Test: Last-Event-ID sent on reconnect
  19352. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19353. std::atomic<int> connection_count{0};
  19354. std::vector<std::string> received_last_event_ids;
  19355. std::mutex id_mutex;
  19356. // Endpoint that checks Last-Event-ID header and sends event with ID
  19357. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19358. int conn = connection_count.fetch_add(1);
  19359. // Capture the Last-Event-ID header from each connection
  19360. {
  19361. std::lock_guard<std::mutex> lock(id_mutex);
  19362. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19363. }
  19364. res.set_chunked_content_provider(
  19365. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19366. if (offset == 0) {
  19367. std::string event =
  19368. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19369. sink.write(event.data(), event.size());
  19370. }
  19371. return false;
  19372. });
  19373. });
  19374. Client client("localhost", get_port());
  19375. sse::SSEClient sse(client, "/reconnect-with-id");
  19376. sse.set_reconnect_interval(100);
  19377. sse.set_max_reconnect_attempts(3);
  19378. sse.start_async();
  19379. // Wait for at least 2 connections
  19380. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19381. sse.stop();
  19382. // Verify behavior
  19383. std::lock_guard<std::mutex> lock(id_mutex);
  19384. EXPECT_GE(received_last_event_ids.size(), 2u);
  19385. // First connection should have no Last-Event-ID
  19386. if (!received_last_event_ids.empty()) {
  19387. EXPECT_EQ(received_last_event_ids[0], "");
  19388. }
  19389. // Second connection should have Last-Event-ID from first connection
  19390. if (received_last_event_ids.size() >= 2) {
  19391. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19392. }
  19393. }
  19394. // Test: set_headers updates headers used on reconnect
  19395. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19396. std::vector<std::string> received_tokens;
  19397. std::mutex token_mutex;
  19398. // Endpoint that captures Authorization header
  19399. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19400. {
  19401. std::lock_guard<std::mutex> lock(token_mutex);
  19402. received_tokens.push_back(req.get_header_value("Authorization"));
  19403. }
  19404. res.set_chunked_content_provider(
  19405. "text/event-stream", [](size_t offset, DataSink &sink) {
  19406. if (offset == 0) {
  19407. std::string event = "data: hello\n\n";
  19408. sink.write(event.data(), event.size());
  19409. }
  19410. return false; // Close connection to trigger reconnect
  19411. });
  19412. });
  19413. Client client("localhost", get_port());
  19414. Headers headers = {{"Authorization", "Bearer old-token"}};
  19415. sse::SSEClient sse(client, "/auth-check", headers);
  19416. // Update headers on each successful connection
  19417. sse.on_open(
  19418. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19419. sse.set_reconnect_interval(100);
  19420. sse.set_max_reconnect_attempts(3);
  19421. sse.start_async();
  19422. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19423. sse.stop();
  19424. std::lock_guard<std::mutex> lock(token_mutex);
  19425. ASSERT_GE(received_tokens.size(), 2u);
  19426. // First connection uses original header
  19427. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19428. // Second connection uses updated header from set_headers
  19429. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  19430. }
  19431. // Test: 401 allows reconnection (so on_error can refresh headers)
  19432. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  19433. std::atomic<int> connection_count{0};
  19434. // Endpoint: returns 401 on first attempt, 200 on second
  19435. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  19436. int conn = connection_count.fetch_add(1);
  19437. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19438. res.status = StatusCode::Unauthorized_401;
  19439. res.set_content("Unauthorized", "text/plain");
  19440. return;
  19441. }
  19442. res.set_chunked_content_provider(
  19443. "text/event-stream", [](size_t offset, DataSink &sink) {
  19444. if (offset == 0) {
  19445. std::string event = "data: authenticated\n\n";
  19446. sink.write(event.data(), event.size());
  19447. }
  19448. return false;
  19449. });
  19450. });
  19451. Client client("localhost", get_port());
  19452. Headers headers = {{"Authorization", "Bearer expired"}};
  19453. sse::SSEClient sse(client, "/auth-retry", headers);
  19454. std::atomic<bool> message_received{false};
  19455. // Refresh token on error
  19456. sse.on_error(
  19457. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19458. sse.on_message([&](const sse::SSEMessage &msg) {
  19459. if (msg.data == "authenticated") { message_received.store(true); }
  19460. });
  19461. sse.set_reconnect_interval(100);
  19462. sse.set_max_reconnect_attempts(3);
  19463. sse.start_async();
  19464. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19465. sse.stop();
  19466. // Should have reconnected after 401 and succeeded with new token
  19467. EXPECT_GE(connection_count.load(), 2);
  19468. EXPECT_TRUE(message_received.load());
  19469. }
  19470. TEST(Issue2318Test, EmptyHostString) {
  19471. {
  19472. httplib::Client cli_empty("", PORT);
  19473. auto res = cli_empty.Get("/");
  19474. ASSERT_FALSE(res);
  19475. EXPECT_EQ(httplib::Error::Connection, res.error());
  19476. }
  19477. {
  19478. httplib::Client cli(" ", PORT);
  19479. auto res = cli.Get("/");
  19480. ASSERT_FALSE(res);
  19481. EXPECT_EQ(httplib::Error::Connection, res.error());
  19482. }
  19483. }
  19484. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19485. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19486. Server svr;
  19487. // Set a small payload limit (1KB)
  19488. svr.set_payload_max_length(1024);
  19489. svr.Post("/test", [&](const Request &req, Response &res) {
  19490. res.set_content("Body size: " + std::to_string(req.body.size()),
  19491. "text/plain");
  19492. });
  19493. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19494. auto se = detail::scope_exit([&] {
  19495. svr.stop();
  19496. listen_thread.join();
  19497. });
  19498. svr.wait_until_ready();
  19499. // Create data that compresses well but exceeds limit when decompressed
  19500. // 8KB of repeated null bytes compresses to a very small size
  19501. std::string original_data(8 * 1024, '\0');
  19502. // Compress the data using gzip
  19503. std::string compressed_data;
  19504. detail::gzip_compressor compressor;
  19505. compressor.compress(original_data.data(), original_data.size(), true,
  19506. [&](const char *data, size_t size) {
  19507. compressed_data.append(data, size);
  19508. return true;
  19509. });
  19510. // Verify compression worked (compressed should be much smaller)
  19511. ASSERT_LT(compressed_data.size(), original_data.size());
  19512. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19513. // Send compressed data with Content-Encoding: gzip
  19514. Client cli(HOST, PORT);
  19515. Headers headers = {{"Content-Encoding", "gzip"}};
  19516. auto res =
  19517. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19518. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19520. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19521. }
  19522. #endif
  19523. // ============================================================================
  19524. // OpenSSL-Specific Tests
  19525. // ============================================================================
  19526. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19527. X509 *readCertificate(const std::string &strFileName) {
  19528. std::ifstream inStream(strFileName);
  19529. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19530. std::istreambuf_iterator<char>());
  19531. if (strCertPEM.empty()) return (nullptr);
  19532. BIO *pbCert = BIO_new(BIO_s_mem());
  19533. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19534. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19535. BIO_free(pbCert);
  19536. return (pCert);
  19537. }
  19538. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19539. std::ifstream inStream(strFileName);
  19540. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19541. std::istreambuf_iterator<char>());
  19542. if (strPrivateKeyPEM.empty()) return (nullptr);
  19543. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19544. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19545. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19546. BIO_free(pbPrivKey);
  19547. return (pPrivateKey);
  19548. }
  19549. TEST(BindServerTest, UpdateCerts) {
  19550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19551. int port = svr.bind_to_any_port("0.0.0.0");
  19552. ASSERT_TRUE(svr.is_valid());
  19553. ASSERT_TRUE(port > 0);
  19554. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19555. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19556. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19557. ASSERT_TRUE(cert != nullptr);
  19558. ASSERT_TRUE(ca_cert != nullptr);
  19559. ASSERT_TRUE(key != nullptr);
  19560. X509_STORE *cert_store = X509_STORE_new();
  19561. X509_STORE_add_cert(cert_store, ca_cert);
  19562. // svr.update_certs(cert, key, cert_store); // deprecated
  19563. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19564. CLIENT_CA_CERT_FILE);
  19565. ASSERT_TRUE(svr.is_valid());
  19566. svr.stop();
  19567. X509_STORE_free(cert_store);
  19568. X509_free(cert);
  19569. X509_free(ca_cert);
  19570. EVP_PKEY_free(key);
  19571. }
  19572. // Test that update_certs() updates client CA list correctly
  19573. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19574. // Start with file-based constructor
  19575. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19576. ASSERT_TRUE(svr.is_valid());
  19577. // Initially no client CA list should be set
  19578. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19579. ASSERT_TRUE(ssl_ctx != nullptr);
  19580. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19581. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19582. EXPECT_EQ(0, count_before);
  19583. // Now update with client CA (PEM string)
  19584. std::string cert_pem, key_pem, ca_pem;
  19585. read_file(SERVER_CERT_FILE, cert_pem);
  19586. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19587. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19588. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19589. ASSERT_TRUE(svr.is_valid());
  19590. // Now client CA list should be set
  19591. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19592. ASSERT_TRUE(ca_list_after != nullptr);
  19593. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19594. }
  19595. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19596. // Test that the file-path SSLServer constructor properly sets the client CA
  19597. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19598. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19599. ASSERT_TRUE(svr.is_valid());
  19600. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19601. ASSERT_TRUE(ssl_ctx != nullptr);
  19602. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19603. ASSERT_TRUE(ca_list != nullptr);
  19604. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19605. }
  19606. #endif
  19607. // ============================================================================
  19608. // MbedTLS-Specific Tests
  19609. // ============================================================================
  19610. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19611. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19612. using namespace httplib::tls;
  19613. // Track if callback was invoked
  19614. bool callback_invoked = false;
  19615. // The callback receives void* ctx which is actually MbedTlsContext*
  19616. // We can access the mbedtls_ssl_config via the context
  19617. auto setup_callback = [&callback_invoked](void *ctx) {
  19618. callback_invoked = true;
  19619. // Cast to MbedTlsContext* to access the ssl config
  19620. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19621. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19622. // Use static variables to hold certificate data (simplified for test)
  19623. static mbedtls_x509_crt own_cert;
  19624. static mbedtls_pk_context own_key;
  19625. static mbedtls_x509_crt ca_chain;
  19626. static bool initialized = false;
  19627. if (!initialized) {
  19628. mbedtls_x509_crt_init(&own_cert);
  19629. mbedtls_pk_init(&own_key);
  19630. mbedtls_x509_crt_init(&ca_chain);
  19631. // Load server certificate
  19632. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19633. return false;
  19634. }
  19635. // Load server private key.
  19636. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19637. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19638. #if MBEDTLS_VERSION_MAJOR == 3
  19639. ,
  19640. mbedtls_ctr_drbg_random, nullptr
  19641. #endif
  19642. ) != 0) {
  19643. return false;
  19644. }
  19645. // Load CA chain for client verification
  19646. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19647. return false;
  19648. }
  19649. initialized = true;
  19650. }
  19651. // Configure the SSL config
  19652. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19653. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19654. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19655. // Set minimum TLS version using mbedTLS native API
  19656. #if MBEDTLS_VERSION_MAJOR >= 3
  19657. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19658. #else
  19659. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19660. MBEDTLS_SSL_MINOR_VERSION_3);
  19661. #endif
  19662. return true;
  19663. };
  19664. SSLServer svr(setup_callback);
  19665. ASSERT_TRUE(svr.is_valid());
  19666. ASSERT_TRUE(callback_invoked);
  19667. svr.Get("/test", [&](const Request &req, Response &res) {
  19668. res.set_content("test", "text/plain");
  19669. auto cert = req.peer_cert();
  19670. ASSERT_TRUE(static_cast<bool>(cert));
  19671. auto common_name = cert.subject_cn();
  19672. EXPECT_EQ("Common Name", common_name);
  19673. });
  19674. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19675. auto se = detail::scope_exit([&] {
  19676. svr.stop();
  19677. t.join();
  19678. ASSERT_FALSE(svr.is_running());
  19679. });
  19680. svr.wait_until_ready();
  19681. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19682. cli.enable_server_certificate_verification(false);
  19683. cli.set_connection_timeout(30);
  19684. auto res = cli.Get("/test");
  19685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19686. ASSERT_EQ(StatusCode::OK_200, res->status);
  19687. }
  19688. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19689. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19690. // keep-alive SSL session, which reads through that config in
  19691. // mbedtls_ssl_close_notify.
  19692. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19693. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19694. ASSERT_TRUE(svr.is_valid());
  19695. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19696. res.set_content("test", "text/plain");
  19697. });
  19698. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19699. auto se = detail::scope_exit([&] {
  19700. svr.stop();
  19701. t.join();
  19702. ASSERT_FALSE(svr.is_running());
  19703. });
  19704. svr.wait_until_ready();
  19705. {
  19706. SSLClient cli(HOST, PORT);
  19707. cli.enable_server_certificate_verification(false);
  19708. cli.set_keep_alive(true);
  19709. auto res = cli.Get("/test");
  19710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19711. ASSERT_EQ(StatusCode::OK_200, res->status);
  19712. // cli is destructed here with the keep-alive SSL session still open.
  19713. }
  19714. }
  19715. #endif
  19716. // WebSocket Tests
  19717. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19718. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19719. // defining the meaning of these bits has been negotiated.
  19720. auto make_frame = [](uint8_t first_byte) {
  19721. std::string frame;
  19722. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19723. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19724. frame += "Hello";
  19725. return frame;
  19726. };
  19727. // RSV1 set (0x40)
  19728. {
  19729. detail::BufferStream strm;
  19730. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19731. ws::Opcode opcode;
  19732. std::string payload;
  19733. bool fin;
  19734. EXPECT_EQ(
  19735. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19736. ws::impl::FrameRead::Fail);
  19737. }
  19738. // RSV2 set (0x20)
  19739. {
  19740. detail::BufferStream strm;
  19741. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19742. ws::Opcode opcode;
  19743. std::string payload;
  19744. bool fin;
  19745. EXPECT_EQ(
  19746. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19747. ws::impl::FrameRead::Fail);
  19748. }
  19749. // RSV3 set (0x10)
  19750. {
  19751. detail::BufferStream strm;
  19752. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19753. ws::Opcode opcode;
  19754. std::string payload;
  19755. bool fin;
  19756. EXPECT_EQ(
  19757. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19758. ws::impl::FrameRead::Fail);
  19759. }
  19760. // No RSV bits set - should succeed
  19761. {
  19762. detail::BufferStream strm;
  19763. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19764. ws::Opcode opcode;
  19765. std::string payload;
  19766. bool fin;
  19767. EXPECT_EQ(
  19768. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19769. ws::impl::FrameRead::Ok);
  19770. EXPECT_EQ(ws::Opcode::Text, opcode);
  19771. EXPECT_EQ("Hello", payload);
  19772. EXPECT_TRUE(fin);
  19773. }
  19774. }
  19775. TEST(WebSocketTest, ControlFrameValidation) {
  19776. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19777. // payload length <= 125.
  19778. // Ping with FIN=0 - must be rejected
  19779. {
  19780. detail::BufferStream strm;
  19781. std::string frame;
  19782. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19783. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19784. strm.write(frame.data(), frame.size());
  19785. ws::Opcode opcode;
  19786. std::string payload;
  19787. bool fin;
  19788. EXPECT_EQ(
  19789. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19790. ws::impl::FrameRead::Fail);
  19791. }
  19792. // Close with FIN=0 - must be rejected
  19793. {
  19794. detail::BufferStream strm;
  19795. std::string frame;
  19796. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19797. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19798. strm.write(frame.data(), frame.size());
  19799. ws::Opcode opcode;
  19800. std::string payload;
  19801. bool fin;
  19802. EXPECT_EQ(
  19803. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19804. ws::impl::FrameRead::Fail);
  19805. }
  19806. // Ping with payload_len=126 (extended length) - must be rejected
  19807. {
  19808. detail::BufferStream strm;
  19809. std::string frame;
  19810. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19811. frame += static_cast<char>(126); // payload_len=126 (>125)
  19812. frame += static_cast<char>(0x00); // extended length high byte
  19813. frame += static_cast<char>(126); // extended length low byte
  19814. frame += std::string(126, 'x');
  19815. strm.write(frame.data(), frame.size());
  19816. ws::Opcode opcode;
  19817. std::string payload;
  19818. bool fin;
  19819. EXPECT_EQ(
  19820. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19821. ws::impl::FrameRead::Fail);
  19822. }
  19823. // Ping with FIN=1 and payload_len=125 - should succeed
  19824. {
  19825. detail::BufferStream strm;
  19826. std::string frame;
  19827. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19828. frame += static_cast<char>(125); // payload_len=125
  19829. frame += std::string(125, 'x');
  19830. strm.write(frame.data(), frame.size());
  19831. ws::Opcode opcode;
  19832. std::string payload;
  19833. bool fin;
  19834. EXPECT_EQ(
  19835. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19836. ws::impl::FrameRead::Ok);
  19837. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19838. EXPECT_EQ(125u, payload.size());
  19839. EXPECT_TRUE(fin);
  19840. }
  19841. }
  19842. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19843. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19844. // length MUST be 0.
  19845. // MSB set - must be rejected
  19846. {
  19847. detail::BufferStream strm;
  19848. std::string frame;
  19849. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19850. frame += static_cast<char>(127); // 64-bit extended length
  19851. frame += static_cast<char>(0x80); // MSB set (invalid)
  19852. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19853. strm.write(frame.data(), frame.size());
  19854. ws::Opcode opcode;
  19855. std::string payload;
  19856. bool fin;
  19857. EXPECT_EQ(
  19858. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19859. ws::impl::FrameRead::Fail);
  19860. }
  19861. // MSB clear - should pass length parsing (will be rejected by max_len,
  19862. // but that's a different check; use a small length to verify)
  19863. {
  19864. detail::BufferStream strm;
  19865. std::string frame;
  19866. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19867. frame += static_cast<char>(127); // 64-bit extended length
  19868. frame += std::string(7, '\0'); // high bytes = 0
  19869. frame += static_cast<char>(0x03); // length = 3
  19870. frame += "abc";
  19871. strm.write(frame.data(), frame.size());
  19872. ws::Opcode opcode;
  19873. std::string payload;
  19874. bool fin;
  19875. EXPECT_EQ(
  19876. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19877. ws::impl::FrameRead::Ok);
  19878. EXPECT_EQ(ws::Opcode::Text, opcode);
  19879. EXPECT_EQ("abc", payload);
  19880. }
  19881. }
  19882. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19883. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19884. // Valid UTF-8
  19885. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19886. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19887. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19888. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19889. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19890. // Invalid UTF-8
  19891. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19892. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19893. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19894. EXPECT_FALSE(
  19895. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19896. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19897. }
  19898. TEST(WebSocketTest, ConnectAndDisconnect) {
  19899. Server svr;
  19900. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19901. std::string msg;
  19902. while (ws.read(msg)) {}
  19903. });
  19904. auto port = svr.bind_to_any_port(HOST);
  19905. std::thread t([&]() { svr.listen_after_bind(); });
  19906. svr.wait_until_ready();
  19907. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19908. auto res = client.connect();
  19909. ASSERT_TRUE(res);
  19910. EXPECT_EQ(Error::Success, res.error());
  19911. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  19912. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  19913. EXPECT_TRUE(client.is_open());
  19914. client.close();
  19915. EXPECT_FALSE(client.is_open());
  19916. svr.stop();
  19917. t.join();
  19918. }
  19919. TEST(WebSocketTest, ValidURL) {
  19920. ws::WebSocketClient ws1("ws://localhost:8080/path");
  19921. EXPECT_TRUE(ws1.is_valid());
  19922. ws::WebSocketClient ws2("ws://example.com/path");
  19923. EXPECT_TRUE(ws2.is_valid());
  19924. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  19925. EXPECT_TRUE(ws3.is_valid());
  19926. #ifdef CPPHTTPLIB_SSL_ENABLED
  19927. ws::WebSocketClient wss1("wss://example.com/path");
  19928. EXPECT_TRUE(wss1.is_valid());
  19929. ws::WebSocketClient wss2("wss://example.com:443/path");
  19930. EXPECT_TRUE(wss2.is_valid());
  19931. #endif
  19932. }
  19933. TEST(WebSocketTest, InvalidURL) {
  19934. // No scheme
  19935. ws::WebSocketClient ws1("localhost:8080/path");
  19936. EXPECT_FALSE(ws1.is_valid());
  19937. // No path
  19938. ws::WebSocketClient ws2("ws://localhost:8080");
  19939. EXPECT_FALSE(ws2.is_valid());
  19940. // Empty string
  19941. ws::WebSocketClient ws3("");
  19942. EXPECT_FALSE(ws3.is_valid());
  19943. // Missing host
  19944. ws::WebSocketClient ws4("ws://:8080/path");
  19945. EXPECT_FALSE(ws4.is_valid());
  19946. // Port number overflow — should not crash
  19947. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  19948. EXPECT_FALSE(ws5.is_valid());
  19949. // Port out of range
  19950. ws::WebSocketClient ws6("ws://localhost:99999/path");
  19951. EXPECT_FALSE(ws6.is_valid());
  19952. }
  19953. TEST(WebSocketTest, UnsupportedScheme) {
  19954. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  19955. ws::WebSocketClient ws1("http://localhost:8080/path");
  19956. EXPECT_FALSE(ws1.is_valid());
  19957. ws::WebSocketClient ws2("https://localhost:8080/path");
  19958. EXPECT_FALSE(ws2.is_valid());
  19959. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  19960. EXPECT_FALSE(ws3.is_valid());
  19961. #else
  19962. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  19963. std::invalid_argument);
  19964. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  19965. std::invalid_argument);
  19966. #endif
  19967. }
  19968. TEST(WebSocketTest, ConnectWhenInvalid) {
  19969. ws::WebSocketClient ws("not a valid url");
  19970. EXPECT_FALSE(ws.is_valid());
  19971. auto res = ws.connect();
  19972. EXPECT_FALSE(res);
  19973. EXPECT_EQ(Error::Connection, res.error());
  19974. EXPECT_EQ(-1, res.status());
  19975. }
  19976. TEST(WebSocketTest, ConnectRefusedReportsError) {
  19977. // Grab a port that is free, then close it again so nothing listens there
  19978. Server svr;
  19979. auto port = svr.bind_to_any_port(HOST);
  19980. svr.stop();
  19981. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19982. auto res = client.connect();
  19983. ASSERT_FALSE(res);
  19984. EXPECT_EQ(Error::Connection, res.error());
  19985. EXPECT_EQ(-1, res.status());
  19986. }
  19987. TEST(WebSocketTest, DefaultPort) {
  19988. ws::WebSocketClient ws1("ws://example.com/path");
  19989. EXPECT_TRUE(ws1.is_valid());
  19990. // ws:// defaults to port 80 (verified by successful parse)
  19991. #ifdef CPPHTTPLIB_SSL_ENABLED
  19992. ws::WebSocketClient ws2("wss://example.com/path");
  19993. EXPECT_TRUE(ws2.is_valid());
  19994. // wss:// defaults to port 443 (verified by successful parse)
  19995. #endif
  19996. }
  19997. TEST(WebSocketTest, IPv6LiteralAddress) {
  19998. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  19999. EXPECT_TRUE(ws1.is_valid());
  20000. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20001. EXPECT_TRUE(ws2.is_valid());
  20002. }
  20003. TEST(WebSocketTest, ComplexPath) {
  20004. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20005. EXPECT_TRUE(ws1.is_valid());
  20006. ws::WebSocketClient ws2("ws://localhost:8080/");
  20007. EXPECT_TRUE(ws2.is_valid());
  20008. }
  20009. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20010. Server svr;
  20011. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20012. std::string msg;
  20013. while (ws.read(msg)) {}
  20014. });
  20015. auto port = svr.bind_to_any_port(HOST);
  20016. std::thread t([&]() { svr.listen_after_bind(); });
  20017. svr.wait_until_ready();
  20018. auto another_host = "example.com";
  20019. auto wrong_ip = "192.0.2.1";
  20020. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20021. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20022. ASSERT_TRUE(client.connect());
  20023. EXPECT_TRUE(client.is_open());
  20024. client.close();
  20025. svr.stop();
  20026. t.join();
  20027. }
  20028. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20029. Server svr;
  20030. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20031. std::string msg;
  20032. while (ws.read(msg)) {}
  20033. });
  20034. auto port = svr.bind_to_any_port(HOST);
  20035. std::thread t([&]() { svr.listen_after_bind(); });
  20036. svr.wait_until_ready();
  20037. auto wrong_ip = "192.0.2.1";
  20038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20039. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20040. client.set_connection_timeout(1);
  20041. client.set_read_timeout(1);
  20042. client.set_write_timeout(1);
  20043. EXPECT_FALSE(client.connect());
  20044. EXPECT_FALSE(client.is_open());
  20045. svr.stop();
  20046. t.join();
  20047. }
  20048. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20049. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20050. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20051. // (RFC 6761) is only a map key and the Host header value.
  20052. auto host = "target.invalid";
  20053. Server svr;
  20054. std::string received_host;
  20055. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20056. received_host = req.get_header_value("Host");
  20057. std::string msg;
  20058. while (ws.read(msg)) {}
  20059. });
  20060. auto port = svr.bind_to_any_port(HOST);
  20061. std::thread t([&]() { svr.listen_after_bind(); });
  20062. // ASSERT_* below returns from the test body, which would leave t joinable
  20063. // and make ~thread call std::terminate.
  20064. auto se = detail::scope_exit([&] {
  20065. svr.stop();
  20066. if (t.joinable()) { t.join(); }
  20067. });
  20068. svr.wait_until_ready();
  20069. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20070. std::to_string(port) + "/ws");
  20071. client.set_hostname_addr_map({{host, HOST}});
  20072. ASSERT_TRUE(client.connect());
  20073. EXPECT_TRUE(client.is_open());
  20074. client.close();
  20075. svr.stop();
  20076. t.join();
  20077. // The mapping only redirects the connection; the identity stays host_.
  20078. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20079. }
  20080. class WebSocketIntegrationTest : public ::testing::Test {
  20081. protected:
  20082. void SetUp() override {
  20083. server_ = httplib::detail::make_unique<Server>();
  20084. setup_server();
  20085. start_server();
  20086. }
  20087. void TearDown() override {
  20088. server_->stop();
  20089. if (server_thread_.joinable()) { server_thread_.join(); }
  20090. }
  20091. void setup_server() {
  20092. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20093. std::string msg;
  20094. ws::ReadResult ret;
  20095. while ((ret = ws.read(msg))) {
  20096. if (ret == ws::Binary) {
  20097. ws.send(msg.data(), msg.size());
  20098. } else {
  20099. ws.send(msg);
  20100. }
  20101. }
  20102. });
  20103. server_->WebSocket("/ws-echo-string",
  20104. [](const Request &, ws::WebSocket &ws) {
  20105. std::string msg;
  20106. while (ws.read(msg)) {
  20107. ws.send("echo: " + msg);
  20108. }
  20109. });
  20110. server_->WebSocket(
  20111. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20112. // Echo back request metadata
  20113. ws.send("path:" + req.path);
  20114. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20115. std::string msg;
  20116. while (ws.read(msg)) {}
  20117. });
  20118. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20119. std::string msg;
  20120. ws.read(msg); // wait for a message
  20121. ws.close();
  20122. });
  20123. server_->WebSocket("/ws-close-status",
  20124. [](const Request &, ws::WebSocket &ws) {
  20125. std::string msg;
  20126. ws.read(msg); // wait for a message
  20127. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20128. });
  20129. server_->WebSocket(
  20130. "/ws-subprotocol",
  20131. [](const Request &, ws::WebSocket &ws) {
  20132. std::string msg;
  20133. while (ws.read(msg)) {
  20134. ws.send(msg);
  20135. }
  20136. },
  20137. [](const std::vector<std::string> &protocols) -> std::string {
  20138. for (const auto &p : protocols) {
  20139. if (p == "graphql-ws") { return p; }
  20140. }
  20141. return "";
  20142. });
  20143. }
  20144. void start_server() {
  20145. port_ = server_->bind_to_any_port(HOST);
  20146. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20147. server_->wait_until_ready();
  20148. }
  20149. std::unique_ptr<Server> server_;
  20150. std::thread server_thread_;
  20151. int port_ = 0;
  20152. };
  20153. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20154. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20155. "/ws-echo");
  20156. ASSERT_TRUE(client.connect());
  20157. ASSERT_TRUE(client.is_open());
  20158. ASSERT_TRUE(client.send("Hello WebSocket"));
  20159. std::string msg;
  20160. EXPECT_EQ(ws::Text, client.read(msg));
  20161. EXPECT_EQ("Hello WebSocket", msg);
  20162. client.close();
  20163. }
  20164. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20165. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20166. "/ws-echo");
  20167. ASSERT_TRUE(client.connect());
  20168. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20169. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20170. std::string msg;
  20171. EXPECT_EQ(ws::Binary, client.read(msg));
  20172. EXPECT_EQ(binary_data, msg);
  20173. client.close();
  20174. }
  20175. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20176. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20177. "/ws-echo");
  20178. ASSERT_TRUE(client.connect());
  20179. for (int i = 0; i < 10; i++) {
  20180. auto text = "message " + std::to_string(i);
  20181. ASSERT_TRUE(client.send(text));
  20182. std::string msg;
  20183. ASSERT_TRUE(client.read(msg));
  20184. EXPECT_EQ(text, msg);
  20185. }
  20186. client.close();
  20187. }
  20188. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20189. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20190. "/ws-close");
  20191. ASSERT_TRUE(client.connect());
  20192. // Send a message to trigger the server to close
  20193. ASSERT_TRUE(client.send("trigger close"));
  20194. // The server will close, so read should return false
  20195. std::string msg;
  20196. EXPECT_FALSE(client.read(msg));
  20197. EXPECT_FALSE(client.is_open());
  20198. }
  20199. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20200. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20201. "/ws-echo");
  20202. ASSERT_TRUE(client.connect());
  20203. // 128KB message
  20204. std::string large_data(128 * 1024, 'X');
  20205. ASSERT_TRUE(client.send(large_data));
  20206. std::string msg;
  20207. ASSERT_TRUE(client.read(msg));
  20208. EXPECT_EQ(large_data, msg);
  20209. client.close();
  20210. }
  20211. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20212. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20213. "/ws-echo");
  20214. ASSERT_TRUE(client.connect());
  20215. const int num_threads = 4;
  20216. std::vector<std::thread> threads;
  20217. std::atomic<int> send_count{0};
  20218. for (int t = 0; t < num_threads; t++) {
  20219. threads.emplace_back([&client, &send_count, t]() {
  20220. for (int i = 0; i < 5; i++) {
  20221. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20222. if (client.send(text)) { send_count++; }
  20223. }
  20224. });
  20225. }
  20226. for (auto &th : threads) {
  20227. th.join();
  20228. }
  20229. int received = 0;
  20230. std::string msg;
  20231. while (received < send_count.load()) {
  20232. if (!client.read(msg)) { break; }
  20233. received++;
  20234. }
  20235. EXPECT_EQ(send_count.load(), received);
  20236. client.close();
  20237. }
  20238. TEST_F(WebSocketIntegrationTest, ReadString) {
  20239. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20240. "/ws-echo-string");
  20241. ASSERT_TRUE(client.connect());
  20242. ASSERT_TRUE(client.send("hello"));
  20243. std::string msg;
  20244. ASSERT_TRUE(client.read(msg));
  20245. EXPECT_EQ("echo: hello", msg);
  20246. ASSERT_TRUE(client.send("world"));
  20247. ASSERT_TRUE(client.read(msg));
  20248. EXPECT_EQ("echo: world", msg);
  20249. client.close();
  20250. }
  20251. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20252. Headers headers = {{"X-Test-Header", "test-value"}};
  20253. ws::WebSocketClient client(
  20254. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20255. ASSERT_TRUE(client.connect());
  20256. std::string msg;
  20257. ASSERT_TRUE(client.read(msg));
  20258. EXPECT_EQ("path:/ws-request-info", msg);
  20259. ASSERT_TRUE(client.read(msg));
  20260. EXPECT_EQ("header:test-value", msg);
  20261. client.close();
  20262. }
  20263. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20264. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20265. "/ws-echo");
  20266. client.set_read_timeout(1, 0); // 1 second
  20267. ASSERT_TRUE(client.connect());
  20268. // Don't send anything — server echo handler waits for a message, so read()
  20269. // should time out. The connection survives it: nothing was consumed.
  20270. std::string msg;
  20271. EXPECT_EQ(client.read(msg), ws::Timeout);
  20272. EXPECT_TRUE(client.is_open());
  20273. // And it is still usable afterwards.
  20274. EXPECT_TRUE(client.send("after timeout"));
  20275. EXPECT_EQ(client.read(msg), ws::Text);
  20276. EXPECT_EQ(msg, "after timeout");
  20277. }
  20278. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20279. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20280. "/ws-echo");
  20281. client.set_read_timeout(1, 0);
  20282. ASSERT_TRUE(client.connect());
  20283. ASSERT_TRUE(client.send("first"));
  20284. std::string msg;
  20285. ASSERT_EQ(client.read(msg), ws::Text);
  20286. ASSERT_EQ(msg, "first");
  20287. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20288. // not be used with a read timeout: it would reprocess the previous message.
  20289. EXPECT_EQ(client.read(msg), ws::Timeout);
  20290. EXPECT_EQ(msg, "first");
  20291. }
  20292. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20293. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20294. "/ws-echo");
  20295. ASSERT_TRUE(client.connect());
  20296. // Setting it once the connection is open reaches the live stream, not just
  20297. // the seed for the next connect().
  20298. client.set_read_timeout(1, 0);
  20299. std::string msg;
  20300. EXPECT_EQ(client.read(msg), ws::Timeout);
  20301. EXPECT_TRUE(client.is_open());
  20302. }
  20303. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20304. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20305. "/ws-echo");
  20306. client.set_read_timeout(5, 0);
  20307. ASSERT_TRUE(client.connect());
  20308. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20309. // The server should reject it and close the connection.
  20310. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20311. client.send(oversized);
  20312. // The server's read() should have failed due to payload limit,
  20313. // so our read() should return false (connection closed).
  20314. std::string msg;
  20315. EXPECT_FALSE(client.read(msg));
  20316. }
  20317. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20318. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20319. "/ws-echo");
  20320. client.set_read_timeout(10, 0);
  20321. ASSERT_TRUE(client.connect());
  20322. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20323. // This should succeed.
  20324. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20325. ASSERT_TRUE(client.send(at_limit));
  20326. std::string msg;
  20327. ASSERT_TRUE(client.read(msg));
  20328. EXPECT_EQ(at_limit.size(), msg.size());
  20329. client.close();
  20330. }
  20331. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20332. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20333. "/nonexistent");
  20334. auto res = client.connect();
  20335. EXPECT_FALSE(res);
  20336. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20337. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20338. EXPECT_FALSE(client.is_open());
  20339. }
  20340. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20341. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20342. "/ws-echo");
  20343. ASSERT_TRUE(client.connect());
  20344. ASSERT_TRUE(client.send(""));
  20345. std::string msg;
  20346. EXPECT_EQ(ws::Text, client.read(msg));
  20347. EXPECT_EQ("", msg);
  20348. client.close();
  20349. }
  20350. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20351. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20352. "/ws-echo");
  20353. // First connection
  20354. ASSERT_TRUE(client.connect());
  20355. ASSERT_TRUE(client.send("first"));
  20356. std::string msg;
  20357. ASSERT_TRUE(client.read(msg));
  20358. EXPECT_EQ("first", msg);
  20359. client.close();
  20360. EXPECT_FALSE(client.is_open());
  20361. // Reconnect using the same client object
  20362. ASSERT_TRUE(client.connect());
  20363. ASSERT_TRUE(client.is_open());
  20364. ASSERT_TRUE(client.send("second"));
  20365. ASSERT_TRUE(client.read(msg));
  20366. EXPECT_EQ("second", msg);
  20367. client.close();
  20368. }
  20369. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20370. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20371. "/ws-close-status");
  20372. ASSERT_TRUE(client.connect());
  20373. // Trigger the server to close with GoingAway status
  20374. ASSERT_TRUE(client.send("trigger"));
  20375. // read() should return false after receiving the close frame
  20376. std::string msg;
  20377. EXPECT_FALSE(client.read(msg));
  20378. EXPECT_FALSE(client.is_open());
  20379. }
  20380. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20381. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20382. "/ws-echo");
  20383. ASSERT_TRUE(client.connect());
  20384. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20385. EXPECT_FALSE(client.is_open());
  20386. }
  20387. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20388. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20389. ws::WebSocketClient client(
  20390. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20391. ASSERT_TRUE(client.connect());
  20392. // Server should have selected graphql-ws
  20393. EXPECT_EQ("graphql-ws", client.subprotocol());
  20394. client.close();
  20395. }
  20396. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  20397. Headers headers;
  20398. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  20399. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  20400. ws::WebSocketClient client(
  20401. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20402. ASSERT_TRUE(client.connect());
  20403. // The offer on the second field line counts too, so graphql-ws is selected
  20404. EXPECT_EQ("graphql-ws", client.subprotocol());
  20405. client.close();
  20406. }
  20407. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  20408. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20409. ws::WebSocketClient client(
  20410. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20411. ASSERT_TRUE(client.connect());
  20412. // Server should not have selected any subprotocol
  20413. EXPECT_TRUE(client.subprotocol().empty());
  20414. client.close();
  20415. }
  20416. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  20417. // Connect without requesting any subprotocol
  20418. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20419. "/ws-subprotocol");
  20420. ASSERT_TRUE(client.connect());
  20421. EXPECT_TRUE(client.subprotocol().empty());
  20422. client.close();
  20423. }
  20424. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  20425. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20426. "/ws-echo");
  20427. client.set_tcp_nodelay(true);
  20428. client.set_connection_timeout(3, 0);
  20429. bool socket_options_called = false;
  20430. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  20431. ASSERT_TRUE(client.connect());
  20432. ASSERT_TRUE(client.is_open());
  20433. EXPECT_TRUE(socket_options_called);
  20434. ASSERT_TRUE(client.send("hello"));
  20435. std::string msg;
  20436. auto result = client.read(msg);
  20437. EXPECT_EQ(result, ws::ReadResult::Text);
  20438. EXPECT_EQ(msg, "hello");
  20439. client.close();
  20440. }
  20441. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20442. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20443. "/ws-echo");
  20444. client.set_connection_timeout(std::chrono::seconds(3));
  20445. client.set_write_timeout(std::chrono::seconds(3));
  20446. // A sub-second remainder exercises the seconds/microseconds split.
  20447. client.set_read_timeout(std::chrono::milliseconds(1500));
  20448. ASSERT_TRUE(client.connect());
  20449. auto start = std::chrono::steady_clock::now();
  20450. std::string msg;
  20451. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20452. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20453. std::chrono::steady_clock::now() - start)
  20454. .count();
  20455. // Above 1s so that dropping the microseconds half of the split fails here.
  20456. // Ignoring the setter altogether would not reach this line at all: a client
  20457. // waits forever by default.
  20458. EXPECT_GE(elapsed, 1400);
  20459. EXPECT_LT(elapsed, 30000);
  20460. }
  20461. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20462. Server svr;
  20463. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20464. if (!req.has_header("Authorization")) {
  20465. res.status = StatusCode::Unauthorized_401;
  20466. res.set_content("Unauthorized", "text/plain");
  20467. return Server::HandlerResponse::Handled;
  20468. }
  20469. return Server::HandlerResponse::Unhandled;
  20470. });
  20471. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20472. std::string msg;
  20473. while (ws.read(msg)) {
  20474. ws.send(msg);
  20475. }
  20476. });
  20477. auto port = svr.bind_to_any_port("localhost");
  20478. std::thread t([&]() { svr.listen_after_bind(); });
  20479. svr.wait_until_ready();
  20480. // Without Authorization header - should be rejected before upgrade
  20481. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20482. EXPECT_FALSE(client1.connect());
  20483. // The rejection is framed like any other HTTP response
  20484. {
  20485. Client cli("localhost", port);
  20486. Headers headers = {{"Upgrade", "websocket"},
  20487. {"Connection", "Upgrade"},
  20488. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20489. {"Sec-WebSocket-Version", "13"}};
  20490. auto res = cli.Get("/ws", headers);
  20491. ASSERT_TRUE(res);
  20492. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20493. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20494. EXPECT_EQ("Unauthorized", res->body);
  20495. }
  20496. // With Authorization header - should succeed
  20497. Headers headers = {{"Authorization", "Bearer token123"}};
  20498. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20499. headers);
  20500. ASSERT_TRUE(client2.connect());
  20501. ASSERT_TRUE(client2.send("hello"));
  20502. std::string msg;
  20503. ASSERT_TRUE(client2.read(msg));
  20504. EXPECT_EQ("hello", msg);
  20505. client2.close();
  20506. svr.stop();
  20507. t.join();
  20508. }
  20509. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20510. Server svr;
  20511. std::atomic<int> pre_request_calls{0};
  20512. std::atomic<bool> route_matched{false};
  20513. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20514. pre_request_calls++;
  20515. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20516. if (req.get_header_value("Authorization") != "Bearer token123") {
  20517. res.status = StatusCode::Unauthorized_401;
  20518. res.set_content("Unauthorized", "text/plain");
  20519. return Server::HandlerResponse::Handled;
  20520. }
  20521. return Server::HandlerResponse::Unhandled;
  20522. });
  20523. std::atomic<bool> handler_called{false};
  20524. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20525. handler_called = true;
  20526. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20527. });
  20528. auto port = svr.bind_to_any_port("localhost");
  20529. std::thread t([&]() { svr.listen_after_bind(); });
  20530. svr.wait_until_ready();
  20531. // Without Authorization header - should be rejected before upgrade
  20532. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20533. "/ws/1");
  20534. EXPECT_FALSE(client1.connect());
  20535. EXPECT_FALSE(handler_called);
  20536. EXPECT_EQ(1, pre_request_calls);
  20537. EXPECT_TRUE(route_matched);
  20538. // The rejection is an ordinary HTTP response, not a protocol switch
  20539. {
  20540. Client cli("localhost", port);
  20541. Headers headers = {{"Upgrade", "websocket"},
  20542. {"Connection", "Upgrade"},
  20543. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20544. {"Sec-WebSocket-Version", "13"}};
  20545. auto res = cli.Get("/ws/1", headers);
  20546. ASSERT_TRUE(res);
  20547. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20548. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20549. EXPECT_EQ("Unauthorized", res->body);
  20550. }
  20551. EXPECT_FALSE(handler_called);
  20552. // With Authorization header - should succeed
  20553. Headers headers = {{"Authorization", "Bearer token123"}};
  20554. ws::WebSocketClient client2(
  20555. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20556. ASSERT_TRUE(client2.connect());
  20557. std::string msg;
  20558. ASSERT_TRUE(client2.read(msg));
  20559. EXPECT_EQ("/ws/:id 2", msg);
  20560. EXPECT_TRUE(handler_called);
  20561. client2.close();
  20562. svr.stop();
  20563. t.join();
  20564. }
  20565. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20566. Server svr;
  20567. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20568. // A read timeout is how a handler gets control back. Without it, a handler
  20569. // parked in read() can never write on the connection it is reading.
  20570. ws.set_read_timeout(std::chrono::milliseconds(100));
  20571. std::string msg;
  20572. while (ws.is_open()) {
  20573. auto r = ws.read(msg);
  20574. if (r == httplib::ws::Timeout) {
  20575. ws.send("tick");
  20576. continue;
  20577. }
  20578. if (r == httplib::ws::Fail) { break; }
  20579. ws.send(msg);
  20580. }
  20581. });
  20582. auto port = svr.bind_to_any_port("localhost");
  20583. std::thread t([&]() { svr.listen_after_bind(); });
  20584. svr.wait_until_ready();
  20585. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20586. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20587. ASSERT_TRUE(client.connect());
  20588. // The client sends nothing, so anything it receives came out of the
  20589. // handler's timeout path.
  20590. std::string msg;
  20591. ASSERT_EQ(client.read(msg), ws::Text);
  20592. EXPECT_EQ("tick", msg);
  20593. client.close();
  20594. svr.stop();
  20595. t.join();
  20596. }
  20597. // Stream::read may return fewer bytes than asked for. This is that contract at
  20598. // its worst -- one byte per call -- which is what a frame header straddling a
  20599. // read buffer's boundary looks like to the frame parser.
  20600. class WsByteAtATimeStream : public Stream {
  20601. public:
  20602. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20603. bool is_readable() const override { return true; }
  20604. bool wait_readable() const override { return true; }
  20605. bool wait_writable() const override { return true; }
  20606. ssize_t read(char *ptr, size_t size) override {
  20607. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20608. *ptr = data_[pos_++];
  20609. return 1;
  20610. }
  20611. ssize_t write(const char *, size_t size) override {
  20612. return static_cast<ssize_t>(size);
  20613. }
  20614. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20615. ip = "127.0.0.1";
  20616. port = 0;
  20617. }
  20618. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20619. ip = "127.0.0.1";
  20620. port = 0;
  20621. }
  20622. socket_t socket() const override { return INVALID_SOCKET; }
  20623. time_t duration() const override { return 0; }
  20624. private:
  20625. std::string data_;
  20626. size_t pos_ = 0;
  20627. };
  20628. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20629. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20630. // length and the mask key are all multi-byte fields here. Each used to be
  20631. // read with a single read() call, which fails as soon as one is split.
  20632. std::string body(200, 'x');
  20633. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20634. std::string frame;
  20635. frame += static_cast<char>(0x81); // FIN + Text
  20636. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20637. frame += static_cast<char>(body.size() >> 8);
  20638. frame += static_cast<char>(body.size() & 0xff);
  20639. for (size_t i = 0; i < 4; i++) {
  20640. frame += static_cast<char>(mask[i]);
  20641. }
  20642. for (size_t i = 0; i < body.size(); i++) {
  20643. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20644. }
  20645. WsByteAtATimeStream strm(frame);
  20646. ws::Opcode opcode;
  20647. std::string payload;
  20648. bool fin = false;
  20649. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20650. /*expect_masked=*/true, 1024),
  20651. ws::impl::FrameRead::Ok);
  20652. EXPECT_TRUE(fin);
  20653. EXPECT_EQ(opcode, ws::Opcode::Text);
  20654. EXPECT_EQ(payload, body);
  20655. }
  20656. TEST(WebSocketTest, QueryStringInHandshake) {
  20657. Server svr;
  20658. std::mutex mtx;
  20659. std::string received_target;
  20660. std::string received_token;
  20661. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20662. {
  20663. std::lock_guard<std::mutex> lock(mtx);
  20664. received_target = req.target;
  20665. if (req.has_param("token")) {
  20666. received_token = req.get_param_value("token");
  20667. }
  20668. }
  20669. std::string msg;
  20670. while (ws.read(msg)) {
  20671. ws.send(msg);
  20672. }
  20673. });
  20674. auto port = svr.bind_to_any_port("localhost");
  20675. std::thread t([&]() { svr.listen_after_bind(); });
  20676. svr.wait_until_ready();
  20677. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20678. "/ws?token=ABC&session=123");
  20679. ASSERT_TRUE(client.connect());
  20680. // Round-trip ensures the handler has run and captured the request.
  20681. ASSERT_TRUE(client.send("hello"));
  20682. std::string msg;
  20683. ASSERT_TRUE(client.read(msg));
  20684. EXPECT_EQ("hello", msg);
  20685. client.close();
  20686. {
  20687. std::lock_guard<std::mutex> lock(mtx);
  20688. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20689. EXPECT_EQ("ABC", received_token);
  20690. }
  20691. svr.stop();
  20692. t.join();
  20693. }
  20694. // Run a handshake against a throwaway server and hand the request the server
  20695. // received back to the caller, so tests can assert on the headers the client
  20696. // actually put on the wire.
  20697. static void capture_websocket_handshake_request(
  20698. const Headers &client_headers,
  20699. std::function<void(const Request &, int port)> verify) {
  20700. Server svr;
  20701. std::mutex mtx;
  20702. Request received;
  20703. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20704. {
  20705. std::lock_guard<std::mutex> lock(mtx);
  20706. received = req;
  20707. }
  20708. std::string msg;
  20709. while (ws.read(msg)) {
  20710. ws.send(msg);
  20711. }
  20712. });
  20713. auto port = svr.bind_to_any_port("localhost");
  20714. std::thread t([&]() { svr.listen_after_bind(); });
  20715. auto se = detail::scope_exit([&] {
  20716. svr.stop();
  20717. t.join();
  20718. });
  20719. svr.wait_until_ready();
  20720. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20721. client_headers);
  20722. ASSERT_TRUE(client.connect());
  20723. ASSERT_TRUE(client.send("hello"));
  20724. std::string msg;
  20725. ASSERT_TRUE(client.read(msg));
  20726. client.close();
  20727. {
  20728. std::lock_guard<std::mutex> lock(mtx);
  20729. verify(received, port);
  20730. }
  20731. }
  20732. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20733. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20734. // Non-default port must be present in the Host header. Default ports
  20735. // (80/443) are omitted; that logic is covered by
  20736. // MakeHostAndPortStringTest.
  20737. EXPECT_EQ("localhost:" + std::to_string(port),
  20738. req.get_header_value("Host"));
  20739. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20740. req.get_header_value("User-Agent"));
  20741. EXPECT_FALSE(req.has_header("Accept"));
  20742. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20743. EXPECT_FALSE(req.has_header("Content-Length"));
  20744. });
  20745. }
  20746. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20747. capture_websocket_handshake_request(
  20748. {{"Host", "example.com"},
  20749. {"User-Agent", "custom-agent"},
  20750. {"X-Custom", "value"}},
  20751. [](const Request &req, int) {
  20752. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20753. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20754. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20755. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20756. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20757. });
  20758. }
  20759. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20760. capture_websocket_handshake_request(
  20761. {{"Upgrade", "bogus"},
  20762. {"Connection", "close"},
  20763. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20764. {"Sec-WebSocket-Version", "8"}},
  20765. [](const Request &req, int) {
  20766. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20767. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20768. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20769. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20770. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20771. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20772. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20773. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20774. req.get_header_value("Sec-WebSocket-Key"));
  20775. });
  20776. }
  20777. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20778. // A header the client refuses to send must abort the handshake before any
  20779. // part of it reaches the wire; a lone request line would otherwise sit in
  20780. // the peer's buffer as a truncated request.
  20781. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20782. ASSERT_NE(INVALID_SOCKET, srv);
  20783. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20784. sockaddr_in addr{};
  20785. addr.sin_family = AF_INET;
  20786. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20787. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20788. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20789. ASSERT_EQ(0, ::listen(srv, 1));
  20790. sockaddr_in bound{};
  20791. socklen_t bound_len = sizeof(bound);
  20792. ASSERT_EQ(
  20793. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20794. auto port = ntohs(bound.sin_port);
  20795. ssize_t received = -1;
  20796. std::thread t([&] {
  20797. // Bound every blocking call so a regression fails the test with a bad
  20798. // value instead of hanging the suite.
  20799. fd_set rfds;
  20800. FD_ZERO(&rfds);
  20801. FD_SET(srv, &rfds);
  20802. timeval tv{5, 0};
  20803. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20804. 0) {
  20805. return;
  20806. }
  20807. sockaddr_in cli_addr{};
  20808. socklen_t cli_len = sizeof(cli_addr);
  20809. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20810. if (cli == INVALID_SOCKET) { return; }
  20811. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20812. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20813. char buf[4096];
  20814. received = ::recv(cli, buf, sizeof(buf), 0);
  20815. });
  20816. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20817. // connect() has already shut the socket down by the time it returns false,
  20818. // so the peer sees EOF without waiting for the client to be destroyed.
  20819. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20820. {{"X-Bad", "a\r\nInjected: 1"}});
  20821. EXPECT_FALSE(client.connect());
  20822. t.join();
  20823. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20824. EXPECT_EQ(0, received);
  20825. }
  20826. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20827. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20828. // contains "upgrade" as a substring is a different token and must not
  20829. // start a WebSocket handshake.
  20830. auto make_request = [](const std::vector<std::string> &connection_values) {
  20831. Request req;
  20832. req.method = "GET";
  20833. req.headers.emplace("Upgrade", "websocket");
  20834. for (const auto &value : connection_values) {
  20835. req.headers.emplace("Connection", value);
  20836. }
  20837. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20838. req.headers.emplace("Sec-WebSocket-Version", "13");
  20839. return req;
  20840. };
  20841. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20842. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20843. EXPECT_TRUE(
  20844. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20845. EXPECT_TRUE(
  20846. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20847. EXPECT_TRUE(
  20848. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20849. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20850. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20851. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20852. EXPECT_FALSE(
  20853. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20854. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20855. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20856. }
  20857. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20858. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20859. // asks recipients to match each protocol-name case-insensitively, and RFC
  20860. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20861. // client naming websocket alongside another protocol, or on a second field
  20862. // line, is offering websocket; a value that merely contains "websocket" as a
  20863. // substring is a different protocol name and is not.
  20864. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20865. Request req;
  20866. req.method = "GET";
  20867. for (const auto &value : upgrade_values) {
  20868. req.headers.emplace("Upgrade", value);
  20869. }
  20870. req.headers.emplace("Connection", "Upgrade");
  20871. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20872. req.headers.emplace("Sec-WebSocket-Version", "13");
  20873. return req;
  20874. };
  20875. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20876. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20877. EXPECT_TRUE(
  20878. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  20879. EXPECT_TRUE(
  20880. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  20881. EXPECT_TRUE(
  20882. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  20883. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  20884. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  20885. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  20886. EXPECT_FALSE(
  20887. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  20888. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  20889. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20890. }
  20891. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  20892. Server svr;
  20893. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  20894. auto port = svr.bind_to_any_port("localhost");
  20895. std::thread t([&]() { svr.listen_after_bind(); });
  20896. auto se = detail::scope_exit([&] {
  20897. svr.stop();
  20898. t.join();
  20899. });
  20900. svr.wait_until_ready();
  20901. Headers headers = {{"Upgrade", "websocket"},
  20902. {"Connection", "notupgrade"},
  20903. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20904. {"Sec-WebSocket-Version", "13"}};
  20905. Client cli("localhost", port);
  20906. auto res = cli.Get("/ws", headers);
  20907. // The route exists only as a WebSocket route, so a request that fails the
  20908. // handshake check falls through to ordinary routing.
  20909. ASSERT_TRUE(res);
  20910. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  20911. }
  20912. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  20913. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  20914. // Connection value is the only thing left for the client to reject.
  20915. Server svr;
  20916. svr.Get("/ws", [](const Request &req, Response &res) {
  20917. res.status = StatusCode::SwitchingProtocol_101;
  20918. res.set_header("Upgrade", "websocket");
  20919. res.set_header("Connection", "notupgrade");
  20920. res.set_header("Sec-WebSocket-Accept",
  20921. detail::websocket_accept_key(
  20922. req.get_header_value("Sec-WebSocket-Key")));
  20923. });
  20924. auto port = svr.bind_to_any_port("localhost");
  20925. std::thread t([&]() { svr.listen_after_bind(); });
  20926. auto se = detail::scope_exit([&] {
  20927. svr.stop();
  20928. t.join();
  20929. });
  20930. svr.wait_until_ready();
  20931. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20932. auto res = client.connect();
  20933. EXPECT_FALSE(res);
  20934. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20935. EXPECT_FALSE(client.is_open());
  20936. }
  20937. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  20938. Server svr;
  20939. svr.Get("/ws", [](const Request &req, Response &res) {
  20940. res.status = StatusCode::SwitchingProtocol_101;
  20941. res.set_header("Upgrade", "websocket");
  20942. res.set_header("Connection", "Upgrade");
  20943. res.set_header("Sec-WebSocket-Accept",
  20944. detail::websocket_accept_key(
  20945. req.get_header_value("Sec-WebSocket-Key")));
  20946. res.set_header("Sec-WebSocket-Protocol", "admin");
  20947. });
  20948. auto port = svr.bind_to_any_port("localhost");
  20949. std::thread t([&]() { svr.listen_after_bind(); });
  20950. auto se = detail::scope_exit([&] {
  20951. svr.stop();
  20952. t.join();
  20953. });
  20954. svr.wait_until_ready();
  20955. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  20956. // Server selects a subprotocol the client never offered
  20957. {
  20958. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  20959. ws::WebSocketClient client(url, headers);
  20960. auto res = client.connect();
  20961. EXPECT_FALSE(res);
  20962. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20963. EXPECT_FALSE(client.is_open());
  20964. EXPECT_TRUE(client.subprotocol().empty());
  20965. }
  20966. // Client offered none but the server named one anyway
  20967. {
  20968. ws::WebSocketClient client(url);
  20969. auto res = client.connect();
  20970. EXPECT_FALSE(res);
  20971. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20972. EXPECT_FALSE(client.is_open());
  20973. EXPECT_TRUE(client.subprotocol().empty());
  20974. }
  20975. }
  20976. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  20977. // The socket path doubles as the URL host, so it must not contain '/'.
  20978. const char *shard = getenv("GTEST_SHARD_INDEX");
  20979. const std::string sock_path =
  20980. shard ? std::string("httplib-ws-") + shard + ".sock"
  20981. : std::string("httplib-ws.sock");
  20982. std::remove(sock_path.c_str());
  20983. Server svr;
  20984. std::mutex mtx;
  20985. std::string received_host;
  20986. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20987. {
  20988. std::lock_guard<std::mutex> lock(mtx);
  20989. received_host = req.get_header_value("Host");
  20990. }
  20991. std::string msg;
  20992. while (ws.read(msg)) {
  20993. ws.send(msg);
  20994. }
  20995. });
  20996. svr.set_address_family(AF_UNIX);
  20997. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  20998. auto se = detail::scope_exit([&] {
  20999. svr.stop();
  21000. t.join();
  21001. std::remove(sock_path.c_str());
  21002. });
  21003. svr.wait_until_ready();
  21004. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21005. client.set_address_family(AF_UNIX);
  21006. ASSERT_TRUE(client.connect());
  21007. ASSERT_TRUE(client.send("hello"));
  21008. std::string msg;
  21009. ASSERT_TRUE(client.read(msg));
  21010. client.close();
  21011. {
  21012. std::lock_guard<std::mutex> lock(mtx);
  21013. // There is no host:port for a Unix socket, so the same "localhost"
  21014. // placeholder the HTTP client uses is expected.
  21015. EXPECT_EQ("localhost", received_host);
  21016. }
  21017. }
  21018. // Two threads must never parse WebSocket frames from the same stream.
  21019. // close() used to read the peer's Close reply with its own frame read, so it
  21020. // raced a reader thread that was in the middle of a payload: the payload loop
  21021. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21022. // so bytes taken by close() were replaced with bytes from further along the
  21023. // stream. The message kept its length and silently changed content.
  21024. //
  21025. // The raw peer below sends a frame header plus part of the payload, waits for
  21026. // the handler to call close(), and only then sends the rest. Whichever thread
  21027. // would win the race for those bytes, the message must arrive intact, because
  21028. // close() must not touch the stream while read() owns it.
  21029. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21030. #ifndef _WIN32
  21031. signal(SIGPIPE, SIG_IGN);
  21032. #endif
  21033. const size_t payload_len = 120; // fits the 7-bit length field
  21034. const size_t prefix_len = 8;
  21035. const int attempts = 8;
  21036. std::string expected(payload_len, '\0');
  21037. for (size_t i = 0; i < payload_len; i++) {
  21038. expected[i] = static_cast<char>('a' + i % 26);
  21039. }
  21040. std::atomic<bool> peer_stalled{false};
  21041. std::atomic<bool> handler_done{false};
  21042. std::mutex received_mutex;
  21043. std::vector<std::string> received;
  21044. // Bound every wait, so a regression fails the test instead of hanging the
  21045. // suite.
  21046. auto wait_for = [](const std::atomic<bool> &flag) {
  21047. for (int i = 0; i < 500 && !flag; i++) {
  21048. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21049. }
  21050. };
  21051. Server svr;
  21052. svr.set_websocket_ping_interval(0);
  21053. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21054. std::thread reader([&]() {
  21055. std::string msg;
  21056. while (ws.read(msg)) {
  21057. std::lock_guard<std::mutex> guard(received_mutex);
  21058. received.push_back(msg);
  21059. }
  21060. });
  21061. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21062. // inside read_websocket_frame() when close() runs.
  21063. wait_for(peer_stalled);
  21064. ws.close();
  21065. reader.join();
  21066. handler_done = true;
  21067. });
  21068. auto port = svr.bind_to_any_port("127.0.0.1");
  21069. std::thread t([&]() { svr.listen_after_bind(); });
  21070. auto se = detail::scope_exit([&] {
  21071. svr.stop();
  21072. t.join();
  21073. });
  21074. svr.wait_until_ready();
  21075. auto send_bytes = [](socket_t s, const std::string &data) {
  21076. #ifdef _WIN32
  21077. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21078. #else
  21079. auto n = ::send(s, data.data(), data.size(), 0);
  21080. #endif
  21081. return n == static_cast<decltype(n)>(data.size());
  21082. };
  21083. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21084. // Every length used here fits the 7-bit length field.
  21085. auto masked_header = [](uint8_t first_byte, size_t len) {
  21086. std::string h;
  21087. h += static_cast<char>(first_byte);
  21088. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21089. h.append(4, '\0'); // mask key
  21090. return h;
  21091. };
  21092. for (int attempt = 0; attempt < attempts; attempt++) {
  21093. peer_stalled = false;
  21094. handler_done = false;
  21095. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21096. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21097. auto se_sock = detail::scope_exit([&] {
  21098. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21099. });
  21100. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21101. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21102. sockaddr_in addr{};
  21103. addr.sin_family = AF_INET;
  21104. addr.sin_port = htons(static_cast<uint16_t>(port));
  21105. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21106. ASSERT_EQ(
  21107. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21108. << "attempt " << attempt;
  21109. ASSERT_TRUE(send_bytes(sock,
  21110. "GET /ws HTTP/1.1\r\n"
  21111. "Host: 127.0.0.1\r\n"
  21112. "Upgrade: websocket\r\n"
  21113. "Connection: Upgrade\r\n"
  21114. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21115. "Sec-WebSocket-Version: 13\r\n"
  21116. "\r\n"))
  21117. << "attempt " << attempt;
  21118. std::string response;
  21119. while (response.find("\r\n\r\n") == std::string::npos) {
  21120. char buf[512];
  21121. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21122. if (n <= 0) { break; }
  21123. response.append(buf, static_cast<size_t>(n));
  21124. }
  21125. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21126. << "attempt " << attempt;
  21127. // Send the header of a Binary message but only the first prefix_len bytes
  21128. // of its payload, leaving the reader thread stalled inside the payload.
  21129. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21130. expected.substr(0, prefix_len)))
  21131. << "attempt " << attempt;
  21132. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21133. peer_stalled = true;
  21134. // Let close() send its Close frame and park in its own read before the
  21135. // rest of the payload arrives, so both threads are waiting for it.
  21136. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21137. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21138. close_frame += static_cast<char>(0x03); // status 1000
  21139. close_frame += static_cast<char>(0xE8);
  21140. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21141. << "attempt " << attempt;
  21142. // Closing the peer releases the reader thread even on the buggy path,
  21143. // where it waits for bytes another thread already consumed.
  21144. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21145. detail::close_socket(sock);
  21146. sock = INVALID_SOCKET;
  21147. wait_for(handler_done);
  21148. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21149. }
  21150. std::lock_guard<std::mutex> guard(received_mutex);
  21151. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21152. << "a message in flight when close() ran was dropped";
  21153. for (size_t i = 0; i < received.size(); i++) {
  21154. EXPECT_EQ(expected, received[i]) << "message " << i;
  21155. }
  21156. }
  21157. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21158. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21159. protected:
  21160. void SetUp() override {
  21161. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21162. SERVER_PRIVATE_KEY_FILE);
  21163. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21164. std::string msg;
  21165. ws::ReadResult ret;
  21166. while ((ret = ws.read(msg))) {
  21167. if (ret == ws::Binary) {
  21168. ws.send(msg.data(), msg.size());
  21169. } else {
  21170. ws.send(msg);
  21171. }
  21172. }
  21173. });
  21174. port_ = server_->bind_to_any_port(HOST);
  21175. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21176. server_->wait_until_ready();
  21177. }
  21178. void TearDown() override {
  21179. server_->stop();
  21180. if (server_thread_.joinable()) { server_thread_.join(); }
  21181. }
  21182. std::unique_ptr<SSLServer> server_;
  21183. std::thread server_thread_;
  21184. int port_ = 0;
  21185. };
  21186. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21187. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21188. "/ws-echo");
  21189. client.enable_server_certificate_verification(false);
  21190. ASSERT_TRUE(client.connect());
  21191. ASSERT_TRUE(client.is_open());
  21192. ASSERT_TRUE(client.send("Hello WSS"));
  21193. std::string msg;
  21194. EXPECT_EQ(ws::Text, client.read(msg));
  21195. EXPECT_EQ("Hello WSS", msg);
  21196. client.close();
  21197. }
  21198. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21199. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21200. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21201. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21202. // client (without calling close() first) is the only path that runs
  21203. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21204. // bug exactly.
  21205. //
  21206. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21207. // when linked against an instrumented libssl; run under Valgrind to catch it
  21208. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21209. // suite (the freed session otherwise stalls on the close handshake) — this test
  21210. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21211. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21212. {
  21213. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21214. "/ws-echo");
  21215. client.enable_server_certificate_verification(false);
  21216. client.set_read_timeout(2, 0);
  21217. client.set_write_timeout(2, 0);
  21218. ASSERT_TRUE(client.connect());
  21219. ASSERT_TRUE(client.is_open());
  21220. ASSERT_TRUE(client.send("still open"));
  21221. // Intentionally do NOT call client.close(): leaving scope runs
  21222. // shutdown_and_close() with the WebSocket still open, which must send the
  21223. // close frame while the TLS session is still alive.
  21224. }
  21225. }
  21226. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21227. // shutdown_and_close() at the start of connect(), reproducing the same
  21228. // use-after-free within the test body rather than at scope exit. The second
  21229. // connect must succeed and echo, proving the close handshake ran over a live
  21230. // session. See the note above about memory-tool requirements.
  21231. TEST_F(WebSocketSSLIntegrationTest,
  21232. ReconnectWhileOpenSendsCloseOverLiveSession) {
  21233. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21234. "/ws-echo");
  21235. client.enable_server_certificate_verification(false);
  21236. client.set_read_timeout(2, 0);
  21237. client.set_write_timeout(2, 0);
  21238. ASSERT_TRUE(client.connect());
  21239. ASSERT_TRUE(client.is_open());
  21240. ASSERT_TRUE(client.send("still open"));
  21241. // Reconnect without closing first: connect() calls shutdown_and_close() on
  21242. // the still-open connection, which must not touch a freed TLS session.
  21243. ASSERT_TRUE(client.connect());
  21244. ASSERT_TRUE(client.is_open());
  21245. ASSERT_TRUE(client.send("after reconnect"));
  21246. std::string msg;
  21247. EXPECT_EQ(ws::Text, client.read(msg));
  21248. EXPECT_EQ("after reconnect", msg);
  21249. client.close();
  21250. }
  21251. #endif
  21252. #ifdef CPPHTTPLIB_SSL_ENABLED
  21253. class WebSocketSSLCATest : public ::testing::Test {
  21254. protected:
  21255. void SetUp() override {
  21256. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  21257. SERVER_PRIVATE_KEY_FILE);
  21258. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21259. std::string msg;
  21260. while (ws.read(msg)) {
  21261. ws.send(msg);
  21262. }
  21263. });
  21264. port_ = server_->bind_to_any_port("127.0.0.1");
  21265. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21266. server_->wait_until_ready();
  21267. }
  21268. void TearDown() override {
  21269. server_->stop();
  21270. if (server_thread_.joinable()) { server_thread_.join(); }
  21271. }
  21272. std::string url() const {
  21273. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21274. }
  21275. std::unique_ptr<SSLServer> server_;
  21276. std::thread server_thread_;
  21277. int port_ = 0;
  21278. };
  21279. // A custom CA loaded as PEM verifies the server with full certificate
  21280. // verification enabled
  21281. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21282. ws::WebSocketClient client(url());
  21283. std::string cert;
  21284. read_file(SERVER_CERT2_FILE, cert);
  21285. client.load_ca_cert_store(cert.c_str(), cert.size());
  21286. ASSERT_TRUE(client.connect());
  21287. ASSERT_TRUE(client.send("hello"));
  21288. std::string msg;
  21289. EXPECT_EQ(ws::Text, client.read(msg));
  21290. EXPECT_EQ("hello", msg);
  21291. client.close();
  21292. }
  21293. // A custom CA that does not cover the server must fail verification (the
  21294. // custom CA is exclusive; system certs are not loaded alongside it)
  21295. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21296. ws::WebSocketClient client(url());
  21297. std::string cert;
  21298. read_file(CLIENT_CA_CERT_FILE, cert);
  21299. client.load_ca_cert_store(cert.c_str(), cert.size());
  21300. auto res = client.connect();
  21301. ASSERT_FALSE(res);
  21302. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21303. EXPECT_EQ(-1, res.status());
  21304. EXPECT_NE(0u, res.ssl_backend_error());
  21305. }
  21306. // The same CA as a file path rather than PEM in memory
  21307. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21308. ws::WebSocketClient client(url());
  21309. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21310. ASSERT_TRUE(client.connect());
  21311. ASSERT_TRUE(client.send("hello"));
  21312. std::string msg;
  21313. EXPECT_EQ(ws::Text, client.read(msg));
  21314. EXPECT_EQ("hello", msg);
  21315. client.close();
  21316. }
  21317. // ...and a CA file that does not cover the server still fails, so it is the
  21318. // path above that decides the outcome
  21319. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21320. ws::WebSocketClient client(url());
  21321. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21322. ASSERT_FALSE(client.connect());
  21323. }
  21324. // Regression test: reconnecting with a native custom CA store used to reuse
  21325. // a store handle the previous TLS context had already freed (use-after-free
  21326. // under the OpenSSL backend). The context now lives as long as the client.
  21327. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  21328. ws::WebSocketClient client(url());
  21329. std::string cert;
  21330. read_file(SERVER_CERT2_FILE, cert);
  21331. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  21332. ASSERT_TRUE(client.connect());
  21333. client.close();
  21334. ASSERT_TRUE(client.connect());
  21335. ASSERT_TRUE(client.send("again"));
  21336. std::string msg;
  21337. EXPECT_EQ(ws::Text, client.read(msg));
  21338. EXPECT_EQ("again", msg);
  21339. client.close();
  21340. }
  21341. // Regression test: a certificate with a trusted chain but no identity match
  21342. // for the server IP must be rejected. The Mbed TLS backend used to skip
  21343. // verification entirely for IP hosts, so this connection succeeded there.
  21344. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  21345. // chain verification while the identity check must still fail.
  21346. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  21347. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21348. ASSERT_TRUE(svr.is_valid());
  21349. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21350. std::string msg;
  21351. while (ws.read(msg)) {
  21352. ws.send(msg);
  21353. }
  21354. });
  21355. auto port = svr.bind_to_any_port("127.0.0.1");
  21356. auto t = std::thread([&]() { svr.listen_after_bind(); });
  21357. auto se = detail::scope_exit([&] {
  21358. svr.stop();
  21359. t.join();
  21360. });
  21361. svr.wait_until_ready();
  21362. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  21363. "/echo");
  21364. std::string cert;
  21365. read_file(SERVER_CERT_FILE, cert);
  21366. client.load_ca_cert_store(cert.c_str(), cert.size());
  21367. ASSERT_FALSE(client.connect());
  21368. }
  21369. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  21370. // SNI, so nothing binds the host name to the TLS session. These bind the
  21371. // server to "localhost" instead, the only shape that exercises the SNI and
  21372. // hostname-verification path with certificate verification left enabled.
  21373. class WebSocketSSLDnsHostTest : public ::testing::Test {
  21374. protected:
  21375. void Start(const char *cert_file) {
  21376. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  21377. SERVER_PRIVATE_KEY_FILE);
  21378. ASSERT_TRUE(server_->is_valid());
  21379. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21380. std::string msg;
  21381. while (ws.read(msg)) {
  21382. ws.send(msg);
  21383. }
  21384. });
  21385. port_ = server_->bind_to_any_port("localhost");
  21386. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21387. server_->wait_until_ready();
  21388. }
  21389. void TearDown() override {
  21390. if (server_) { server_->stop(); }
  21391. if (server_thread_.joinable()) { server_thread_.join(); }
  21392. }
  21393. std::string url() const {
  21394. return "wss://localhost:" + std::to_string(port_) + "/echo";
  21395. }
  21396. std::unique_ptr<SSLServer> server_;
  21397. std::thread server_thread_;
  21398. int port_ = 0;
  21399. };
  21400. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  21401. // out and the connection is usable
  21402. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  21403. Start(SERVER_CERT2_FILE);
  21404. ws::WebSocketClient client(url());
  21405. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21406. ASSERT_TRUE(client.connect());
  21407. ASSERT_TRUE(client.send("hello"));
  21408. std::string msg;
  21409. EXPECT_EQ(ws::Text, client.read(msg));
  21410. EXPECT_EQ("hello", msg);
  21411. client.close();
  21412. }
  21413. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  21414. // while the identity check must still reject "localhost"
  21415. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  21416. Start(SERVER_CERT_FILE);
  21417. ws::WebSocketClient client(url());
  21418. client.set_ca_cert_path(SERVER_CERT_FILE);
  21419. auto res = client.connect();
  21420. ASSERT_FALSE(res);
  21421. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  21422. EXPECT_EQ(-1, res.status());
  21423. }
  21424. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  21425. // disabled: the chain is still checked, only the identity check is skipped
  21426. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  21427. Start(SERVER_CERT_FILE);
  21428. ws::WebSocketClient client(url());
  21429. client.set_ca_cert_path(SERVER_CERT_FILE);
  21430. client.enable_server_hostname_verification(false);
  21431. ASSERT_TRUE(client.connect());
  21432. ASSERT_TRUE(client.send("hello"));
  21433. std::string msg;
  21434. EXPECT_EQ(ws::Text, client.read(msg));
  21435. EXPECT_EQ("hello", msg);
  21436. client.close();
  21437. }
  21438. // A CA that did not sign the server certificate fails the chain, even though
  21439. // the name would match
  21440. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  21441. Start(SERVER_CERT2_FILE);
  21442. ws::WebSocketClient client(url());
  21443. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21444. ASSERT_FALSE(client.connect());
  21445. }
  21446. // With verification disabled, neither the chain nor the name is checked
  21447. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  21448. Start(SERVER_CERT_FILE);
  21449. ws::WebSocketClient client(url());
  21450. client.enable_server_certificate_verification(false);
  21451. ASSERT_TRUE(client.connect());
  21452. ASSERT_TRUE(client.send("hello"));
  21453. std::string msg;
  21454. EXPECT_EQ(ws::Text, client.read(msg));
  21455. EXPECT_EQ("hello", msg);
  21456. client.close();
  21457. }
  21458. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  21459. protected:
  21460. void SetUp() override {
  21461. server_ = httplib::detail::make_unique<SSLServer>(
  21462. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21463. ASSERT_TRUE(server_->is_valid());
  21464. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21465. std::string msg;
  21466. while (ws.read(msg)) {
  21467. ws.send(msg);
  21468. }
  21469. });
  21470. port_ = server_->bind_to_any_port("localhost");
  21471. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21472. server_->wait_until_ready();
  21473. }
  21474. void TearDown() override {
  21475. server_->stop();
  21476. if (server_thread_.joinable()) { server_thread_.join(); }
  21477. }
  21478. std::string url() const {
  21479. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21480. }
  21481. void ConnectWithClientCert(const std::string &client_cert_file,
  21482. const std::string &client_private_key_file,
  21483. const char *private_key_password) {
  21484. std::string cert_pem, key_pem;
  21485. read_file(client_cert_file, cert_pem);
  21486. read_file(client_private_key_file, key_pem);
  21487. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21488. key_pem.c_str(), key_pem.size(),
  21489. private_key_password};
  21490. ws::WebSocketClient client(url(), pem);
  21491. ASSERT_TRUE(client.is_valid());
  21492. client.enable_server_certificate_verification(false);
  21493. ASSERT_TRUE(client.connect());
  21494. ASSERT_TRUE(client.send("hello"));
  21495. std::string msg;
  21496. EXPECT_EQ(ws::Text, client.read(msg));
  21497. EXPECT_EQ("hello", msg);
  21498. client.close();
  21499. }
  21500. std::unique_ptr<SSLServer> server_;
  21501. std::thread server_thread_;
  21502. int port_ = 0;
  21503. };
  21504. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21505. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21506. }
  21507. // Control for the tests above: the fixture's server really does require a
  21508. // client certificate, so it is the PEM the constructor installed that decides
  21509. // the outcome.
  21510. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21511. ws::WebSocketClient client(url());
  21512. ASSERT_TRUE(client.is_valid());
  21513. client.enable_server_certificate_verification(false);
  21514. EXPECT_FALSE(client.connect());
  21515. }
  21516. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21517. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21518. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21519. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21520. }
  21521. #endif
  21522. #if !defined(_WIN32)
  21523. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21524. auto secret_dir = std::string("./symlink_test_secret");
  21525. auto served_dir = std::string("./symlink_test_served");
  21526. auto secret_file = secret_dir + "/secret.txt";
  21527. auto symlink_path = served_dir + "/escape";
  21528. // Setup: create directories and files
  21529. mkdir(secret_dir.c_str(), 0755);
  21530. mkdir(served_dir.c_str(), 0755);
  21531. {
  21532. std::ofstream ofs(secret_file);
  21533. ofs << "SECRET_DATA";
  21534. }
  21535. // Create symlink using absolute path so it resolves correctly
  21536. #ifdef PATH_MAX
  21537. char abs_secret[PATH_MAX];
  21538. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21539. #else
  21540. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21541. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21542. ASSERT_NE(nullptr, abs_secret);
  21543. #endif
  21544. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21545. auto se = detail::scope_exit([&] {
  21546. unlink(symlink_path.c_str());
  21547. unlink(secret_file.c_str());
  21548. rmdir(served_dir.c_str());
  21549. rmdir(secret_dir.c_str());
  21550. });
  21551. Server svr;
  21552. svr.set_mount_point("/", served_dir);
  21553. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21554. auto se2 = detail::scope_exit([&] {
  21555. svr.stop();
  21556. listen_thread.join();
  21557. });
  21558. svr.wait_until_ready();
  21559. Client cli("localhost", PORT);
  21560. // Symlink pointing outside base dir should be blocked
  21561. auto res = cli.Get("/escape/secret.txt");
  21562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21563. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21564. }
  21565. #endif
  21566. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  21567. // "GET /smuggled" request), reads the first response, and only then sends the
  21568. // embedded request as the body. Returns how many times /smuggled ran.
  21569. //
  21570. // The body is sent AFTER receiving the first response (as in the original
  21571. // PoC) so that the stream_line_reader cannot buffer it together with the
  21572. // headers of the first request.
  21573. static int count_smuggled_requests(const std::string &outer_head,
  21574. std::string &first_response) {
  21575. Server svr;
  21576. svr.set_mount_point("/", "./www");
  21577. std::atomic<int> smuggled_count(0);
  21578. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21579. smuggled_count++;
  21580. res.set_content("oops", "text/plain");
  21581. });
  21582. svr.Post("/post", [&](const Request &req, Response &res) {
  21583. res.set_content(req.body, "text/plain");
  21584. });
  21585. auto port = svr.bind_to_any_port("localhost");
  21586. thread t = thread([&] { svr.listen_after_bind(); });
  21587. auto se = detail::scope_exit([&] {
  21588. svr.stop();
  21589. t.join();
  21590. });
  21591. svr.wait_until_ready();
  21592. auto error = Error::Success;
  21593. auto sock = detail::create_client_socket(
  21594. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21595. /*connection_timeout_sec=*/2, 0,
  21596. /*read_timeout_sec=*/2, 0,
  21597. /*write_timeout_sec=*/2, 0, std::string(), error);
  21598. EXPECT_NE(INVALID_SOCKET, sock);
  21599. if (sock == INVALID_SOCKET) { return -1; }
  21600. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21601. // The "smuggled" request will be sent as the body of the outer request
  21602. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21603. "Host: localhost\r\n"
  21604. "Connection: close\r\n"
  21605. "\r\n";
  21606. auto head = outer_head;
  21607. auto len = std::to_string(smuggled.size());
  21608. for (auto pos = head.find("{len}"); pos != std::string::npos;
  21609. pos = head.find("{len}", pos + len.size())) {
  21610. head.replace(pos, 5, len);
  21611. }
  21612. // Step 1: Send only the outer request headers (no body yet)
  21613. auto sent = send(sock, head.data(), head.size(), 0);
  21614. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  21615. // Step 2: Read the first response
  21616. char buf[4096];
  21617. for (;;) {
  21618. auto n = recv(sock, buf, sizeof(buf), 0);
  21619. if (n <= 0) break;
  21620. first_response.append(buf, static_cast<size_t>(n));
  21621. // Stop once we have a complete response (headers + body)
  21622. auto hdr_end = first_response.find("\r\n\r\n");
  21623. if (hdr_end != std::string::npos) {
  21624. // Check for Content-Length to know when the body is complete
  21625. auto cl_pos = first_response.find("Content-Length:");
  21626. if (cl_pos != std::string::npos) {
  21627. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21628. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21629. auto cl = std::stoul(
  21630. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21631. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21632. } else {
  21633. break; // No Content-Length, assume headers-only response
  21634. }
  21635. }
  21636. }
  21637. // Step 3: Now send the body, which looks like a new HTTP request. On a
  21638. // vulnerable server the keep-alive loop reads this as a second request. The
  21639. // server may already have closed the connection, so the result is ignored.
  21640. send(sock, smuggled.data(), smuggled.size(), 0);
  21641. // Half-close so that a server which drained the body sees EOF and closes,
  21642. // instead of the read below waiting for the read timeout.
  21643. #ifdef _WIN32
  21644. ::shutdown(sock, SD_SEND);
  21645. #else
  21646. ::shutdown(sock, SHUT_WR);
  21647. #endif
  21648. // Step 4: Read until the server closes the connection
  21649. for (;;) {
  21650. auto n = recv(sock, buf, sizeof(buf), 0);
  21651. if (n <= 0) break;
  21652. }
  21653. return smuggled_count.load();
  21654. }
  21655. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21656. // A GET request with Content-Length to a static file handler must have its
  21657. // body drained before the keep-alive connection is reused. Otherwise the
  21658. // unread body bytes are interpreted as the next HTTP request.
  21659. std::string first_response;
  21660. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21661. "Host: localhost\r\n"
  21662. "Content-Length: {len}\r\n"
  21663. "\r\n",
  21664. first_response));
  21665. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  21666. }
  21667. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  21668. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  21669. // be answered with 400 and the connection closed. Treating it as "no body"
  21670. // leaves the body to be parsed as the next request.
  21671. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  21672. const char *targets[] = {
  21673. "GET /file", // handler that never reads the body
  21674. "GET /not-found", // no handler matches (404)
  21675. "POST /post", // handler that reads the body
  21676. };
  21677. for (auto target : targets) {
  21678. for (auto value : values) {
  21679. std::string first_response;
  21680. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  21681. " HTTP/1.1\r\n"
  21682. "Host: localhost\r\n"
  21683. "Content-Length: " +
  21684. value + "\r\n\r\n",
  21685. first_response))
  21686. << target << " with Content-Length: " << value;
  21687. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  21688. << target << " with Content-Length: " << value;
  21689. }
  21690. }
  21691. }
  21692. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  21693. // A 400 for an unparseable request line leaves the rest of the message
  21694. // unread, so the connection must be closed rather than reused.
  21695. std::string first_response;
  21696. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  21697. "Host: localhost\r\n"
  21698. "Content-Length: {len}\r\n"
  21699. "\r\n",
  21700. first_response));
  21701. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21702. }
  21703. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  21704. // Same as above for a header block that fails to parse.
  21705. std::string first_response;
  21706. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21707. "Host: localhost\r\n"
  21708. "Bad Header\r\n"
  21709. "Content-Length: {len}\r\n"
  21710. "\r\n",
  21711. first_response));
  21712. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21713. }
  21714. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  21715. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  21716. // server must not read another request on that connection, even when the
  21717. // request had no body to drain.
  21718. std::string first_response;
  21719. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  21720. "Host: localhost\r\n"
  21721. "\r\n",
  21722. first_response));
  21723. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  21724. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  21725. }
  21726. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21727. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21728. // must be rejected with 400 Bad Request.
  21729. Server svr;
  21730. svr.Post("/test", [&](const Request &, Response &res) {
  21731. res.set_content("ok", "text/plain");
  21732. });
  21733. thread t = thread([&] { svr.listen(HOST, PORT); });
  21734. auto se = detail::scope_exit([&] {
  21735. svr.stop();
  21736. t.join();
  21737. ASSERT_FALSE(svr.is_running());
  21738. });
  21739. svr.wait_until_ready();
  21740. // Exact "chunked"
  21741. {
  21742. auto req = "POST /test HTTP/1.1\r\n"
  21743. "Host: localhost\r\n"
  21744. "Content-Length: 5\r\n"
  21745. "Transfer-Encoding: chunked\r\n"
  21746. "Connection: close\r\n"
  21747. "\r\n"
  21748. "hello";
  21749. std::string response;
  21750. ASSERT_TRUE(send_request(1, req, &response));
  21751. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21752. response.substr(0, response.find("\r\n")));
  21753. }
  21754. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21755. {
  21756. auto req = "POST /test HTTP/1.1\r\n"
  21757. "Host: localhost\r\n"
  21758. "Content-Length: 5\r\n"
  21759. "Transfer-Encoding: gzip, chunked\r\n"
  21760. "Connection: close\r\n"
  21761. "\r\n"
  21762. "hello";
  21763. std::string response;
  21764. ASSERT_TRUE(send_request(1, req, &response));
  21765. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21766. response.substr(0, response.find("\r\n")));
  21767. }
  21768. }
  21769. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21770. Server svr;
  21771. svr.Post("/test", [&](const Request &, Response &res) {
  21772. res.set_content("ok", "text/plain");
  21773. });
  21774. thread t = thread([&] { svr.listen(HOST, PORT); });
  21775. auto se = detail::scope_exit([&] {
  21776. svr.stop();
  21777. t.join();
  21778. ASSERT_FALSE(svr.is_running());
  21779. });
  21780. svr.wait_until_ready();
  21781. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  21782. // length cannot be determined, so the server must answer 400 and close
  21783. // rather than treat the request as bodyless and leave the body in the
  21784. // socket for the next request to pick up.
  21785. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  21786. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  21787. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  21788. std::string response;
  21789. ASSERT_TRUE(send_request(1, req, &response));
  21790. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21791. response.substr(0, response.find("\r\n")))
  21792. << transfer_encoding;
  21793. }
  21794. // RFC 9110 5.3: the codings may also be split across several
  21795. // Transfer-Encoding lines, which combine in the order they were received.
  21796. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  21797. // just like the single-line "chunked, gzip" above.
  21798. {
  21799. auto req = "POST /test HTTP/1.1\r\n"
  21800. "Host: localhost\r\n"
  21801. "Transfer-Encoding: chunked\r\n"
  21802. "Transfer-Encoding: gzip\r\n"
  21803. "\r\n"
  21804. "0\r\n\r\n";
  21805. std::string response;
  21806. ASSERT_TRUE(send_request(1, req, &response));
  21807. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21808. response.substr(0, response.find("\r\n")));
  21809. }
  21810. // A sequence ending in chunked stays valid.
  21811. auto req = "POST /test HTTP/1.1\r\n"
  21812. "Host: localhost\r\n"
  21813. "Transfer-Encoding: gzip, chunked\r\n"
  21814. "Connection: close\r\n"
  21815. "\r\n"
  21816. "0\r\n\r\n";
  21817. std::string response;
  21818. ASSERT_TRUE(send_request(1, req, &response));
  21819. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21820. // ...including when it is spread over several lines.
  21821. auto split_req = "POST /test HTTP/1.1\r\n"
  21822. "Host: localhost\r\n"
  21823. "Transfer-Encoding: gzip\r\n"
  21824. "Transfer-Encoding: chunked\r\n"
  21825. "Connection: close\r\n"
  21826. "\r\n"
  21827. "0\r\n\r\n";
  21828. std::string split_response;
  21829. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21830. EXPECT_EQ("HTTP/1.1 200 OK",
  21831. split_response.substr(0, split_response.find("\r\n")));
  21832. }
  21833. // Regression for issue #2450: a DELETE without Content-Length on a
  21834. // keep-alive connection must not let the post-response drain consume the
  21835. // next request's bytes.
  21836. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21837. Server svr;
  21838. std::atomic<int> delete_count(0);
  21839. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21840. delete_count++;
  21841. res.status = StatusCode::NoContent_204;
  21842. });
  21843. auto port = svr.bind_to_any_port(HOST);
  21844. thread t = thread([&] { svr.listen_after_bind(); });
  21845. auto se = detail::scope_exit([&] {
  21846. svr.stop();
  21847. t.join();
  21848. });
  21849. svr.wait_until_ready();
  21850. auto error = Error::Success;
  21851. auto sock = detail::create_client_socket(
  21852. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21853. /*connection_timeout_sec=*/2, 0,
  21854. /*read_timeout_sec=*/2, 0,
  21855. /*write_timeout_sec=*/2, 0, std::string(), error);
  21856. ASSERT_NE(INVALID_SOCKET, sock);
  21857. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21858. auto send_request_and_read_response = [&](const std::string &req,
  21859. std::string &out) -> bool {
  21860. auto sent = send(sock, req.data(), req.size(), 0);
  21861. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21862. char buf[4096];
  21863. for (;;) {
  21864. auto n = recv(sock, buf, sizeof(buf), 0);
  21865. if (n <= 0) { return !out.empty(); }
  21866. out.append(buf, static_cast<size_t>(n));
  21867. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21868. }
  21869. };
  21870. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21871. "Host: localhost\r\n"
  21872. "\r\n";
  21873. std::string resp1;
  21874. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21875. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21876. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21877. "Host: localhost\r\n"
  21878. "Connection: close\r\n"
  21879. "\r\n";
  21880. std::string resp2;
  21881. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  21882. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  21883. EXPECT_EQ(2, delete_count.load());
  21884. }
  21885. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  21886. Server svr;
  21887. svr.Post("/ingest", [&](const Request &, Response &res,
  21888. const ContentReader &content_reader) {
  21889. auto consumed = content_reader([](const char *, size_t) { return false; });
  21890. EXPECT_FALSE(consumed);
  21891. res.status = StatusCode::Conflict_409;
  21892. res.set_header("Connection", "close");
  21893. });
  21894. auto port = svr.bind_to_any_port(HOST);
  21895. thread t = thread([&] { svr.listen_after_bind(); });
  21896. auto se = detail::scope_exit([&] {
  21897. svr.stop();
  21898. t.join();
  21899. });
  21900. svr.wait_until_ready();
  21901. auto error = Error::Success;
  21902. auto sock = detail::create_client_socket(
  21903. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21904. /*connection_timeout_sec=*/2, 0,
  21905. /*read_timeout_sec=*/1, 0,
  21906. /*write_timeout_sec=*/2, 0, std::string(), error);
  21907. ASSERT_NE(INVALID_SOCKET, sock);
  21908. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21909. std::string request = "POST /ingest HTTP/1.1\r\n"
  21910. "Host: localhost\r\n"
  21911. "Transfer-Encoding: chunked\r\n"
  21912. "\r\n"
  21913. "4\r\n"
  21914. "data\r\n";
  21915. auto sent = send(sock, request.data(), request.size(), 0);
  21916. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  21917. std::string response;
  21918. ssize_t received = 0;
  21919. do {
  21920. char buf[4096];
  21921. received = recv(sock, buf, sizeof(buf), 0);
  21922. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  21923. } while (received > 0);
  21924. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  21925. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  21926. EXPECT_EQ(0, received);
  21927. }
  21928. namespace no_proxy_test {
  21929. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  21930. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  21931. // calling listen().
  21932. class ScopedServer {
  21933. public:
  21934. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  21935. ~ScopedServer() {
  21936. svr_.stop();
  21937. if (th_.joinable()) { th_.join(); }
  21938. }
  21939. Server &svr() { return svr_; }
  21940. int port() const { return port_; }
  21941. void listen() {
  21942. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21943. svr_.wait_until_ready();
  21944. }
  21945. private:
  21946. Server svr_;
  21947. std::thread th_;
  21948. int port_ = 0;
  21949. };
  21950. class ProxyAndTargetServers {
  21951. public:
  21952. ProxyAndTargetServers() {
  21953. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  21954. proxy_hits_++;
  21955. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21956. res.set_content("via-proxy", "text/plain");
  21957. });
  21958. target_.Get(".*", [this](const Request &req, Response &res) {
  21959. target_hits_++;
  21960. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21961. res.set_content("direct", "text/plain");
  21962. });
  21963. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  21964. target_port_ = target_.bind_to_any_port("127.0.0.1");
  21965. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  21966. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  21967. proxy_mock_.wait_until_ready();
  21968. target_.wait_until_ready();
  21969. }
  21970. ~ProxyAndTargetServers() {
  21971. proxy_mock_.stop();
  21972. target_.stop();
  21973. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  21974. if (target_thread_.joinable()) { target_thread_.join(); }
  21975. }
  21976. Server &proxy_mock() { return proxy_mock_; }
  21977. Server &target() { return target_; }
  21978. int proxy_port() const { return proxy_port_; }
  21979. int target_port() const { return target_port_; }
  21980. int proxy_hits() const { return proxy_hits_.load(); }
  21981. int target_hits() const { return target_hits_.load(); }
  21982. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  21983. void reset_counters() {
  21984. proxy_hits_ = 0;
  21985. target_hits_ = 0;
  21986. last_had_proxy_authz_ = false;
  21987. }
  21988. private:
  21989. Server proxy_mock_;
  21990. Server target_;
  21991. std::thread proxy_thread_;
  21992. std::thread target_thread_;
  21993. int proxy_port_ = 0;
  21994. int target_port_ = 0;
  21995. std::atomic<int> proxy_hits_{0};
  21996. std::atomic<int> target_hits_{0};
  21997. std::atomic<bool> last_had_proxy_authz_{false};
  21998. };
  21999. inline std::unique_ptr<Client> make_client(const std::string &host,
  22000. ProxyAndTargetServers &s) {
  22001. auto cli = detail::make_unique<Client>(host, s.target_port());
  22002. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22003. cli->set_proxy("127.0.0.1", s.proxy_port());
  22004. return cli;
  22005. }
  22006. } // namespace no_proxy_test
  22007. using no_proxy_test::make_client;
  22008. using no_proxy_test::ProxyAndTargetServers;
  22009. TEST(NoProxyTest, ExactHostnameBypasses) {
  22010. ProxyAndTargetServers s;
  22011. auto cli = make_client("example.com", s);
  22012. cli->set_no_proxy({"example.com"});
  22013. auto res = cli->Get("/");
  22014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22015. EXPECT_EQ(0, s.proxy_hits());
  22016. EXPECT_EQ(1, s.target_hits());
  22017. }
  22018. TEST(NoProxyTest, SubdomainBypasses) {
  22019. ProxyAndTargetServers s;
  22020. auto cli = make_client("foo.example.com", s);
  22021. cli->set_no_proxy({"example.com"});
  22022. auto res = cli->Get("/");
  22023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22024. EXPECT_EQ(0, s.proxy_hits());
  22025. EXPECT_EQ(1, s.target_hits());
  22026. }
  22027. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  22028. // Regression guard: "evilexample.com" must not be considered a subdomain
  22029. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22030. // check would let traffic bypass the proxy and leak credentials direct
  22031. // to the attacker host.
  22032. ProxyAndTargetServers s;
  22033. auto cli = make_client("evilexample.com", s);
  22034. cli->set_no_proxy({"example.com"});
  22035. auto res = cli->Get("/");
  22036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22037. EXPECT_GE(s.proxy_hits(), 1);
  22038. EXPECT_EQ(0, s.target_hits());
  22039. }
  22040. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22041. ProxyAndTargetServers s;
  22042. auto cli = make_client("example.com.evil.com", s);
  22043. cli->set_no_proxy({"example.com"});
  22044. auto res = cli->Get("/");
  22045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22046. EXPECT_GE(s.proxy_hits(), 1);
  22047. EXPECT_EQ(0, s.target_hits());
  22048. }
  22049. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22050. ProxyAndTargetServers s;
  22051. auto cli = make_client("example.com", s);
  22052. cli->set_no_proxy({".example.com"});
  22053. auto res = cli->Get("/");
  22054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22055. EXPECT_EQ(0, s.proxy_hits());
  22056. EXPECT_EQ(1, s.target_hits());
  22057. }
  22058. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22059. ProxyAndTargetServers s;
  22060. auto cli = make_client("Example.COM", s);
  22061. cli->set_no_proxy({"EXAMPLE.com"});
  22062. auto res = cli->Get("/");
  22063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22064. EXPECT_EQ(0, s.proxy_hits());
  22065. EXPECT_EQ(1, s.target_hits());
  22066. }
  22067. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22068. ProxyAndTargetServers s;
  22069. auto cli = make_client("example.com.", s);
  22070. cli->set_no_proxy({"example.com"});
  22071. auto res = cli->Get("/");
  22072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22073. EXPECT_EQ(0, s.proxy_hits());
  22074. EXPECT_EQ(1, s.target_hits());
  22075. }
  22076. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22077. // Trailing dots must be normalized on BOTH sides — host and entry.
  22078. // An implementation that only strips the host-side trailing dot would
  22079. // fail to match host "example.com" against entry "example.com." because
  22080. // a literal substring search would compare 11 chars against 12.
  22081. ProxyAndTargetServers s;
  22082. auto cli = make_client("example.com", s);
  22083. cli->set_no_proxy({"example.com."});
  22084. auto res = cli->Get("/");
  22085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22086. EXPECT_EQ(0, s.proxy_hits());
  22087. EXPECT_EQ(1, s.target_hits());
  22088. }
  22089. TEST(NoProxyTest, WildcardBypassesEverything) {
  22090. ProxyAndTargetServers s;
  22091. auto cli = make_client("anything.invalid.test", s);
  22092. cli->set_no_proxy({"*"});
  22093. auto res = cli->Get("/");
  22094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22095. EXPECT_EQ(0, s.proxy_hits());
  22096. EXPECT_EQ(1, s.target_hits());
  22097. }
  22098. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22099. ProxyAndTargetServers s;
  22100. Client cli("127.0.0.1", s.target_port());
  22101. cli.set_proxy("127.0.0.1", s.proxy_port());
  22102. cli.set_no_proxy({"127.0.0.1"});
  22103. auto res = cli.Get("/");
  22104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22105. EXPECT_EQ(0, s.proxy_hits());
  22106. EXPECT_EQ(1, s.target_hits());
  22107. }
  22108. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22109. ProxyAndTargetServers s;
  22110. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22111. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22112. cli.set_proxy("127.0.0.1", s.proxy_port());
  22113. cli.set_no_proxy({"::1"});
  22114. auto res = cli.Get("/");
  22115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22116. EXPECT_EQ(0, s.proxy_hits());
  22117. EXPECT_EQ(1, s.target_hits());
  22118. }
  22119. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22120. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22121. // must still be recognized as IPv6 for CIDR matching. Implementations
  22122. // that detect IPv6 only when the host begins with '[' would parse the
  22123. // host as a hostname and miss the match.
  22124. ProxyAndTargetServers s;
  22125. Client cli("fe80::1", s.target_port());
  22126. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22127. cli.set_proxy("127.0.0.1", s.proxy_port());
  22128. cli.set_no_proxy({"fe80::/10"});
  22129. auto res = cli.Get("/");
  22130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22131. EXPECT_EQ(0, s.proxy_hits());
  22132. EXPECT_EQ(1, s.target_hits());
  22133. }
  22134. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22135. ProxyAndTargetServers s;
  22136. Client cli("::1", s.target_port());
  22137. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22138. cli.set_proxy("127.0.0.1", s.proxy_port());
  22139. cli.set_no_proxy({"[::1]"});
  22140. auto res = cli.Get("/");
  22141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22142. EXPECT_EQ(0, s.proxy_hits());
  22143. EXPECT_EQ(1, s.target_hits());
  22144. }
  22145. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  22146. ProxyAndTargetServers s;
  22147. Client cli("fe80::1", s.target_port());
  22148. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22149. cli.set_proxy("127.0.0.1", s.proxy_port());
  22150. cli.set_no_proxy({"[fe80::]/10"});
  22151. auto res = cli.Get("/");
  22152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22153. EXPECT_EQ(0, s.proxy_hits());
  22154. EXPECT_EQ(1, s.target_hits());
  22155. }
  22156. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22157. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22158. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22159. // tricks via address-family conversion.
  22160. ProxyAndTargetServers s;
  22161. Client cli("::ffff:127.0.0.1", s.target_port());
  22162. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22163. cli.set_proxy("127.0.0.1", s.proxy_port());
  22164. cli.set_no_proxy({"127.0.0.1"});
  22165. auto res = cli.Get("/");
  22166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22167. EXPECT_GE(s.proxy_hits(), 1);
  22168. EXPECT_EQ(0, s.target_hits());
  22169. }
  22170. TEST(NoProxyTest, IPv4CidrMatch) {
  22171. ProxyAndTargetServers s;
  22172. Client cli("127.0.0.1", s.target_port());
  22173. cli.set_proxy("127.0.0.1", s.proxy_port());
  22174. cli.set_no_proxy({"127.0.0.0/8"});
  22175. auto res = cli.Get("/");
  22176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22177. EXPECT_EQ(0, s.proxy_hits());
  22178. EXPECT_EQ(1, s.target_hits());
  22179. }
  22180. TEST(NoProxyTest, IPv4CidrNonMatch) {
  22181. ProxyAndTargetServers s;
  22182. Client cli("127.0.0.1", s.target_port());
  22183. cli.set_proxy("127.0.0.1", s.proxy_port());
  22184. cli.set_no_proxy({"10.0.0.0/8"});
  22185. auto res = cli.Get("/");
  22186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22187. EXPECT_GE(s.proxy_hits(), 1);
  22188. EXPECT_EQ(0, s.target_hits());
  22189. }
  22190. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  22191. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  22192. // IPv4 target matches.
  22193. ProxyAndTargetServers s;
  22194. Client cli("127.0.0.1", s.target_port());
  22195. cli.set_proxy("127.0.0.1", s.proxy_port());
  22196. cli.set_no_proxy({"0.0.0.0/0"});
  22197. auto res = cli.Get("/");
  22198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22199. EXPECT_EQ(0, s.proxy_hits());
  22200. EXPECT_EQ(1, s.target_hits());
  22201. }
  22202. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  22203. ProxyAndTargetServers s;
  22204. Client cli("127.0.0.1", s.target_port());
  22205. cli.set_proxy("127.0.0.1", s.proxy_port());
  22206. cli.set_no_proxy({"127.0.0.1"});
  22207. auto res = cli.Get("/");
  22208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22209. EXPECT_EQ(0, s.proxy_hits());
  22210. EXPECT_EQ(1, s.target_hits());
  22211. }
  22212. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  22213. ProxyAndTargetServers s;
  22214. Client cli("127.0.0.1", s.target_port());
  22215. cli.set_proxy("127.0.0.1", s.proxy_port());
  22216. cli.set_no_proxy({"127.0.0.0/33"});
  22217. auto res = cli.Get("/");
  22218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22219. EXPECT_GE(s.proxy_hits(), 1);
  22220. EXPECT_EQ(0, s.target_hits());
  22221. }
  22222. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  22223. // Empty prefix after the slash must be rejected, not silently treated as /32.
  22224. ProxyAndTargetServers s;
  22225. Client cli("127.0.0.1", s.target_port());
  22226. cli.set_proxy("127.0.0.1", s.proxy_port());
  22227. cli.set_no_proxy({"127.0.0.1/"});
  22228. auto res = cli.Get("/");
  22229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22230. EXPECT_GE(s.proxy_hits(), 1);
  22231. EXPECT_EQ(0, s.target_hits());
  22232. }
  22233. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  22234. ProxyAndTargetServers s;
  22235. auto cli = make_client("internal.corp", s);
  22236. cli->set_proxy_basic_auth("u", "p");
  22237. cli->set_no_proxy({"internal.corp"});
  22238. auto res = cli->Get("/");
  22239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22240. EXPECT_EQ(1, s.target_hits());
  22241. EXPECT_EQ(0, s.proxy_hits());
  22242. EXPECT_FALSE(s.last_had_proxy_authz())
  22243. << "Proxy-Authorization must not be sent direct to the target";
  22244. }
  22245. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  22246. ProxyAndTargetServers s;
  22247. auto cli = make_client("public.example", s);
  22248. cli->set_proxy_basic_auth("u", "p");
  22249. cli->set_no_proxy({"internal.corp"}); // does not match
  22250. auto res = cli->Get("/");
  22251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22252. EXPECT_GE(s.proxy_hits(), 1);
  22253. EXPECT_TRUE(s.last_had_proxy_authz());
  22254. }
  22255. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  22256. ProxyAndTargetServers s;
  22257. auto cli = make_client("anything.test", s);
  22258. auto res = cli->Get("/");
  22259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22260. EXPECT_GE(s.proxy_hits(), 1);
  22261. EXPECT_EQ(0, s.target_hits());
  22262. }
  22263. TEST(NoProxyTest, PortSpecificEntryRejected) {
  22264. ProxyAndTargetServers s;
  22265. auto cli = make_client("example.com", s);
  22266. cli->set_no_proxy({"example.com:8080"});
  22267. auto res = cli->Get("/");
  22268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22269. EXPECT_GE(s.proxy_hits(), 1);
  22270. EXPECT_EQ(0, s.target_hits());
  22271. }
  22272. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  22273. ProxyAndTargetServers s;
  22274. auto cli = make_client("anything.test", s);
  22275. cli->set_no_proxy({"", " ", "\t"});
  22276. auto res = cli->Get("/");
  22277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22278. EXPECT_GE(s.proxy_hits(), 1);
  22279. EXPECT_EQ(0, s.target_hits());
  22280. }
  22281. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  22282. // An entry with leading/trailing whitespace must still match — env-style
  22283. // values are commonly pasted with stray spaces and an implementation
  22284. // that feeds the raw token directly to inet_pton would fail to match
  22285. // valid CIDRs because of the spaces.
  22286. ProxyAndTargetServers s;
  22287. Client cli("127.0.0.1", s.target_port());
  22288. cli.set_proxy("127.0.0.1", s.proxy_port());
  22289. cli.set_no_proxy({" 127.0.0.0/8 "});
  22290. auto res = cli.Get("/");
  22291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22292. EXPECT_EQ(0, s.proxy_hits());
  22293. EXPECT_EQ(1, s.target_hits());
  22294. }
  22295. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  22296. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  22297. // go direct and must NOT carry Proxy-Authorization.
  22298. std::atomic<int> proxy_hits{0};
  22299. std::atomic<int> target_hits{0};
  22300. std::atomic<bool> target_saw_authz{false};
  22301. no_proxy_test::ScopedServer proxy_mock, target;
  22302. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22303. proxy_hits++;
  22304. res.status = 302;
  22305. res.set_header("Location", "http://127.0.0.1:" +
  22306. std::to_string(target.port()) + "/landed");
  22307. });
  22308. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22309. target_hits++;
  22310. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  22311. res.set_content("direct", "text/plain");
  22312. });
  22313. proxy_mock.listen();
  22314. target.listen();
  22315. Client cli("public.example", target.port());
  22316. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22317. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22318. cli.set_proxy_basic_auth("u", "p");
  22319. cli.set_no_proxy({"127.0.0.1"});
  22320. cli.set_follow_location(true);
  22321. auto res = cli.Get("/redir");
  22322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22323. EXPECT_GE(proxy_hits.load(), 1);
  22324. EXPECT_GE(target_hits.load(), 1);
  22325. EXPECT_FALSE(target_saw_authz.load());
  22326. }
  22327. #ifdef CPPHTTPLIB_SSL_ENABLED
  22328. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  22329. // Direct origin replying 407 must not trigger the digest retry; otherwise
  22330. // proxy creds would be sent to the (possibly hostile) origin.
  22331. std::atomic<int> target_hits{0};
  22332. std::atomic<bool> target_saw_proxy_authz{false};
  22333. no_proxy_test::ScopedServer target;
  22334. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22335. target_hits++;
  22336. if (req.has_header("Proxy-Authorization")) {
  22337. target_saw_proxy_authz = true;
  22338. }
  22339. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22340. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  22341. "nonce=\"abc\", algorithm=MD5");
  22342. });
  22343. target.listen();
  22344. // The proxy address is set to the target's port: the bypass MUST kick in;
  22345. // if it doesn't, the test still routes "via proxy" to the same server and
  22346. // the Proxy-Authorization assertion below catches the leak.
  22347. Client cli("evil.example", target.port());
  22348. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  22349. cli.set_proxy("127.0.0.1", target.port());
  22350. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22351. cli.set_no_proxy({"evil.example"});
  22352. auto res = cli.Get("/x");
  22353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22354. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22355. EXPECT_EQ(1, target_hits.load());
  22356. EXPECT_FALSE(target_saw_proxy_authz.load());
  22357. }
  22358. #endif
  22359. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  22360. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  22361. std::atomic<int> proxy_hits{0};
  22362. std::atomic<int> bypass_hits{0};
  22363. std::atomic<bool> proxy_saw_c_url{false};
  22364. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  22365. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22366. proxy_hits++;
  22367. if (req.path.find("/start") != std::string::npos) {
  22368. res.status = 302;
  22369. res.set_header("Location", "http://127.0.0.1:" +
  22370. std::to_string(bypass_server.port()) +
  22371. "/middle");
  22372. return;
  22373. }
  22374. if (req.path.find("/end") != std::string::npos) {
  22375. proxy_saw_c_url = true;
  22376. res.set_content("c-via-proxy", "text/plain");
  22377. return;
  22378. }
  22379. res.set_content("unexpected", "text/plain");
  22380. });
  22381. // public.example's "advertised" port is arbitrary (the request never lands
  22382. // there — it goes through the proxy), but use a dynamic value to stay
  22383. // friendly with sharded parallel runs.
  22384. int public_port = bypass_server.port();
  22385. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  22386. bypass_hits++;
  22387. res.status = 302;
  22388. res.set_header("Location", "http://public.example:" +
  22389. std::to_string(public_port) + "/end");
  22390. });
  22391. proxy_mock.listen();
  22392. bypass_server.listen();
  22393. Client cli("public.example", public_port);
  22394. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22395. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22396. cli.set_no_proxy({"127.0.0.1"});
  22397. cli.set_follow_location(true);
  22398. auto res = cli.Get("/start");
  22399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22400. EXPECT_EQ(StatusCode::OK_200, res->status);
  22401. EXPECT_EQ("c-via-proxy", res->body);
  22402. EXPECT_GE(proxy_hits.load(), 2);
  22403. EXPECT_GE(bypass_hits.load(), 1);
  22404. EXPECT_TRUE(proxy_saw_c_url.load());
  22405. }
  22406. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  22407. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  22408. // request reconnects to the correct endpoint.
  22409. std::atomic<int> proxy_hits{0};
  22410. std::atomic<int> target_hits{0};
  22411. no_proxy_test::ScopedServer proxy_mock, target;
  22412. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22413. proxy_hits++;
  22414. res.set_content("via-proxy", "text/plain");
  22415. });
  22416. target.svr().Get(".*", [&](const Request &, Response &res) {
  22417. target_hits++;
  22418. res.set_content("direct", "text/plain");
  22419. });
  22420. proxy_mock.listen();
  22421. target.listen();
  22422. Client cli("public.example", target.port());
  22423. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22424. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22425. cli.set_keep_alive(true);
  22426. auto res1 = cli.Get("/a");
  22427. ASSERT_TRUE(res1);
  22428. EXPECT_EQ("via-proxy", res1->body);
  22429. EXPECT_EQ(1, proxy_hits.load());
  22430. EXPECT_EQ(0, target_hits.load());
  22431. cli.set_no_proxy({"public.example"});
  22432. auto res2 = cli.Get("/b");
  22433. ASSERT_TRUE(res2);
  22434. EXPECT_EQ("direct", res2->body);
  22435. EXPECT_EQ(1, proxy_hits.load());
  22436. EXPECT_EQ(1, target_hits.load());
  22437. }
  22438. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  22439. namespace proxy_tunnel_test {
  22440. // SSLServer counterpart to no_proxy_test::ScopedServer.
  22441. class ScopedSSLServer {
  22442. public:
  22443. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  22444. port_ = svr_.bind_to_any_port("127.0.0.1");
  22445. }
  22446. ~ScopedSSLServer() {
  22447. svr_.stop();
  22448. if (th_.joinable()) { th_.join(); }
  22449. }
  22450. SSLServer &svr() { return svr_; }
  22451. int port() const { return port_; }
  22452. void listen() {
  22453. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22454. svr_.wait_until_ready();
  22455. }
  22456. private:
  22457. SSLServer svr_;
  22458. std::thread th_;
  22459. int port_ = 0;
  22460. };
  22461. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  22462. class ScopedConnectProxy {
  22463. public:
  22464. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  22465. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  22466. if (listen_fd_ < 0) { return; }
  22467. int yes = 1;
  22468. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  22469. sockaddr_in a{};
  22470. a.sin_family = AF_INET;
  22471. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22472. a.sin_port = 0;
  22473. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  22474. return;
  22475. }
  22476. socklen_t alen = sizeof(a);
  22477. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  22478. 0) {
  22479. return;
  22480. }
  22481. port_ = ntohs(a.sin_port);
  22482. if (::listen(listen_fd_, 1) != 0) { return; }
  22483. th_ = std::thread([this] { run(); });
  22484. }
  22485. ~ScopedConnectProxy() {
  22486. stop_ = true;
  22487. if (listen_fd_ >= 0) {
  22488. ::shutdown(listen_fd_, SHUT_RDWR);
  22489. ::close(listen_fd_);
  22490. }
  22491. if (th_.joinable()) { th_.join(); }
  22492. }
  22493. int port() const { return port_; }
  22494. int connect_hits() const { return connect_hits_.load(); }
  22495. // Head of the last CONNECT request, as the proxy saw it on the wire.
  22496. std::string connect_request() const {
  22497. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22498. return connect_request_;
  22499. }
  22500. private:
  22501. void run() {
  22502. while (!stop_.load()) {
  22503. fd_set rfds;
  22504. FD_ZERO(&rfds);
  22505. FD_SET(listen_fd_, &rfds);
  22506. timeval tv{0, 100 * 1000};
  22507. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  22508. if (sel <= 0) { continue; }
  22509. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  22510. if (client_fd < 0) { continue; }
  22511. std::string req;
  22512. char buf[2048];
  22513. while (req.find("\r\n\r\n") == std::string::npos) {
  22514. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  22515. if (n <= 0) { break; }
  22516. req.append(buf, static_cast<size_t>(n));
  22517. }
  22518. if (req.compare(0, 7, "CONNECT") != 0) {
  22519. ::close(client_fd);
  22520. continue;
  22521. }
  22522. connect_hits_++;
  22523. {
  22524. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22525. connect_request_ = req;
  22526. }
  22527. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  22528. ::send(client_fd, ok, std::strlen(ok), 0);
  22529. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  22530. sockaddr_in o{};
  22531. o.sin_family = AF_INET;
  22532. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22533. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  22534. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  22535. 0) {
  22536. ::close(client_fd);
  22537. ::close(origin_fd);
  22538. continue;
  22539. }
  22540. auto forward = [](int from, int to) {
  22541. char b[8192];
  22542. for (;;) {
  22543. ssize_t n = ::recv(from, b, sizeof(b), 0);
  22544. if (n <= 0) { break; }
  22545. ssize_t off = 0;
  22546. while (off < n) {
  22547. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  22548. if (s <= 0) {
  22549. off = n;
  22550. break;
  22551. }
  22552. off += s;
  22553. }
  22554. }
  22555. ::shutdown(to, SHUT_WR);
  22556. };
  22557. std::thread t1([&] { forward(client_fd, origin_fd); });
  22558. std::thread t2([&] { forward(origin_fd, client_fd); });
  22559. t1.join();
  22560. t2.join();
  22561. ::close(client_fd);
  22562. ::close(origin_fd);
  22563. }
  22564. }
  22565. int forward_port_ = -1;
  22566. int listen_fd_ = -1;
  22567. int port_ = 0;
  22568. std::thread th_;
  22569. std::atomic<bool> stop_{false};
  22570. std::atomic<int> connect_hits_{0};
  22571. mutable std::mutex connect_request_mutex_;
  22572. std::string connect_request_;
  22573. };
  22574. // Sends one request through the CONNECT proxy to the TLS origin with a
  22575. // credential configured for each hop, and checks that each credential reaches
  22576. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22577. // origin's (every header in origin_headers) on the tunnelled request.
  22578. void CredentialsStayWithTheirHop(
  22579. const std::function<void(SSLClient &)> &set_credentials,
  22580. const std::string &scheme,
  22581. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22582. std::atomic<int> origin_hits{0};
  22583. std::atomic<bool> origin_saw_proxy_authz{false};
  22584. std::atomic<bool> origin_saw_headers{false};
  22585. ScopedSSLServer origin;
  22586. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22587. origin_hits++;
  22588. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22589. origin_saw_headers =
  22590. std::all_of(origin_headers.begin(), origin_headers.end(),
  22591. [&](const std::string &h) { return req.has_header(h); });
  22592. res.set_content("ok", "text/plain");
  22593. });
  22594. origin.listen();
  22595. ScopedConnectProxy proxy(origin.port());
  22596. ASSERT_NE(0, proxy.port());
  22597. // Pinned to 127.0.0.1 for the same reason as the test below.
  22598. SSLClient cli("127.0.0.1", origin.port());
  22599. cli.enable_server_certificate_verification(false);
  22600. cli.set_proxy("127.0.0.1", proxy.port());
  22601. set_credentials(cli);
  22602. auto res = cli.Get("/x");
  22603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22604. EXPECT_EQ(StatusCode::OK_200, res->status);
  22605. EXPECT_EQ(1, origin_hits.load());
  22606. EXPECT_EQ(1, proxy.connect_hits());
  22607. EXPECT_TRUE(origin_saw_headers.load());
  22608. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22609. << "Proxy-Authorization must not be sent inside the tunnel";
  22610. auto connect_req = proxy.connect_request();
  22611. EXPECT_NE(std::string::npos,
  22612. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22613. for (const auto &h : origin_headers) {
  22614. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22615. << h << " must not be sent to the proxy on CONNECT";
  22616. }
  22617. }
  22618. } // namespace proxy_tunnel_test
  22619. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22620. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22621. [](SSLClient &cli) {
  22622. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22623. cli.set_basic_auth("origin-user", "origin-pass");
  22624. },
  22625. "Basic");
  22626. }
  22627. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22628. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22629. [](SSLClient &cli) {
  22630. cli.set_proxy_bearer_token_auth("proxy-token");
  22631. cli.set_bearer_token_auth("origin-token");
  22632. },
  22633. "Bearer");
  22634. }
  22635. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22636. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22637. [](SSLClient &cli) {
  22638. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22639. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22640. {"Cookie", "sid=origin-session"},
  22641. {"X-Api-Key", "origin-key"}});
  22642. },
  22643. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22644. }
  22645. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22646. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22647. // retry; otherwise proxy creds would be sent to the origin.
  22648. std::atomic<int> origin_hits{0};
  22649. std::atomic<bool> origin_saw_proxy_authz{false};
  22650. proxy_tunnel_test::ScopedSSLServer origin;
  22651. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22652. origin_hits++;
  22653. if (req.has_header("Proxy-Authorization")) {
  22654. origin_saw_proxy_authz = true;
  22655. }
  22656. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22657. res.set_header("Proxy-Authenticate",
  22658. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22659. "algorithm=MD5");
  22660. });
  22661. origin.listen();
  22662. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22663. ASSERT_NE(0, proxy.port());
  22664. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22665. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22666. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22667. // and answer with its own status, making this test flaky.
  22668. SSLClient cli("127.0.0.1", origin.port());
  22669. cli.enable_server_certificate_verification(false);
  22670. cli.set_proxy("127.0.0.1", proxy.port());
  22671. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22672. auto res = cli.Get("/x");
  22673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22674. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22675. EXPECT_EQ(1, origin_hits.load());
  22676. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22677. EXPECT_EQ(1, proxy.connect_hits());
  22678. }
  22679. #endif