1
0

test.cc 974 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. } // namespace tls
  69. } // namespace httplib
  70. #endif
  71. using namespace std;
  72. using namespace httplib;
  73. const char *HOST = "localhost";
  74. static int get_base_port() {
  75. const char *shard = getenv("GTEST_SHARD_INDEX");
  76. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  77. }
  78. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  79. // New standalone tests MUST use svr.bind_to_any_port() instead.
  80. const int PORT = get_base_port();
  81. const string LONG_QUERY_VALUE = string(25000, '@');
  82. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  83. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  84. const string TOO_LONG_QUERY_URL =
  85. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  86. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  87. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  88. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  89. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  90. return file.name == key;
  91. });
  92. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  93. return *it;
  94. #else
  95. if (it != items.end()) { return *it; }
  96. throw std::runtime_error("invalid multipart form data name error");
  97. #endif
  98. }
  99. static void read_file(const std::string &path, std::string &out) {
  100. std::ifstream fs(path, std::ios_base::binary);
  101. if (!fs) {
  102. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  103. return;
  104. #else
  105. throw std::runtime_error("File not found: " + path);
  106. #endif
  107. }
  108. fs.seekg(0, std::ios_base::end);
  109. auto size = fs.tellg();
  110. fs.seekg(0);
  111. out.resize(static_cast<size_t>(size));
  112. fs.read(&out[0], static_cast<std::streamsize>(size));
  113. }
  114. class UnixSocketTest : public ::testing::Test {
  115. protected:
  116. void TearDown() override { std::remove(pathname_.c_str()); }
  117. void client_GET(const std::string &addr) {
  118. httplib::Client cli{addr};
  119. cli.set_address_family(AF_UNIX);
  120. ASSERT_TRUE(cli.is_valid());
  121. const auto &result = cli.Get(pattern_);
  122. ASSERT_TRUE(result) << "error: " << result.error();
  123. const auto &resp = result.value();
  124. EXPECT_EQ(resp.status, StatusCode::OK_200);
  125. EXPECT_EQ(resp.body, content_);
  126. }
  127. static std::string make_sock_path() {
  128. const char *shard = getenv("GTEST_SHARD_INDEX");
  129. return shard ? std::string("./httplib-server-") + shard + ".sock"
  130. : "./httplib-server.sock";
  131. }
  132. const std::string pathname_{make_sock_path()};
  133. const std::string pattern_{"/hi"};
  134. const std::string content_{"Hello World!"};
  135. };
  136. TEST_F(UnixSocketTest, pathname) {
  137. httplib::Server svr;
  138. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  139. res.set_content(content_, "text/plain");
  140. });
  141. std::thread t{[&] {
  142. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  143. }};
  144. auto se = detail::scope_exit([&] {
  145. svr.stop();
  146. t.join();
  147. ASSERT_FALSE(svr.is_running());
  148. });
  149. svr.wait_until_ready();
  150. ASSERT_TRUE(svr.is_running());
  151. client_GET(pathname_);
  152. // ".//x.sock", which is not taken for a URL
  153. client_GET("./" + pathname_.substr(1));
  154. }
  155. #if defined(__linux__) || \
  156. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  157. TEST_F(UnixSocketTest, PeerPid) {
  158. httplib::Server svr;
  159. std::string remote_port_val;
  160. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  161. res.set_content(content_, "text/plain");
  162. remote_port_val = std::to_string(req.remote_port);
  163. });
  164. std::thread t{[&] {
  165. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  166. }};
  167. auto se = detail::scope_exit([&] {
  168. svr.stop();
  169. t.join();
  170. ASSERT_FALSE(svr.is_running());
  171. });
  172. svr.wait_until_ready();
  173. ASSERT_TRUE(svr.is_running());
  174. client_GET(pathname_);
  175. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  176. }
  177. #endif
  178. #ifdef __linux__
  179. TEST_F(UnixSocketTest, abstract) {
  180. constexpr char svr_path[]{"\x00httplib-server.sock"};
  181. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  182. httplib::Server svr;
  183. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. client_GET(abstract_addr);
  197. }
  198. #endif
  199. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  200. httplib::Server svr;
  201. std::string received_host_header;
  202. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  203. // Capture the Host header sent by the client
  204. auto host_iter = req.headers.find("Host");
  205. if (host_iter != req.headers.end()) {
  206. received_host_header = host_iter->second;
  207. }
  208. res.set_content(content_, "text/plain");
  209. });
  210. std::thread t{[&] {
  211. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  212. }};
  213. auto se = detail::scope_exit([&] {
  214. svr.stop();
  215. t.join();
  216. ASSERT_FALSE(svr.is_running());
  217. });
  218. svr.wait_until_ready();
  219. ASSERT_TRUE(svr.is_running());
  220. // Test that Host header is automatically set to "localhost" for Unix socket
  221. // connections
  222. httplib::Client cli{pathname_};
  223. cli.set_address_family(AF_UNIX);
  224. ASSERT_TRUE(cli.is_valid());
  225. const auto &result = cli.Get(pattern_);
  226. ASSERT_TRUE(result) << "error: " << result.error();
  227. const auto &resp = result.value();
  228. EXPECT_EQ(resp.status, StatusCode::OK_200);
  229. EXPECT_EQ(resp.body, content_);
  230. // Verify that Host header was automatically set to "localhost"
  231. EXPECT_EQ(received_host_header, "localhost");
  232. }
  233. #ifndef _WIN32
  234. TEST(SocketStream, wait_writable_UNIX) {
  235. int fds[2];
  236. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  237. const auto asSocketStream = [&](socket_t fd,
  238. std::function<bool(Stream &)> func) {
  239. return detail::process_client_socket(
  240. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  241. };
  242. asSocketStream(fds[0], [&](Stream &s0) {
  243. EXPECT_EQ(s0.socket(), fds[0]);
  244. EXPECT_TRUE(s0.wait_writable());
  245. EXPECT_TRUE(s0.is_peer_alive());
  246. EXPECT_EQ(0, close(fds[1]));
  247. EXPECT_FALSE(s0.is_peer_alive());
  248. return true;
  249. });
  250. EXPECT_EQ(0, close(fds[0]));
  251. }
  252. TEST(SocketStream, wait_writable_INET) {
  253. sockaddr_in addr;
  254. memset(&addr, 0, sizeof(addr));
  255. addr.sin_family = AF_INET;
  256. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  257. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  258. int disconnected_svr_sock = -1;
  259. std::thread svr{[&] {
  260. const int s = socket(AF_INET, SOCK_STREAM, 0);
  261. ASSERT_LE(0, s);
  262. // PORT + 1 is shared with the SSL redirect tests and with
  263. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  264. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  265. // because that happens on a worker thread the ASSERT does not stop the
  266. // test: it runs on and fails at the disconnected_svr_sock check instead.
  267. default_socket_options(s);
  268. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  269. ASSERT_EQ(0, listen(s, 1));
  270. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  271. ASSERT_EQ(0, close(s));
  272. }};
  273. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  274. std::thread cli{[&] {
  275. const int s = socket(AF_INET, SOCK_STREAM, 0);
  276. ASSERT_LE(0, s);
  277. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  278. ASSERT_EQ(0, close(s));
  279. }};
  280. cli.join();
  281. svr.join();
  282. ASSERT_NE(disconnected_svr_sock, -1);
  283. const auto asSocketStream = [&](socket_t fd,
  284. std::function<bool(Stream &)> func) {
  285. return detail::process_client_socket(
  286. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  287. };
  288. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  289. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  290. // wait_writable() returns true because select_write() only checks if the
  291. // send buffer has space. Peer disconnection is detected later by send().
  292. EXPECT_TRUE(ss.wait_writable());
  293. return true;
  294. });
  295. ASSERT_EQ(0, close(disconnected_svr_sock));
  296. }
  297. #endif // #ifndef _WIN32
  298. TEST(SetSocketOptTest, TcpNoDelay) {
  299. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  300. ASSERT_NE(sock, INVALID_SOCKET);
  301. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  302. int val = 0;
  303. socklen_t len = sizeof(val);
  304. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  305. reinterpret_cast<char *>(&val), &len));
  306. EXPECT_NE(val, 0);
  307. detail::close_socket(sock);
  308. }
  309. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  310. // accept() reports failures through WSAGetLastError() on Windows and through
  311. // errno everywhere else. Asking the wrong one is what made the accept loop
  312. // treat every recoverable failure as fatal on Windows.
  313. struct Classification {
  314. bool resource;
  315. bool transient;
  316. };
  317. auto classify = [](int err) {
  318. #ifdef _WIN32
  319. WSASetLastError(err);
  320. #else
  321. errno = err;
  322. #endif
  323. // Read both before asserting: an assertion may clobber the error slot.
  324. Classification c;
  325. c.resource = detail::is_accept_resource_error();
  326. c.transient = detail::is_accept_transient_error();
  327. return c;
  328. };
  329. #ifdef _WIN32
  330. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  331. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  332. WSAECONNRESET, WSAECONNABORTED};
  333. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  334. #else
  335. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  336. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  337. ECONNABORTED};
  338. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  339. #endif
  340. for (auto err : resource_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.resource) << "error " << err;
  343. EXPECT_FALSE(c.transient) << "error " << err;
  344. }
  345. for (auto err : transient_errors) {
  346. const auto c = classify(err);
  347. EXPECT_TRUE(c.transient) << "error " << err;
  348. EXPECT_FALSE(c.resource) << "error " << err;
  349. }
  350. for (auto err : fatal_errors) {
  351. const auto c = classify(err);
  352. EXPECT_FALSE(c.resource) << "error " << err;
  353. EXPECT_FALSE(c.transient) << "error " << err;
  354. }
  355. #ifdef _WIN32
  356. WSASetLastError(0);
  357. #else
  358. errno = 0;
  359. #endif
  360. }
  361. TEST(ClientTest, MoveConstructible) {
  362. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  363. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  364. }
  365. TEST(ClientTest, MoveAssignable) {
  366. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  367. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  368. }
  369. #ifdef _WIN32
  370. TEST(StartupTest, WSAStartup) {
  371. WSADATA wsaData;
  372. int ret = WSAStartup(0x0002, &wsaData);
  373. ASSERT_EQ(0, ret);
  374. }
  375. #endif
  376. TEST(DecodePathTest, PercentCharacter) {
  377. EXPECT_EQ(
  378. decode_path_component(
  379. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  380. U8("descrip=Gastos áéíóúñÑ 6"));
  381. }
  382. TEST(DecodePathTest, PercentCharacterNUL) {
  383. string expected;
  384. expected.push_back('x');
  385. expected.push_back('\0');
  386. expected.push_back('x');
  387. EXPECT_EQ(decode_path_component("x%00x"), expected);
  388. }
  389. TEST(DecodePathTest, UnicodeEncoding) {
  390. // %u0041 = 'A' (1-byte UTF-8)
  391. EXPECT_EQ("A", decode_path_component("%u0041"));
  392. // %u00E9 = 'é' (2-byte UTF-8)
  393. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  394. // %u3042 = 'あ' (3-byte UTF-8)
  395. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  396. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  397. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  398. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  399. // neighbours)
  400. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  401. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  402. }
  403. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  404. // A sign or whitespace inside the two-character escape window must not be
  405. // accepted as a valid percent-encoding; the sequence is passed through
  406. // literally, matching decode_uri_component / decode_path_component.
  407. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  408. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  409. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  410. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  411. // Well-formed escapes still decode.
  412. EXPECT_EQ("-", decode_query_component("%2D", false));
  413. EXPECT_EQ("A", decode_query_component("%41", false));
  414. }
  415. TEST(SanitizeFilenameTest, VariousPatterns) {
  416. // Path traversal
  417. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  419. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  420. // Normal and edge cases
  421. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  422. EXPECT_EQ("filename.txt",
  423. httplib::sanitize_filename("/path/to/filename.txt"));
  424. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  425. EXPECT_EQ("", httplib::sanitize_filename(".."));
  426. EXPECT_EQ("", httplib::sanitize_filename(""));
  427. // Null bytes stripped
  428. EXPECT_EQ("safe.txt",
  429. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  430. // Whitespace-only rejected
  431. EXPECT_EQ("", httplib::sanitize_filename(" "));
  432. }
  433. // Forward declaration (see the base64_encode note below): split builds move the
  434. // definition into httplib.cc, so re-declaring it here lets the test link.
  435. namespace httplib {
  436. namespace detail {
  437. bool is_chunked_transfer_encoding(const Headers &headers);
  438. } // namespace detail
  439. } // namespace httplib
  440. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  441. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  442. auto make = [](std::initializer_list<const char *> lines) {
  443. Headers h;
  444. for (auto te : lines) {
  445. if (te) { h.emplace("Transfer-Encoding", te); }
  446. }
  447. return h;
  448. };
  449. // Sole coding, matched case-insensitively.
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  453. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  454. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  457. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  462. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  463. // were received, into one list. Headers preserves that order, so the answer
  464. // is decided by the last coding of the last line and the order the lines
  465. // arrived in is significant.
  466. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  467. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  469. // The split can fall anywhere in the list.
  470. EXPECT_TRUE(
  471. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  472. EXPECT_FALSE(
  473. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  474. // A trailing line naming no coding leaves the list ending in nothing, so it
  475. // must not inherit the chunked from the line before it.
  476. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  477. }
  478. // Forward declarations (see the base64_encode note below).
  479. namespace httplib {
  480. namespace detail {
  481. bool parse_status_line(const char *line, std::string &version, int &status,
  482. std::string &reason);
  483. std::string file_extension(const std::string &path);
  484. std::string
  485. find_content_type(const std::string &path,
  486. const std::map<std::string, std::string> &user_data,
  487. const std::string &default_content_type);
  488. bool can_compress_content_type(const std::string &content_type);
  489. bool is_prohibited_header_name(const std::string &name);
  490. #ifdef CPPHTTPLIB_SSL_ENABLED
  491. bool match_hostname(const std::string &pattern, const std::string &hostname);
  492. #endif
  493. } // namespace detail
  494. } // namespace httplib
  495. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  496. struct {
  497. const char *line;
  498. const char *version;
  499. int status;
  500. const char *reason;
  501. } cases[] = {
  502. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  503. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  504. // The reason phrase may be empty, or left out along with its space.
  505. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  506. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  507. };
  508. for (const auto &c : cases) {
  509. std::string version;
  510. int status = 0;
  511. std::string reason = "unset";
  512. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  513. << c.line;
  514. EXPECT_EQ(c.version, version);
  515. EXPECT_EQ(c.status, status);
  516. EXPECT_EQ(c.reason, reason);
  517. }
  518. }
  519. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  520. const char *lines[] = {
  521. "HTTP/2 200 OK\r\n",
  522. "HTTP/1.2 200 OK\r\n",
  523. "HTTP/1.1 20 OK\r\n",
  524. "HTTP/1.1 2000 OK\r\n",
  525. "HTTP/1.1 2x0 OK\r\n",
  526. "HTTP/1.1 200 OK\r\n",
  527. "HTTP/1.1 200OK\r\n",
  528. "HTTP/1.1 200 O\rK\r\n",
  529. "HTTP/1.1 200 OK",
  530. "HTTP/1.1 200 OK\r\nX",
  531. "",
  532. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  533. "HTTP/1.1 200 OK\n",
  534. #endif
  535. };
  536. for (auto line : lines) {
  537. std::string version;
  538. int status = 0;
  539. std::string reason;
  540. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  541. << line;
  542. }
  543. }
  544. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  545. // Long enough to overflow the stack when matched with std::regex.
  546. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  547. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  548. std::string version;
  549. int status = 0;
  550. std::string reason;
  551. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  552. EXPECT_EQ(200, status);
  553. EXPECT_EQ(long_reason, reason);
  554. }
  555. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  556. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  557. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  558. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  559. EXPECT_EQ("", detail::file_extension("noext"));
  560. EXPECT_EQ("", detail::file_extension("a."));
  561. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  562. EXPECT_EQ("", detail::file_extension("a.b-c"));
  563. // Long enough to overflow the stack when matched with std::regex.
  564. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  565. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  566. }
  567. #ifdef CPPHTTPLIB_SSL_ENABLED
  568. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  569. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  570. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  572. // A wildcard needs two labels after it, in the leftmost label only
  573. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  574. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  575. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  576. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  577. EXPECT_FALSE(
  578. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  579. // No name may have an empty label
  580. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  581. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  582. }
  583. #endif
  584. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  585. detail::case_ignore::hash hash;
  586. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  587. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  588. // Long enough to overflow the stack if hashed one call per character.
  589. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  590. }
  591. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  592. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  593. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  594. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  595. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  596. // Same 26-bit hash as html, svg and js.
  597. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  598. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  600. }
  601. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  602. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  603. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  604. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  605. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  606. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  607. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  608. // Same 26-bit hash as application/json.
  609. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  610. }
  611. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  612. Request req;
  613. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  614. EXPECT_TRUE(req.is_multipart_form_data());
  615. std::string boundary;
  616. EXPECT_TRUE(detail::parse_multipart_boundary(
  617. req.get_header_value("Content-Type"), boundary));
  618. EXPECT_EQ("x", boundary);
  619. }
  620. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  621. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  622. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  623. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  624. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  625. // Same 26-bit hash as REMOTE_ADDR.
  626. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  627. }
  628. // Forward declaration: in split builds split.py strips `inline` and moves the
  629. // definition into httplib.cc, so detail::base64_encode is not visible from the
  630. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  631. // in both header-only and split builds.
  632. namespace httplib {
  633. namespace detail {
  634. std::string base64_encode(const std::string &in);
  635. } // namespace detail
  636. } // namespace httplib
  637. TEST(Base64EncodeTest, KnownAnswers) {
  638. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  639. // where the accumulator's top bit is already set before the next shift.
  640. EXPECT_EQ("", detail::base64_encode(""));
  641. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  642. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  643. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  644. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  645. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  646. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  647. // High bytes keep the top bit set across several rounds.
  648. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  649. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  650. }
  651. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  652. string unescapedCharacters = "-_.!~*'()";
  653. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  654. }
  655. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  656. string reservedCharacters = ";,/?:@&=+$";
  657. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  658. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  659. }
  660. TEST(ClientQueryOrder, PreserveOrder) {
  661. // This test reproduces Issue #2259: client may reorder query parameters
  662. // when sending a GET request. The expected behavior is that the client
  663. // preserves the original query string order when the caller supplied it
  664. // as part of the path.
  665. Server svr;
  666. svr.Get("/", [&](const Request &req, Response &res) {
  667. // Echo back the raw target so the test can assert ordering
  668. res.set_content(req.target, "text/plain");
  669. });
  670. std::thread t{[&] { svr.listen(HOST, PORT); }};
  671. auto se = detail::scope_exit([&] {
  672. svr.stop();
  673. t.join();
  674. ASSERT_FALSE(svr.is_running());
  675. });
  676. svr.wait_until_ready();
  677. Client cli(HOST, PORT);
  678. ASSERT_TRUE(cli.is_valid());
  679. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  680. auto res = cli.Get(original);
  681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  682. // Expect the echoed target to exactly match the original path (order
  683. // preserved)
  684. EXPECT_EQ(res->body, original);
  685. }
  686. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  687. string chineseCharacters = U8("中国語");
  688. string russianCharacters = U8("дом");
  689. string brazilianCharacters = U8("óculos");
  690. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  691. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  692. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  693. "%D0%B4%D0%BE%D0%BC");
  694. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  695. }
  696. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  697. string unescapedCharacters = "-_.!~*'()";
  698. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  699. }
  700. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  701. string reservedCharacters = ";,/?:@&=+$";
  702. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  703. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  704. }
  705. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  706. string chineseCharacters = U8("中国語");
  707. string russianCharacters = U8("дом");
  708. string brazilianCharacters = U8("óculos");
  709. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  710. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  711. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  712. "%D0%B4%D0%BE%D0%BC");
  713. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  714. }
  715. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  716. // Issue #2082 use case: encoding path component with ampersand
  717. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  718. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  719. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  720. }
  721. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  722. string unescapedCharacters = "-_.!~*'()";
  723. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  724. }
  725. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  726. string reservedCharacters = ";,/?:@&=+$#";
  727. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  728. }
  729. TEST(EncodeUriTest, TestUTF8Characters) {
  730. string chineseCharacters = U8("中国語");
  731. string russianCharacters = U8("дом");
  732. string brazilianCharacters = U8("óculos");
  733. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  734. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  735. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  736. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  737. }
  738. TEST(EncodeUriTest, TestCompleteUri) {
  739. string uri =
  740. "https://example.com/path/to/resource?query=value&param=test#fragment";
  741. EXPECT_EQ(
  742. httplib::encode_uri(uri),
  743. "https://example.com/path/to/resource?query=value&param=test#fragment");
  744. }
  745. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  746. string uri =
  747. "https://example.com/path with spaces/file name.html?q=hello world";
  748. EXPECT_EQ(httplib::encode_uri(uri),
  749. "https://example.com/path%20with%20spaces/"
  750. "file%20name.html?q=hello%20world");
  751. }
  752. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  753. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  754. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  755. }
  756. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  757. string unescapedCharacters = "-_.!~*'()";
  758. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  759. }
  760. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  761. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  762. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  763. string encodedBrazilian = "%C3%B3culos";
  764. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  765. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  767. }
  768. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  769. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  770. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  771. "Piri Tommy Villiers - on & on");
  772. }
  773. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  774. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  775. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  776. }
  777. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  778. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  779. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  780. }
  781. TEST(DecodeUriTest, TestUTF8Characters) {
  782. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  783. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  784. string encodedBrazilian = "%C3%B3culos";
  785. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  786. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  787. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  788. }
  789. TEST(DecodeUriTest, TestCompleteUri) {
  790. string encodedUri = "https://example.com/path%20with%20spaces/"
  791. "file%20name.html?q=hello%20world";
  792. EXPECT_EQ(
  793. httplib::decode_uri(encodedUri),
  794. "https://example.com/path with spaces/file name.html?q=hello world");
  795. }
  796. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  797. string original =
  798. "https://example.com/path with spaces/file name.html?q=hello world";
  799. string encoded = httplib::encode_uri(original);
  800. string decoded = httplib::decode_uri(encoded);
  801. EXPECT_EQ(decoded, original);
  802. }
  803. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  804. // decode_uri is the inverse of encode_uri: an escaped reserved character
  805. // stays encoded so it is not promoted into a real delimiter, while
  806. // non-reserved escapes still decode (like JS decodeURI).
  807. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  808. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  809. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  810. "%3F%3A%40%26%3D%2B%24%2C%3B");
  811. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  812. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  813. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  814. "http://example.com/a%2Fb");
  815. // decode_uri_component still decodes the reserved character.
  816. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  817. }
  818. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  819. string original = "Piri Tommy Villiers - on & on";
  820. string encoded = httplib::encode_uri_component(original);
  821. string decoded = httplib::decode_uri_component(encoded);
  822. EXPECT_EQ(decoded, original);
  823. }
  824. TEST(TrimTests, TrimStringTests) {
  825. EXPECT_EQ("abc", detail::trim_copy("abc"));
  826. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  827. EXPECT_TRUE(detail::trim_copy("").empty());
  828. }
  829. TEST(AsciiTest, LocaleIndependentClassification) {
  830. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  831. // which consult the global C locale: std::isalnum(0xC5) can return true
  832. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  833. // helpers must classify every byte by the ASCII grammar alone.
  834. for (int i = 0; i < 256; i++) {
  835. auto c = static_cast<char>(i);
  836. auto is_digit = i >= '0' && i <= '9';
  837. auto is_upper = i >= 'A' && i <= 'Z';
  838. auto is_lower = i >= 'a' && i <= 'z';
  839. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  840. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  841. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  842. << "byte " << i;
  843. }
  844. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  845. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  846. // Non-ASCII bytes must be percent-encoded, never passed through as
  847. // alphanumeric.
  848. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  849. }
  850. TEST(FromCharsTest, Double) {
  851. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  852. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  853. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  854. auto parse = [](const std::string &s, double &v) {
  855. return detail::from_chars(s.data(), s.data() + s.size(), v);
  856. };
  857. double v = -1.0;
  858. // Representative quality values.
  859. EXPECT_EQ(parse("0", v).ec, std::errc{});
  860. EXPECT_DOUBLE_EQ(v, 0.0);
  861. EXPECT_EQ(parse("1", v).ec, std::errc{});
  862. EXPECT_DOUBLE_EQ(v, 1.0);
  863. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.8);
  865. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 0.001);
  867. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 1.0);
  869. // A missing integer or fractional part is tolerated.
  870. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  871. EXPECT_DOUBLE_EQ(v, 0.5);
  872. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 5.0);
  874. // Values outside [0, 1] still parse; the caller range-checks them.
  875. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  876. EXPECT_DOUBLE_EQ(v, 123.456);
  877. // Stops at the first byte that is not part of the number and reports where.
  878. std::string trailing = "0.9, text/html";
  879. auto r = parse(trailing, v);
  880. EXPECT_EQ(r.ec, std::errc{});
  881. EXPECT_DOUBLE_EQ(v, 0.9);
  882. EXPECT_EQ(*r.ptr, ',');
  883. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  884. // outright, and an 'e'/'E' simply ends the number.
  885. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  886. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  887. std::string exp_input = "1.5e3";
  888. r = parse(exp_input, v);
  889. EXPECT_EQ(r.ec, std::errc{});
  890. EXPECT_DOUBLE_EQ(v, 1.5);
  891. EXPECT_EQ(*r.ptr, 'e');
  892. // Invalid inputs.
  893. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  898. // Pathological but well-formed inputs must stay bounded (no overflow, no
  899. // out-of-bounds table access) and stay within [0, 1] for the caller.
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  901. std::errc{});
  902. EXPECT_DOUBLE_EQ(v, 0.0);
  903. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  904. std::errc{});
  905. EXPECT_GE(v, 0.0);
  906. EXPECT_LE(v, 1.0);
  907. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  908. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  909. }
  910. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  911. // Simple case without quality values
  912. std::vector<std::string> result1;
  913. EXPECT_TRUE(detail::parse_accept_header(
  914. "text/html,application/json,text/plain", result1));
  915. EXPECT_EQ(result1.size(), 3U);
  916. EXPECT_EQ(result1[0], "text/html");
  917. EXPECT_EQ(result1[1], "application/json");
  918. EXPECT_EQ(result1[2], "text/plain");
  919. // With quality values
  920. std::vector<std::string> result2;
  921. EXPECT_TRUE(detail::parse_accept_header(
  922. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  923. EXPECT_EQ(result2.size(), 3U);
  924. EXPECT_EQ(result2[0], "application/json"); // highest q value
  925. EXPECT_EQ(result2[1], "text/html");
  926. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  927. }
  928. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  929. // Mixed with and without quality values
  930. std::vector<std::string> result;
  931. EXPECT_TRUE(detail::parse_accept_header(
  932. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  933. EXPECT_EQ(result.size(), 3U);
  934. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  935. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  936. EXPECT_EQ(result[2], "application/json"); // q=0.5
  937. }
  938. TEST(ParseAcceptHeaderTest, EdgeCases) {
  939. // Empty header
  940. std::vector<std::string> empty_result;
  941. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  942. EXPECT_TRUE(empty_result.empty());
  943. // Single type
  944. std::vector<std::string> single_result;
  945. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  946. EXPECT_EQ(single_result.size(), 1U);
  947. EXPECT_EQ(single_result[0], "application/json");
  948. // Wildcard types
  949. std::vector<std::string> wildcard_result;
  950. EXPECT_TRUE(detail::parse_accept_header(
  951. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  952. EXPECT_EQ(wildcard_result.size(), 3U);
  953. EXPECT_EQ(wildcard_result[0], "application/json");
  954. EXPECT_EQ(wildcard_result[1], "text/*");
  955. EXPECT_EQ(wildcard_result[2], "*/*");
  956. }
  957. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  958. // Common browser Accept header
  959. std::vector<std::string> browser_result;
  960. EXPECT_TRUE(
  961. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  962. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  963. browser_result));
  964. EXPECT_EQ(browser_result.size(), 6U);
  965. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  970. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  971. // API client header
  972. std::vector<std::string> api_result;
  973. EXPECT_TRUE(detail::parse_accept_header(
  974. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  975. api_result));
  976. EXPECT_EQ(api_result.size(), 3U);
  977. EXPECT_EQ(api_result[0], "application/json");
  978. EXPECT_EQ(api_result[1], "application/xml");
  979. EXPECT_EQ(api_result[2], "text/plain");
  980. }
  981. TEST(ParseAcceptHeaderTest, SpecialCases) {
  982. // Quality value with 3 decimal places
  983. std::vector<std::string> decimal_result;
  984. EXPECT_TRUE(detail::parse_accept_header(
  985. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  986. EXPECT_EQ(decimal_result.size(), 2U);
  987. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  988. EXPECT_EQ(decimal_result[1], "text/html");
  989. // Zero quality (should still be included but with lowest priority)
  990. std::vector<std::string> zero_q_result;
  991. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  992. zero_q_result));
  993. EXPECT_EQ(zero_q_result.size(), 2U);
  994. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  995. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  996. // No spaces around commas
  997. std::vector<std::string> no_space_result;
  998. EXPECT_TRUE(detail::parse_accept_header(
  999. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1000. no_space_result));
  1001. EXPECT_EQ(no_space_result.size(), 3U);
  1002. EXPECT_EQ(no_space_result[0], "text/html");
  1003. EXPECT_EQ(no_space_result[1], "application/json");
  1004. EXPECT_EQ(no_space_result[2], "text/plain");
  1005. }
  1006. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1007. // Quality values always use '.' as the decimal separator, so parsing must
  1008. // not depend on the process locale. An embedding application may have
  1009. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1010. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1011. std::string saved = cur ? cur : "C";
  1012. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1013. "fr_FR.UTF-8"};
  1014. bool switched = false;
  1015. for (const auto loc : comma_locales) {
  1016. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1017. std::localeconv()->decimal_point[0] == ',') {
  1018. switched = true;
  1019. break;
  1020. }
  1021. }
  1022. if (!switched) {
  1023. std::setlocale(LC_NUMERIC, saved.c_str());
  1024. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1025. }
  1026. // The higher-weighted type appears later in the list, so a correct parse
  1027. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1028. // sensitive parse reads both weights as 0 and leaves the original order.
  1029. std::vector<std::string> result;
  1030. EXPECT_TRUE(detail::parse_accept_header(
  1031. "application/json;q=0.1,text/html;q=0.9", result));
  1032. ASSERT_EQ(result.size(), 2U);
  1033. EXPECT_EQ(result[0], "text/html");
  1034. EXPECT_EQ(result[1], "application/json");
  1035. std::setlocale(LC_NUMERIC, saved.c_str());
  1036. }
  1037. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1038. std::vector<std::string> result;
  1039. // Invalid quality value (> 1.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1042. // Invalid quality value (< 0.0)
  1043. EXPECT_FALSE(
  1044. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1045. // Invalid quality value (not a number)
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=invalid,application/json", result));
  1048. // A valid numeric prefix does not make the entire quality value valid.
  1049. EXPECT_FALSE(detail::parse_accept_header(
  1050. "text/html;q=0.5junk,application/json", result));
  1051. // Empty quality value
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("text/html;q=,application/json", result));
  1054. // Invalid media type format (no slash and not wildcard)
  1055. EXPECT_FALSE(
  1056. detail::parse_accept_header("invalidtype,application/json", result));
  1057. // Valid cases should still work
  1058. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1059. EXPECT_EQ(result.size(), 1U);
  1060. EXPECT_EQ(result[0], "*/*");
  1061. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "*");
  1064. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1065. EXPECT_EQ(result.size(), 1U);
  1066. EXPECT_EQ(result[0], "text/*");
  1067. }
  1068. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1069. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1070. // and must not be answered with 400 Bad Request.
  1071. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1072. struct {
  1073. const char *value;
  1074. std::vector<std::string> expected;
  1075. } cases[] = {
  1076. {",application/json", {"application/json"}},
  1077. {"text/html,", {"text/html"}},
  1078. {"text/html,,*/*", {"text/html", "*/*"}},
  1079. // An empty element may be spelled with whitespace in it
  1080. {"text/html, , application/json", {"text/html", "application/json"}},
  1081. // Nothing but empty elements is an empty list, which means the same
  1082. // thing as no Accept header at all
  1083. {",,,", {}},
  1084. // Quality values still apply across ignored empty elements
  1085. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1086. };
  1087. for (const auto &c : cases) {
  1088. std::vector<std::string> result;
  1089. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1090. << "value: " << c.value;
  1091. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1092. }
  1093. // An invalid entry is still rejected when empty elements surround it
  1094. std::vector<std::string> result;
  1095. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1096. }
  1097. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1098. // or ';' inside one does not end the list element or the parameter. Section
  1099. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1100. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1101. struct {
  1102. const char *value;
  1103. std::vector<std::string> expected;
  1104. } cases[] = {
  1105. {"text/html;profile=\"a,b\",application/json",
  1106. {"text/html", "application/json"}},
  1107. // A "q=" inside a quoted value is not the weight
  1108. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1109. {"text/html", "application/json"}},
  1110. // The weight after a quoted value still applies
  1111. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1112. {"application/json", "text/html"}},
  1113. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1114. {"application/json", "text/html"}},
  1115. {"text/html;profile=\"a\\\"b\",application/json",
  1116. {"text/html", "application/json"}},
  1117. // An escaped backslash does not escape the '"' after it
  1118. {"text/html;profile=\"a\\\\\",application/json",
  1119. {"text/html", "application/json"}},
  1120. };
  1121. for (const auto &c : cases) {
  1122. std::vector<std::string> result;
  1123. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1124. << "value: " << c.value;
  1125. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1126. }
  1127. }
  1128. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1129. Server svr;
  1130. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1131. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1132. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1133. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1134. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1135. res.set_content("ok", "text/plain");
  1136. });
  1137. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1138. EXPECT_TRUE(false);
  1139. res.set_content("bad request", "text/plain");
  1140. });
  1141. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1142. auto se = detail::scope_exit([&] {
  1143. svr.stop();
  1144. listen_thread.join();
  1145. ASSERT_FALSE(svr.is_running());
  1146. });
  1147. svr.wait_until_ready();
  1148. Client cli("localhost", PORT);
  1149. {
  1150. auto res = cli.Get(
  1151. "/accept_ok",
  1152. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1154. EXPECT_EQ(StatusCode::OK_200, res->status);
  1155. }
  1156. {
  1157. auto res = cli.Get("/accept_bad_request",
  1158. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1160. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1161. }
  1162. }
  1163. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1164. Server svr;
  1165. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1166. res.set_content("ok", "text/plain");
  1167. });
  1168. std::atomic<int> start_count{0};
  1169. std::atomic<bool> running_when_called{false};
  1170. svr.set_start_handler([&]() {
  1171. running_when_called = svr.is_running();
  1172. start_count++;
  1173. });
  1174. auto port = svr.bind_to_any_port(HOST);
  1175. std::thread t([&]() { svr.listen_after_bind(); });
  1176. auto se = detail::scope_exit([&] {
  1177. svr.stop();
  1178. t.join();
  1179. ASSERT_FALSE(svr.is_running());
  1180. });
  1181. svr.wait_until_ready();
  1182. // A successful request proves the accept loop is running, which the start
  1183. // handler precedes; so by now the handler must have run exactly once.
  1184. Client cli(HOST, port);
  1185. cli.set_connection_timeout(std::chrono::seconds(5));
  1186. auto res = cli.Get("/");
  1187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1188. EXPECT_EQ(StatusCode::OK_200, res->status);
  1189. EXPECT_EQ(1, start_count.load());
  1190. EXPECT_TRUE(running_when_called.load());
  1191. }
  1192. TEST(DivideTest, DivideStringTests) {
  1193. auto divide = [](const std::string &str, char d) {
  1194. std::string lhs;
  1195. std::string rhs;
  1196. detail::divide(str, d,
  1197. [&](const char *lhs_data, std::size_t lhs_size,
  1198. const char *rhs_data, std::size_t rhs_size) {
  1199. lhs.assign(lhs_data, lhs_size);
  1200. rhs.assign(rhs_data, rhs_size);
  1201. });
  1202. return std::make_pair(std::move(lhs), std::move(rhs));
  1203. };
  1204. {
  1205. const auto res = divide("", '=');
  1206. EXPECT_EQ(res.first, "");
  1207. EXPECT_EQ(res.second, "");
  1208. }
  1209. {
  1210. const auto res = divide("=", '=');
  1211. EXPECT_EQ(res.first, "");
  1212. EXPECT_EQ(res.second, "");
  1213. }
  1214. {
  1215. const auto res = divide(" ", '=');
  1216. EXPECT_EQ(res.first, " ");
  1217. EXPECT_EQ(res.second, "");
  1218. }
  1219. {
  1220. const auto res = divide("a", '=');
  1221. EXPECT_EQ(res.first, "a");
  1222. EXPECT_EQ(res.second, "");
  1223. }
  1224. {
  1225. const auto res = divide("a=", '=');
  1226. EXPECT_EQ(res.first, "a");
  1227. EXPECT_EQ(res.second, "");
  1228. }
  1229. {
  1230. const auto res = divide("=b", '=');
  1231. EXPECT_EQ(res.first, "");
  1232. EXPECT_EQ(res.second, "b");
  1233. }
  1234. {
  1235. const auto res = divide("a=b", '=');
  1236. EXPECT_EQ(res.first, "a");
  1237. EXPECT_EQ(res.second, "b");
  1238. }
  1239. {
  1240. const auto res = divide("a=b=", '=');
  1241. EXPECT_EQ(res.first, "a");
  1242. EXPECT_EQ(res.second, "b=");
  1243. }
  1244. {
  1245. const auto res = divide("a=b=c", '=');
  1246. EXPECT_EQ(res.first, "a");
  1247. EXPECT_EQ(res.second, "b=c");
  1248. }
  1249. }
  1250. TEST(SplitTest, ParseQueryString) {
  1251. string s = "key1=val1&key2=val2&key3=val3";
  1252. Params dic;
  1253. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1254. [&](const char *b, const char *e) {
  1255. string key, val;
  1256. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1257. if (key.empty()) {
  1258. key.assign(b2, e2);
  1259. } else {
  1260. val.assign(b2, e2);
  1261. }
  1262. });
  1263. dic.emplace(key, val);
  1264. });
  1265. EXPECT_EQ("val1", dic.find("key1")->second);
  1266. EXPECT_EQ("val2", dic.find("key2")->second);
  1267. EXPECT_EQ("val3", dic.find("key3")->second);
  1268. }
  1269. TEST(SplitTest, ParseInvalidQueryTests) {
  1270. {
  1271. string s = " ";
  1272. Params dict;
  1273. detail::parse_query_text(s, dict);
  1274. EXPECT_TRUE(dict.empty());
  1275. }
  1276. {
  1277. string s = " = =";
  1278. Params dict;
  1279. detail::parse_query_text(s, dict);
  1280. EXPECT_TRUE(dict.empty());
  1281. }
  1282. }
  1283. TEST(ParseQueryTest, ParseQueryString) {
  1284. {
  1285. std::string s = "key1=val1&key2=val2&key3=val3";
  1286. Params dic;
  1287. detail::parse_query_text(s, dic);
  1288. EXPECT_EQ("val1", dic.find("key1")->second);
  1289. EXPECT_EQ("val2", dic.find("key2")->second);
  1290. EXPECT_EQ("val3", dic.find("key3")->second);
  1291. }
  1292. {
  1293. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1294. Params dic;
  1295. detail::parse_query_text(s, dic);
  1296. EXPECT_EQ("", dic.find("key1")->second);
  1297. EXPECT_EQ("val1", dic.find("key2")->second);
  1298. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1299. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1300. }
  1301. }
  1302. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1303. Params dic;
  1304. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1305. dic.emplace("key1", "val1");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1307. dic.emplace("key2", "val2");
  1308. dic.emplace("key3", "val3");
  1309. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1310. }
  1311. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1312. Params params;
  1313. params.emplace("a", "1");
  1314. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1315. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1316. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1317. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1318. // Long enough to overflow the stack when matched with std::regex.
  1319. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1320. EXPECT_EQ("/p?" + long_query + "&a=1",
  1321. append_query_params("/p?" + long_query, params));
  1322. }
  1323. // Joins every entry of a Headers or Params into "key=value " so a whole
  1324. // traversal can be compared in one assertion. Both are instantiations of the
  1325. // same insertion-ordered container, so one helper serves both.
  1326. template <typename Map> static std::string entries_to_string(const Map &m) {
  1327. std::string s;
  1328. for (const auto &entry : m) {
  1329. s += entry.first + "=" + entry.second + " ";
  1330. }
  1331. return s;
  1332. }
  1333. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1334. // Params used to be a std::multimap, which sorted by name and handed the
  1335. // caller's query back alphabetised. A client signing its query string could
  1336. // not reproduce the order it asked for.
  1337. Params dic;
  1338. dic.emplace("zulu", "1");
  1339. dic.emplace("alpha", "2");
  1340. dic.emplace("mike", "3");
  1341. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1342. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1343. }
  1344. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1345. Params dic;
  1346. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1347. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1348. }
  1349. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1350. Request req;
  1351. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1352. req.params);
  1353. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1354. EXPECT_EQ("first", req.get_param_value("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1356. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1357. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1358. EXPECT_EQ("", req.get_param_value("tag", 3));
  1359. }
  1360. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1361. // Params shares its container with Headers, which matches field names
  1362. // case-insensitively. Parameter names must not pick that up.
  1363. Params dic;
  1364. dic.emplace("Key", "upper");
  1365. dic.emplace("key", "lower");
  1366. EXPECT_EQ(2U, dic.size());
  1367. EXPECT_EQ(1U, dic.count("Key"));
  1368. EXPECT_EQ(1U, dic.count("key"));
  1369. EXPECT_EQ("upper", dic.find("Key")->second);
  1370. EXPECT_EQ("lower", dic.find("key")->second);
  1371. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1372. }
  1373. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1374. Server svr;
  1375. std::string order;
  1376. svr.Get("/order", [&](const Request &req, Response &res) {
  1377. order = entries_to_string(req.params);
  1378. res.set_content("ok", "text/plain");
  1379. });
  1380. auto port = svr.bind_to_any_port(HOST);
  1381. thread t = thread([&] { svr.listen_after_bind(); });
  1382. auto se = detail::scope_exit([&] {
  1383. svr.stop();
  1384. t.join();
  1385. ASSERT_FALSE(svr.is_running());
  1386. });
  1387. svr.wait_until_ready();
  1388. Client cli(HOST, port);
  1389. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1390. ASSERT_TRUE(res);
  1391. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1392. }
  1393. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1394. Server svr;
  1395. std::string field_order, file_order;
  1396. svr.Post("/order", [&](const Request &req, Response &res) {
  1397. for (const auto &field : req.form.fields) {
  1398. field_order += field.first + "=" + field.second.content + " ";
  1399. }
  1400. for (const auto &file : req.form.files) {
  1401. file_order += file.first + "=" + file.second.filename + " ";
  1402. }
  1403. res.set_content("ok", "text/plain");
  1404. });
  1405. auto port = svr.bind_to_any_port(HOST);
  1406. thread t = thread([&] { svr.listen_after_bind(); });
  1407. auto se = detail::scope_exit([&] {
  1408. svr.stop();
  1409. t.join();
  1410. ASSERT_FALSE(svr.is_running());
  1411. });
  1412. svr.wait_until_ready();
  1413. UploadFormDataItems items = {
  1414. {"zulu", "1", "", ""},
  1415. {"alpha", "2", "", ""},
  1416. {"mike", "3", "", ""},
  1417. {"zebra", "z", "z.txt", "text/plain"},
  1418. {"apple", "a", "a.txt", "text/plain"},
  1419. };
  1420. Client cli(HOST, port);
  1421. auto res = cli.Post("/order", items);
  1422. ASSERT_TRUE(res);
  1423. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1424. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1425. }
  1426. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1427. Server svr;
  1428. std::vector<std::string> values;
  1429. std::string first, second, out_of_range, order;
  1430. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1431. values = req.form.get_fields("tag");
  1432. first = req.form.get_field("tag", 0);
  1433. second = req.form.get_field("tag", 1);
  1434. out_of_range = req.form.get_field("tag", 2);
  1435. for (const auto &field : req.form.fields) {
  1436. order += field.first + "=" + field.second.content + " ";
  1437. }
  1438. res.set_content("ok", "text/plain");
  1439. });
  1440. auto port = svr.bind_to_any_port(HOST);
  1441. thread t = thread([&] { svr.listen_after_bind(); });
  1442. auto se = detail::scope_exit([&] {
  1443. svr.stop();
  1444. t.join();
  1445. ASSERT_FALSE(svr.is_running());
  1446. });
  1447. svr.wait_until_ready();
  1448. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1449. // not adjacent in the container.
  1450. UploadFormDataItems items = {
  1451. {"tag", "first", "", ""},
  1452. {"other", "x", "", ""},
  1453. {"tag", "second", "", ""},
  1454. };
  1455. Client cli(HOST, port);
  1456. auto res = cli.Post("/repeated", items);
  1457. ASSERT_TRUE(res);
  1458. ASSERT_EQ(2U, values.size());
  1459. EXPECT_EQ("first", values[0]);
  1460. EXPECT_EQ("second", values[1]);
  1461. EXPECT_EQ("first", first);
  1462. EXPECT_EQ("second", second);
  1463. // std::multimap already kept entries sharing a name in insertion order, so
  1464. // everything above passes without this change too. The whole traversal is
  1465. // what tells the two apart: sorting by name would hoist "other" to the front
  1466. // and the two "tag" parts would end up adjacent.
  1467. EXPECT_EQ("tag=first other=x tag=second ", order);
  1468. // Advancing past the last entry of a name used to run off the container;
  1469. // the container's saturating increment makes it return the default instead.
  1470. EXPECT_EQ("", out_of_range);
  1471. }
  1472. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1473. Server svr;
  1474. std::string file_names;
  1475. svr.Post("/upload", [&](const Request &req, Response &res) {
  1476. for (const auto &file : req.form.files) {
  1477. file_names += file.first + "|" + file.second.filename + " ";
  1478. }
  1479. res.set_content("ok", "text/plain");
  1480. });
  1481. auto port = svr.bind_to_any_port(HOST);
  1482. thread t = thread([&] { svr.listen_after_bind(); });
  1483. auto se = detail::scope_exit([&] {
  1484. svr.stop();
  1485. t.join();
  1486. ASSERT_FALSE(svr.is_running());
  1487. });
  1488. svr.wait_until_ready();
  1489. // A trailing backslash would otherwise escape the closing quote.
  1490. UploadFormDataItems items = {
  1491. {"dir\\", "x", "a.txt", "text/plain"},
  1492. {"b", "y", "a\\\\b.txt", "text/plain"},
  1493. };
  1494. Client cli(HOST, port);
  1495. auto res = cli.Post("/upload", items);
  1496. ASSERT_TRUE(res);
  1497. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1498. }
  1499. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1500. // Server::read_content() keeps a FormFields::iterator alive across the
  1501. // content callbacks that fill the part it points at. The container is
  1502. // vector-backed, so a later emplace can reallocate and invalidate an older
  1503. // iterator; 64 parts grow the vector through seven reallocations, which
  1504. // checks that every part's content still lands in its own entry.
  1505. const size_t part_count = 64;
  1506. // One formula for both the parts sent and the values expected back, so the
  1507. // two cannot drift apart.
  1508. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1509. auto content_of = [](size_t i) {
  1510. return std::string(64, static_cast<char>('a' + (i % 26)));
  1511. };
  1512. Server svr;
  1513. std::vector<std::pair<std::string, std::string>> received;
  1514. svr.Post("/many", [&](const Request &req, Response &res) {
  1515. for (const auto &field : req.form.fields) {
  1516. received.emplace_back(field.first, field.second.content);
  1517. }
  1518. res.set_content("ok", "text/plain");
  1519. });
  1520. auto port = svr.bind_to_any_port(HOST);
  1521. thread t = thread([&] { svr.listen_after_bind(); });
  1522. auto se = detail::scope_exit([&] {
  1523. svr.stop();
  1524. t.join();
  1525. ASSERT_FALSE(svr.is_running());
  1526. });
  1527. svr.wait_until_ready();
  1528. UploadFormDataItems items;
  1529. for (size_t i = 0; i < part_count; i++) {
  1530. items.push_back({name_of(i), content_of(i), "", ""});
  1531. }
  1532. Client cli(HOST, port);
  1533. auto res = cli.Post("/many", items);
  1534. ASSERT_TRUE(res);
  1535. ASSERT_EQ(part_count, received.size());
  1536. for (size_t i = 0; i < part_count; i++) {
  1537. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1538. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1539. }
  1540. }
  1541. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1542. string content_type = "multipart/form-data; boundary=something";
  1543. string boundary;
  1544. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1545. EXPECT_TRUE(ret);
  1546. EXPECT_EQ(boundary, "something");
  1547. }
  1548. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1549. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1550. string boundary;
  1551. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1552. EXPECT_TRUE(ret);
  1553. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1556. string content_type =
  1557. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1558. string boundary;
  1559. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1560. EXPECT_TRUE(ret);
  1561. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1562. }
  1563. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1564. string content_type =
  1565. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1566. string boundary;
  1567. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1568. EXPECT_TRUE(ret);
  1569. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1570. }
  1571. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1572. const string boundary(70, 'a');
  1573. string content_type = "multipart/form-data; boundary=" + boundary;
  1574. string parsed;
  1575. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1576. EXPECT_TRUE(ret);
  1577. EXPECT_EQ(parsed, boundary);
  1578. }
  1579. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1580. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1581. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1582. string parsed;
  1583. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1584. EXPECT_FALSE(ret);
  1585. }
  1586. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1587. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1588. // is 72 characters on the wire and still valid.
  1589. const string boundary(70, 'a');
  1590. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1591. string parsed;
  1592. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1593. EXPECT_EQ(parsed, boundary);
  1594. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1595. parsed.clear();
  1596. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1597. }
  1598. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1599. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1600. // The parameter parser must not treat that '=' as the key/value separator.
  1601. string content_type =
  1602. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1603. "charset=UTF-8";
  1604. string parsed;
  1605. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1606. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1607. }
  1608. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1609. // A ';' inside the quoted-string is part of the value, not a parameter
  1610. // separator, so it must not truncate the boundary.
  1611. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1612. string parsed;
  1613. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1614. EXPECT_EQ(parsed, "a;b");
  1615. }
  1616. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1617. string parsed;
  1618. EXPECT_TRUE(detail::parse_multipart_boundary(
  1619. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1620. EXPECT_EQ("a\\b", parsed);
  1621. EXPECT_TRUE(detail::parse_multipart_boundary(
  1622. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1623. EXPECT_EQ("a\"b", parsed);
  1624. }
  1625. TEST(ParseDispositionParamsTest, QuotedValues) {
  1626. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1627. // ';' and '=' are ordinary characters inside one.
  1628. struct {
  1629. const char *value;
  1630. std::vector<std::pair<const char *, const char *>> expected;
  1631. } cases[] = {
  1632. {"name=\"file1\"; filename=\"a.txt\"",
  1633. {{"name", "file1"}, {"filename", "a.txt"}}},
  1634. // Whitespace around '=' and ';' is still trimmed
  1635. {"name=\"file2\" ;filename = \"a.html\"",
  1636. {{"name", "file2"}, {"filename", "a.html"}}},
  1637. // '=' inside the value used to leave only the text after the last one
  1638. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1639. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1640. {"name=\"x=y\"", {{"name", "x=y"}}},
  1641. // ';' inside the value used to truncate the pair and leave a bogus one
  1642. {"name=\"file3\"; filename=\"a;b.txt\"",
  1643. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1644. // An unquoted value keeps working, and so does filename*
  1645. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1646. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1647. // A parameter with no key is dropped rather than turned into one whose
  1648. // key is the value
  1649. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1650. // An escaped quote does not end the value
  1651. {"name=\"a\\\"; filename=evil.php\"",
  1652. {{"name", "a\"; filename=evil.php"}}},
  1653. // Other backslashes, as in a Windows path, are kept
  1654. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1655. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1656. };
  1657. for (const auto &c : cases) {
  1658. Params params;
  1659. detail::parse_disposition_params(c.value, params);
  1660. for (const auto &kv : c.expected) {
  1661. auto it = params.find(kv.first);
  1662. ASSERT_NE(it, params.end())
  1663. << "value: " << c.value << ", key: " << kv.first;
  1664. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1665. }
  1666. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1667. }
  1668. }
  1669. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1670. Server svr;
  1671. std::string filename;
  1672. std::string content;
  1673. svr.Post("/upload", [&](const Request &req, Response &) {
  1674. const auto &file = req.form.get_file("file");
  1675. filename = file.filename;
  1676. content = file.content;
  1677. });
  1678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1679. auto se = detail::scope_exit([&] {
  1680. svr.stop();
  1681. thread.join();
  1682. ASSERT_FALSE(svr.is_running());
  1683. });
  1684. svr.wait_until_ready();
  1685. std::string body = "--B\r\n"
  1686. "Content-Disposition: form-data; name=\"file\"; "
  1687. "filename=\"a.txt\"\r\n"
  1688. "Content-Type: text/plain\r\n"
  1689. "\r\n"
  1690. "hello\r\n"
  1691. "--B--\r\n";
  1692. Client cli(HOST, PORT);
  1693. auto res = cli.Post(
  1694. "/upload",
  1695. [&](size_t offset, DataSink &sink) {
  1696. if (offset < body.size()) {
  1697. sink.write(&body[offset], 1);
  1698. } else {
  1699. sink.done();
  1700. }
  1701. return true;
  1702. },
  1703. "multipart/form-data; boundary=B");
  1704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1705. EXPECT_EQ(StatusCode::OK_200, res->status);
  1706. EXPECT_EQ("a.txt", filename);
  1707. EXPECT_EQ("hello", content);
  1708. }
  1709. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1710. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1711. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1712. Server svr;
  1713. std::string field_value, file_name, file_filename;
  1714. bool has_field = false, has_file = false;
  1715. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1716. has_field = req.form.has_field("x=y");
  1717. field_value = req.form.get_field("x=y");
  1718. has_file = req.form.has_file("file1");
  1719. const auto &file = req.form.get_file("file1");
  1720. file_name = file.name;
  1721. file_filename = file.filename;
  1722. res.set_content("ok", "text/plain");
  1723. });
  1724. auto port = svr.bind_to_any_port(HOST);
  1725. thread t = thread([&] { svr.listen_after_bind(); });
  1726. auto se = detail::scope_exit([&] {
  1727. svr.stop();
  1728. t.join();
  1729. ASSERT_FALSE(svr.is_running());
  1730. });
  1731. svr.wait_until_ready();
  1732. UploadFormDataItems items = {
  1733. {"x=y", "field-value", "", ""},
  1734. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1735. };
  1736. Client cli(HOST, port);
  1737. auto res = cli.Post("/quoted", items);
  1738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1739. ASSERT_EQ(StatusCode::OK_200, res->status);
  1740. EXPECT_TRUE(has_field);
  1741. EXPECT_EQ("field-value", field_value);
  1742. EXPECT_TRUE(has_file);
  1743. EXPECT_EQ("file1", file_name);
  1744. EXPECT_EQ("a;b=report.pdf", file_filename);
  1745. }
  1746. TEST(GetHeaderValueTest, DefaultValue) {
  1747. Headers headers = {{"Dummy", "Dummy"}};
  1748. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1749. EXPECT_STREQ("text/plain", val);
  1750. }
  1751. TEST(GetHeaderValueTest, DefaultValueInt) {
  1752. Headers headers = {{"Dummy", "Dummy"}};
  1753. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1754. EXPECT_EQ(100ull, val);
  1755. }
  1756. TEST(GetHeaderValueTest, RegularValue) {
  1757. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1758. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1759. EXPECT_STREQ("text/html", val);
  1760. }
  1761. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1762. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1763. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1764. EXPECT_STREQ("text/html", val);
  1765. }
  1766. TEST(GetHeaderValueTest, SetContent) {
  1767. Response res;
  1768. res.set_content("html", "text/html");
  1769. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1770. res.set_content("text", "text/plain");
  1771. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1772. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1773. }
  1774. TEST(GetHeaderValueTest, RegularValueInt) {
  1775. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1776. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1777. EXPECT_EQ(100ull, val);
  1778. }
  1779. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1780. Headers headers = {{"Content-Length", "x"}};
  1781. auto is_invalid_value = false;
  1782. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1783. is_invalid_value);
  1784. EXPECT_EQ(0ull, val);
  1785. EXPECT_TRUE(is_invalid_value);
  1786. }
  1787. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1788. // An all-digit value that overflows size_t must be reported as invalid, not
  1789. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1790. // a large length to a small one on 32-bit builds, leaving the framing length
  1791. // wrong while is_invalid_value stayed false.
  1792. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1793. auto is_invalid_value = false;
  1794. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1795. is_invalid_value);
  1796. EXPECT_TRUE(is_invalid_value);
  1797. // A well-formed length is unaffected.
  1798. Headers ok = {{"Content-Length", "1234"}};
  1799. is_invalid_value = false;
  1800. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1801. is_invalid_value);
  1802. EXPECT_EQ(1234ull, val);
  1803. EXPECT_FALSE(is_invalid_value);
  1804. }
  1805. TEST(GetHeaderValueTest, Range) {
  1806. {
  1807. Headers headers = {make_range_header({{1, -1}})};
  1808. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1809. EXPECT_STREQ("bytes=1-", val);
  1810. }
  1811. {
  1812. Headers headers = {make_range_header({{-1, 1}})};
  1813. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1814. EXPECT_STREQ("bytes=-1", val);
  1815. }
  1816. {
  1817. Headers headers = {make_range_header({{1, 10}})};
  1818. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1819. EXPECT_STREQ("bytes=1-10", val);
  1820. }
  1821. {
  1822. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1823. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1824. EXPECT_STREQ("bytes=1-10, 100-", val);
  1825. }
  1826. {
  1827. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1828. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1829. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1830. }
  1831. {
  1832. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1833. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1834. EXPECT_STREQ("bytes=0-0, -1", val);
  1835. }
  1836. }
  1837. TEST(BearerTokenAuthTest, SchemeValidation) {
  1838. // A value shorter than "Bearer " must not throw from the fixed-length
  1839. // substr, and a non-Bearer scheme must not be reported as a token.
  1840. struct {
  1841. const char *value;
  1842. const char *expected;
  1843. } cases[] = {
  1844. {"x", ""},
  1845. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1846. {"Bearer abc123", "abc123"},
  1847. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1848. };
  1849. for (const auto &c : cases) {
  1850. Request req;
  1851. req.set_header("Authorization", c.value);
  1852. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1853. }
  1854. }
  1855. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1856. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1857. // to depend on the standard library (libstdc++ handed back duplicates in
  1858. // reverse insertion order, libc++ in insertion order).
  1859. Request req;
  1860. req.set_header("Accept-Encoding", "gzip");
  1861. req.set_header("Accept-Encoding", "deflate");
  1862. req.set_header("Accept-Encoding", "br");
  1863. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1864. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1866. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1867. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1868. }
  1869. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1870. Request req;
  1871. req.set_header("X-Test", "only");
  1872. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1873. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1875. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1876. }
  1877. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1878. Request req;
  1879. req.set_header("X-First", "1");
  1880. req.set_header("X-Test", "2");
  1881. req.params.emplace("first", "1");
  1882. req.params.emplace("test", "2");
  1883. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1884. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1885. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1886. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1887. // The second one is negative when read as a signed value
  1888. const auto max_id = (std::numeric_limits<size_t>::max)();
  1889. for (auto id : {max_id / 2, max_id}) {
  1890. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1891. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1892. EXPECT_EQ("", req.get_param_value("test", id));
  1893. EXPECT_EQ("", req.form.get_field("test", id));
  1894. EXPECT_EQ("", req.form.get_file("test", id).content);
  1895. }
  1896. }
  1897. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1898. Headers headers;
  1899. headers.emplace("Host", "example.com");
  1900. headers.emplace("Accept-Encoding", "gzip");
  1901. headers.emplace("User-Agent", "test");
  1902. headers.emplace("Accept-Encoding", "deflate");
  1903. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1904. "Accept-Encoding=deflate ",
  1905. entries_to_string(headers));
  1906. }
  1907. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1908. Headers headers = {{"Content-Type", "text/html"},
  1909. {"CONTENT-TYPE", "text/xml"}};
  1910. EXPECT_EQ(2U, headers.count("content-type"));
  1911. auto it = headers.find("content-type");
  1912. ASSERT_TRUE(it != headers.end());
  1913. EXPECT_EQ("text/html", it->second);
  1914. }
  1915. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1916. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1917. // drop only those fields and leave everything positioned between them.
  1918. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1919. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1920. auto rng = headers.equal_range("a");
  1921. headers.erase(rng.first, rng.second);
  1922. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1923. }
  1924. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1925. Headers headers = {
  1926. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1927. EXPECT_EQ(3U, headers.erase("A"));
  1928. EXPECT_EQ(0U, headers.count("A"));
  1929. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1930. }
  1931. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1932. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1933. headers.emplace_front("Host", "example.com");
  1934. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1935. entries_to_string(headers));
  1936. }
  1937. TEST(ParseHeaderValueTest, Range) {
  1938. {
  1939. Ranges ranges;
  1940. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1941. EXPECT_TRUE(ret);
  1942. EXPECT_EQ(1u, ranges.size());
  1943. EXPECT_EQ(1u, ranges[0].first);
  1944. EXPECT_EQ(-1, ranges[0].second);
  1945. }
  1946. {
  1947. Ranges ranges;
  1948. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1949. EXPECT_TRUE(ret);
  1950. EXPECT_EQ(1u, ranges.size());
  1951. EXPECT_EQ(-1, ranges[0].first);
  1952. EXPECT_EQ(1u, ranges[0].second);
  1953. }
  1954. {
  1955. Ranges ranges;
  1956. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1957. EXPECT_TRUE(ret);
  1958. EXPECT_EQ(1u, ranges.size());
  1959. EXPECT_EQ(1u, ranges[0].first);
  1960. EXPECT_EQ(10u, ranges[0].second);
  1961. }
  1962. {
  1963. Ranges ranges;
  1964. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1965. EXPECT_FALSE(ret);
  1966. }
  1967. {
  1968. Ranges ranges;
  1969. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1970. EXPECT_TRUE(ret);
  1971. EXPECT_EQ(2u, ranges.size());
  1972. EXPECT_EQ(1u, ranges[0].first);
  1973. EXPECT_EQ(10u, ranges[0].second);
  1974. EXPECT_EQ(100u, ranges[1].first);
  1975. EXPECT_EQ(-1, ranges[1].second);
  1976. }
  1977. {
  1978. Ranges ranges;
  1979. auto ret =
  1980. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1981. EXPECT_TRUE(ret);
  1982. EXPECT_EQ(3u, ranges.size());
  1983. EXPECT_EQ(1u, ranges[0].first);
  1984. EXPECT_EQ(10u, ranges[0].second);
  1985. EXPECT_EQ(100u, ranges[1].first);
  1986. EXPECT_EQ(200u, ranges[1].second);
  1987. EXPECT_EQ(300u, ranges[2].first);
  1988. EXPECT_EQ(400u, ranges[2].second);
  1989. }
  1990. {
  1991. Ranges ranges;
  1992. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1996. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1997. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1998. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2002. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2003. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2004. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2005. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2006. EXPECT_FALSE(
  2007. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2008. EXPECT_TRUE(ranges.empty());
  2009. }
  2010. {
  2011. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2012. // remainder of the representation, so it stays accepted.
  2013. Ranges ranges;
  2014. auto ret =
  2015. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2016. EXPECT_TRUE(ret);
  2017. ASSERT_EQ(1u, ranges.size());
  2018. EXPECT_EQ(0, ranges[0].first);
  2019. EXPECT_EQ(-1, ranges[0].second);
  2020. }
  2021. // RFC 9110 14.1: range unit names are case-insensitive.
  2022. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2023. Ranges ranges;
  2024. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2025. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2026. }
  2027. }
  2028. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2029. Request req;
  2030. req.set_header("Accept-Encoding", "gzip");
  2031. Response res;
  2032. res.set_header("Content-Type", "text/plain");
  2033. auto ret = detail::encoding_type(req, res);
  2034. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2035. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2036. #else
  2037. EXPECT_TRUE(ret == detail::EncodingType::None);
  2038. #endif
  2039. }
  2040. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2041. Request req;
  2042. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2043. Response res;
  2044. res.set_header("Content-Type", "text/plain");
  2045. auto ret = detail::encoding_type(req, res);
  2046. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2047. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2048. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2050. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2051. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2052. #else
  2053. EXPECT_TRUE(ret == detail::EncodingType::None);
  2054. #endif
  2055. }
  2056. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2057. Request req;
  2058. req.set_header("Accept-Encoding",
  2059. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2060. Response res;
  2061. res.set_header("Content-Type", "text/plain");
  2062. auto ret = detail::encoding_type(req, res);
  2063. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2065. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2066. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2067. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2068. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2069. #else
  2070. EXPECT_TRUE(ret == detail::EncodingType::None);
  2071. #endif
  2072. }
  2073. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2074. // All supported encodings rejected with q=0 should return None
  2075. Request req;
  2076. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2077. Response res;
  2078. res.set_header("Content-Type", "text/plain");
  2079. auto ret = detail::encoding_type(req, res);
  2080. EXPECT_TRUE(ret == detail::EncodingType::None);
  2081. }
  2082. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2083. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2084. Request req;
  2085. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2086. Response res;
  2087. res.set_header("Content-Type", "text/plain");
  2088. auto ret = detail::encoding_type(req, res);
  2089. EXPECT_TRUE(ret == detail::EncodingType::None);
  2090. }
  2091. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2092. Request req;
  2093. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2094. Response res;
  2095. res.set_header("Content-Type", "text/plain");
  2096. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2097. }
  2098. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2099. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2100. Request req;
  2101. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2102. Response res;
  2103. res.set_header("Content-Type", "text/plain");
  2104. auto ret = detail::encoding_type(req, res);
  2105. EXPECT_TRUE(ret == detail::EncodingType::None);
  2106. }
  2107. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2108. // RFC 7231: Accept-Encoding values are case-insensitive
  2109. Request req;
  2110. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2111. Response res;
  2112. res.set_header("Content-Type", "text/plain");
  2113. auto ret = detail::encoding_type(req, res);
  2114. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2115. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2116. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2117. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2118. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2119. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2120. #else
  2121. EXPECT_TRUE(ret == detail::EncodingType::None);
  2122. #endif
  2123. }
  2124. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2125. // q value should determine priority, not hardcoded order
  2126. Request req;
  2127. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2128. Response res;
  2129. res.set_header("Content-Type", "text/plain");
  2130. auto ret = detail::encoding_type(req, res);
  2131. // gzip has highest q=1.0, so it should be selected even though
  2132. // br and zstd are also supported
  2133. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2134. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2135. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2136. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2137. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2138. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2139. #else
  2140. EXPECT_TRUE(ret == detail::EncodingType::None);
  2141. #endif
  2142. }
  2143. TEST(BufferStreamTest, read) {
  2144. detail::BufferStream strm1;
  2145. Stream &strm = strm1;
  2146. EXPECT_EQ(5, strm.write("hello"));
  2147. char buf[512];
  2148. EXPECT_EQ(2, strm.read(buf, 2));
  2149. EXPECT_EQ('h', buf[0]);
  2150. EXPECT_EQ('e', buf[1]);
  2151. EXPECT_EQ(2, strm.read(buf, 2));
  2152. EXPECT_EQ('l', buf[0]);
  2153. EXPECT_EQ('l', buf[1]);
  2154. EXPECT_EQ(1, strm.read(buf, 1));
  2155. EXPECT_EQ('o', buf[0]);
  2156. EXPECT_EQ(0, strm.read(buf, 1));
  2157. }
  2158. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2159. auto host = "www.httpwatch.com";
  2160. auto ip = hosted_at(host);
  2161. EXPECT_EQ("23.96.13.243", ip);
  2162. std::vector<std::string> addrs;
  2163. hosted_at(host, addrs);
  2164. EXPECT_EQ(1u, addrs.size());
  2165. }
  2166. #if 0 // It depends on each test environment...
  2167. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2168. auto host = "www.youtube.com";
  2169. std::vector<std::string> addrs;
  2170. hosted_at(host, addrs);
  2171. EXPECT_EQ(20u, addrs.size());
  2172. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2173. EXPECT_TRUE(it != addrs.end());
  2174. }
  2175. #endif
  2176. class ChunkedEncodingTest : public ::testing::Test {
  2177. protected:
  2178. ChunkedEncodingTest()
  2179. : cli_(HOST, PORT)
  2180. #ifdef CPPHTTPLIB_SSL_ENABLED
  2181. ,
  2182. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2183. #endif
  2184. {
  2185. cli_.set_connection_timeout(2);
  2186. #ifdef CPPHTTPLIB_SSL_ENABLED
  2187. cli_.enable_server_certificate_verification(false);
  2188. #endif
  2189. }
  2190. virtual void SetUp() {
  2191. read_file("./image.jpg", image_data_);
  2192. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2193. res.set_content("Hello World!", "text/plain");
  2194. });
  2195. svr_.Get(
  2196. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2197. res.set_chunked_content_provider(
  2198. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2199. size_t remaining = image_data_.size() - offset;
  2200. if (remaining == 0) {
  2201. sink.done();
  2202. } else {
  2203. constexpr size_t CHUNK_SIZE = 1024;
  2204. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2205. sink.write(&image_data_[offset], send_size);
  2206. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2207. }
  2208. return true;
  2209. });
  2210. });
  2211. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2212. svr_.wait_until_ready();
  2213. }
  2214. virtual void TearDown() {
  2215. svr_.stop();
  2216. if (!request_threads_.empty()) {
  2217. std::this_thread::sleep_for(std::chrono::seconds(1));
  2218. for (auto &t : request_threads_) {
  2219. t.join();
  2220. }
  2221. }
  2222. t_.join();
  2223. }
  2224. #ifdef CPPHTTPLIB_SSL_ENABLED
  2225. SSLClient cli_;
  2226. SSLServer svr_;
  2227. #else
  2228. Client cli_;
  2229. Server svr_;
  2230. #endif
  2231. thread t_;
  2232. std::vector<thread> request_threads_;
  2233. std::string image_data_;
  2234. };
  2235. TEST_F(ChunkedEncodingTest, NormalGet) {
  2236. auto res = cli_.Get("/chunked");
  2237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2238. std::string out;
  2239. read_file("./image.jpg", out);
  2240. EXPECT_EQ(StatusCode::OK_200, res->status);
  2241. EXPECT_EQ(out, res->body);
  2242. }
  2243. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2244. std::string body;
  2245. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2246. body.append(data, data_length);
  2247. return true;
  2248. });
  2249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2250. std::string out;
  2251. read_file("./image.jpg", out);
  2252. EXPECT_EQ(StatusCode::OK_200, res->status);
  2253. EXPECT_EQ(out, body);
  2254. }
  2255. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2256. std::string body;
  2257. auto res = cli_.Get(
  2258. "/chunked",
  2259. [&](const Response &response) {
  2260. EXPECT_EQ(StatusCode::OK_200, response.status);
  2261. return true;
  2262. },
  2263. [&](const char *data, size_t data_length) {
  2264. body.append(data, data_length);
  2265. return true;
  2266. });
  2267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2268. std::string out;
  2269. read_file("./image.jpg", out);
  2270. EXPECT_EQ(StatusCode::OK_200, res->status);
  2271. EXPECT_EQ(out, body);
  2272. }
  2273. TEST(RangeTest, FromHTTPBin_Online) {
  2274. auto host = "httpbingo.org";
  2275. auto path = std::string{"/range/32"};
  2276. #ifdef CPPHTTPLIB_SSL_ENABLED
  2277. auto port = 443;
  2278. SSLClient cli(host, port);
  2279. #else
  2280. auto port = 80;
  2281. Client cli(host, port);
  2282. #endif
  2283. cli.set_connection_timeout(5);
  2284. {
  2285. auto res = cli.Get(path);
  2286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2287. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2288. EXPECT_EQ(StatusCode::OK_200, res->status);
  2289. }
  2290. {
  2291. Headers headers = {make_range_header({{1, -1}})};
  2292. auto res = cli.Get(path, headers);
  2293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2294. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2295. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2296. }
  2297. {
  2298. Headers headers = {make_range_header({{1, 10}})};
  2299. auto res = cli.Get(path, headers);
  2300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2301. EXPECT_EQ("bcdefghijk", res->body);
  2302. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2303. }
  2304. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2305. // entire resource, while the original httpbin returned 200. Both are
  2306. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2307. {
  2308. Headers headers = {make_range_header({{0, 31}})};
  2309. auto res = cli.Get(path, headers);
  2310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2311. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2312. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2313. res->status == StatusCode::PartialContent_206);
  2314. }
  2315. {
  2316. Headers headers = {make_range_header({{0, -1}})};
  2317. auto res = cli.Get(path, headers);
  2318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2319. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2320. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2321. res->status == StatusCode::PartialContent_206);
  2322. }
  2323. // go-httpbin returns 206 with clamped range for over-range requests,
  2324. // while the original httpbin returned 416. Both behaviors are observed
  2325. // in real servers, so we only verify the request succeeds.
  2326. {
  2327. Headers headers = {make_range_header({{0, 32}})};
  2328. auto res = cli.Get(path, headers);
  2329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2330. }
  2331. }
  2332. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2333. auto host = "unresolvableaddress.local";
  2334. auto path = std::string{"/"};
  2335. #ifdef CPPHTTPLIB_SSL_ENABLED
  2336. auto port = 443;
  2337. SSLClient cli(host, port);
  2338. #else
  2339. auto port = 80;
  2340. Client cli(host, port);
  2341. #endif
  2342. cli.set_connection_timeout(1);
  2343. {
  2344. auto res = cli.Get(path);
  2345. ASSERT_FALSE(res);
  2346. }
  2347. std::this_thread::sleep_for(std::chrono::seconds(8));
  2348. }
  2349. #if defined(__linux__) && defined(__GLIBC__) && \
  2350. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2351. // Forward declaration: in split builds split.py strips `inline` and moves the
  2352. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2353. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2354. // against the symbol in both header-only and split builds.
  2355. namespace httplib {
  2356. namespace detail {
  2357. int getaddrinfo_with_timeout(const char *node, const char *service,
  2358. const struct addrinfo *hints,
  2359. struct addrinfo **res, time_t timeout_sec);
  2360. } // namespace detail
  2361. } // namespace httplib
  2362. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2363. //
  2364. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2365. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2366. // gai_suspend() call hits the connection timeout the function calls
  2367. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2368. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2369. // still alive and still references the now-destroyed stack frame.
  2370. //
  2371. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2372. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2373. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2374. // and runs them in a container.
  2375. namespace {
  2376. bool should_run_issue_2431_tests() {
  2377. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2378. return v && *v && std::string(v) != "0";
  2379. }
  2380. std::string unique_unresolvable_host(int n) {
  2381. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2382. // glibc still asks the configured nameserver — which is exactly the path
  2383. // we want to exercise. A unique label per call avoids the resolver cache.
  2384. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2385. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2386. std::to_string(n) + ".invalid";
  2387. }
  2388. } // namespace
  2389. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2390. if (!should_run_issue_2431_tests()) {
  2391. GTEST_SKIP()
  2392. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2393. }
  2394. for (int i = 0; i < 8; ++i) {
  2395. struct addrinfo hints;
  2396. memset(&hints, 0, sizeof(hints));
  2397. hints.ai_family = AF_UNSPEC;
  2398. hints.ai_socktype = SOCK_STREAM;
  2399. auto host = unique_unresolvable_host(i);
  2400. struct addrinfo *result = nullptr;
  2401. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2402. &result, /*timeout_sec=*/1);
  2403. if (rc == 0 && result) { freeaddrinfo(result); }
  2404. }
  2405. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2406. // stack region they still believe holds their gaicb.
  2407. std::this_thread::sleep_for(std::chrono::seconds(3));
  2408. }
  2409. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2410. if (!should_run_issue_2431_tests()) {
  2411. GTEST_SKIP()
  2412. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2413. }
  2414. std::atomic<bool> stop{false};
  2415. std::vector<std::thread> threads;
  2416. for (int t = 0; t < 8; ++t) {
  2417. threads.emplace_back([t, &stop] {
  2418. int i = 0;
  2419. while (!stop.load(std::memory_order_relaxed)) {
  2420. struct addrinfo hints;
  2421. memset(&hints, 0, sizeof(hints));
  2422. hints.ai_family = AF_UNSPEC;
  2423. hints.ai_socktype = SOCK_STREAM;
  2424. auto host = unique_unresolvable_host(t * 100000 + i++);
  2425. struct addrinfo *result = nullptr;
  2426. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2427. &result, /*timeout_sec=*/1);
  2428. if (rc == 0 && result) { freeaddrinfo(result); }
  2429. }
  2430. });
  2431. }
  2432. std::this_thread::sleep_for(std::chrono::seconds(8));
  2433. stop.store(true, std::memory_order_relaxed);
  2434. for (auto &th : threads) {
  2435. th.join();
  2436. }
  2437. std::this_thread::sleep_for(std::chrono::seconds(3));
  2438. }
  2439. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2440. if (!should_run_issue_2431_tests()) {
  2441. GTEST_SKIP()
  2442. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2443. }
  2444. std::atomic<bool> stop{false};
  2445. std::vector<std::thread> threads;
  2446. for (int t = 0; t < 8; ++t) {
  2447. threads.emplace_back([t, &stop] {
  2448. int i = 0;
  2449. while (!stop.load(std::memory_order_relaxed)) {
  2450. auto host = unique_unresolvable_host(t * 100000 + i++);
  2451. Client cli(host, 80);
  2452. cli.set_connection_timeout(1, 0);
  2453. cli.set_read_timeout(1, 0);
  2454. cli.set_write_timeout(1, 0);
  2455. (void)cli.Get("/");
  2456. }
  2457. });
  2458. }
  2459. std::this_thread::sleep_for(std::chrono::seconds(8));
  2460. stop.store(true, std::memory_order_relaxed);
  2461. for (auto &th : threads) {
  2462. th.join();
  2463. }
  2464. std::this_thread::sleep_for(std::chrono::seconds(3));
  2465. }
  2466. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2467. TEST(ConnectionErrorTest, InvalidHost) {
  2468. auto host = "-abcde.com";
  2469. #ifdef CPPHTTPLIB_SSL_ENABLED
  2470. auto port = 443;
  2471. SSLClient cli(host, port);
  2472. #else
  2473. auto port = 80;
  2474. Client cli(host, port);
  2475. #endif
  2476. cli.set_connection_timeout(std::chrono::seconds(2));
  2477. auto res = cli.Get("/");
  2478. ASSERT_TRUE(!res);
  2479. EXPECT_EQ(Error::Connection, res.error());
  2480. }
  2481. TEST(ConnectionErrorTest, InvalidHost2) {
  2482. auto host = "httpcan.org/";
  2483. #ifdef CPPHTTPLIB_SSL_ENABLED
  2484. SSLClient cli(host);
  2485. #else
  2486. Client cli(host);
  2487. #endif
  2488. cli.set_connection_timeout(std::chrono::seconds(2));
  2489. auto res = cli.Get("/");
  2490. ASSERT_TRUE(!res);
  2491. EXPECT_EQ(Error::Connection, res.error());
  2492. }
  2493. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2494. auto host = "httpcan.org/";
  2495. #ifdef CPPHTTPLIB_SSL_ENABLED
  2496. SSLClient cli(host);
  2497. #else
  2498. Client cli(host);
  2499. #endif
  2500. cli.set_connection_timeout(std::chrono::seconds(2));
  2501. auto res = cli.Get("/");
  2502. ASSERT_TRUE(!res);
  2503. stringstream s;
  2504. s << "error code: " << res.error();
  2505. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2506. }
  2507. TEST(ConnectionErrorTest, InvalidPort) {
  2508. auto host = "localhost";
  2509. auto port = 44380;
  2510. #ifdef CPPHTTPLIB_SSL_ENABLED
  2511. SSLClient cli(host, port);
  2512. #else
  2513. Client cli(host, port);
  2514. #endif
  2515. cli.set_connection_timeout(std::chrono::seconds(2));
  2516. auto res = cli.Get("/");
  2517. ASSERT_TRUE(!res);
  2518. EXPECT_TRUE(Error::Connection == res.error() ||
  2519. Error::ConnectionTimeout == res.error());
  2520. }
  2521. TEST(ConnectionErrorTest, Timeout_Online) {
  2522. auto host = "google.com";
  2523. #ifdef CPPHTTPLIB_SSL_ENABLED
  2524. auto port = 44380;
  2525. SSLClient cli(host, port);
  2526. #else
  2527. auto port = 8080;
  2528. Client cli(host, port);
  2529. #endif
  2530. cli.set_connection_timeout(std::chrono::seconds(2));
  2531. // only probe one address type so that the error reason
  2532. // correlates to the timed-out IPv4, not the unsupported
  2533. // IPv6 connection attempt
  2534. cli.set_address_family(AF_INET);
  2535. auto res = cli.Get("/");
  2536. ASSERT_TRUE(!res);
  2537. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2538. }
  2539. TEST(CancelTest, NoCancel_Online) {
  2540. auto host = "httpbingo.org";
  2541. auto path = std::string{"/range/32"};
  2542. #ifdef CPPHTTPLIB_SSL_ENABLED
  2543. auto port = 443;
  2544. SSLClient cli(host, port);
  2545. #else
  2546. auto port = 80;
  2547. Client cli(host, port);
  2548. #endif
  2549. cli.set_connection_timeout(std::chrono::seconds(5));
  2550. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2552. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2553. EXPECT_EQ(StatusCode::OK_200, res->status);
  2554. }
  2555. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2556. // Use /bytes with a large payload so that the DownloadProgress callback
  2557. // (which only fires for Content-Length responses) is invoked before the
  2558. // entire body is received, giving cancellation a chance to fire.
  2559. auto host = "httpbingo.org";
  2560. auto path = std::string{"/bytes/524288"};
  2561. #ifdef CPPHTTPLIB_SSL_ENABLED
  2562. auto port = 443;
  2563. SSLClient cli(host, port);
  2564. #else
  2565. auto port = 80;
  2566. Client cli(host, port);
  2567. #endif
  2568. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2569. cli.set_connection_timeout(std::chrono::seconds(5));
  2570. ASSERT_TRUE(!res);
  2571. EXPECT_EQ(Error::Canceled, res.error());
  2572. }
  2573. TEST(CancelTest, WithCancelLargePayload_Online) {
  2574. auto host = "httpbingo.org";
  2575. auto path = std::string{"/bytes/524288"};
  2576. #ifdef CPPHTTPLIB_SSL_ENABLED
  2577. auto port = 443;
  2578. SSLClient cli(host, port);
  2579. #else
  2580. auto port = 80;
  2581. Client cli(host, port);
  2582. #endif
  2583. cli.set_connection_timeout(std::chrono::seconds(5));
  2584. uint32_t count = 0;
  2585. auto res =
  2586. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2587. ASSERT_TRUE(!res);
  2588. EXPECT_EQ(Error::Canceled, res.error());
  2589. }
  2590. TEST(CancelTest, NoCancelPost) {
  2591. Server svr;
  2592. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2593. res.set_content("Hello World!", "text/plain");
  2594. });
  2595. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2596. auto se = detail::scope_exit([&] {
  2597. svr.stop();
  2598. thread.join();
  2599. ASSERT_FALSE(svr.is_running());
  2600. });
  2601. svr.wait_until_ready();
  2602. Client cli(HOST, PORT);
  2603. cli.set_connection_timeout(std::chrono::seconds(5));
  2604. auto res =
  2605. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2606. "application/json", [](uint64_t, uint64_t) { return true; });
  2607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2608. EXPECT_EQ("Hello World!", res->body);
  2609. EXPECT_EQ(StatusCode::OK_200, res->status);
  2610. }
  2611. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2612. Server svr;
  2613. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2614. res.set_content("Hello World!", "text/plain");
  2615. });
  2616. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2617. auto se = detail::scope_exit([&] {
  2618. svr.stop();
  2619. thread.join();
  2620. ASSERT_FALSE(svr.is_running());
  2621. });
  2622. svr.wait_until_ready();
  2623. Client cli(HOST, PORT);
  2624. cli.set_connection_timeout(std::chrono::seconds(5));
  2625. auto res =
  2626. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2627. "application/json", [](uint64_t, uint64_t) { return false; });
  2628. ASSERT_TRUE(!res);
  2629. EXPECT_EQ(Error::Canceled, res.error());
  2630. }
  2631. TEST(CancelTest, WithCancelLargePayloadPost) {
  2632. Server svr;
  2633. svr.set_payload_max_length(200 * 1024 * 1024);
  2634. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2635. res.set_content(LARGE_DATA, "text/plain");
  2636. });
  2637. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2638. auto se = detail::scope_exit([&] {
  2639. svr.stop();
  2640. thread.join();
  2641. ASSERT_FALSE(svr.is_running());
  2642. });
  2643. svr.wait_until_ready();
  2644. Client cli(HOST, PORT);
  2645. cli.set_payload_max_length(200 * 1024 * 1024);
  2646. cli.set_connection_timeout(std::chrono::seconds(5));
  2647. auto res =
  2648. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2649. "application/json", [](uint64_t, uint64_t) { return false; });
  2650. ASSERT_TRUE(!res);
  2651. EXPECT_EQ(Error::Canceled, res.error());
  2652. }
  2653. TEST(CancelTest, NoCancelPut) {
  2654. Server svr;
  2655. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2656. res.set_content("Hello World!", "text/plain");
  2657. });
  2658. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2659. auto se = detail::scope_exit([&] {
  2660. svr.stop();
  2661. thread.join();
  2662. ASSERT_FALSE(svr.is_running());
  2663. });
  2664. svr.wait_until_ready();
  2665. Client cli(HOST, PORT);
  2666. cli.set_connection_timeout(std::chrono::seconds(5));
  2667. auto res =
  2668. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2669. "application/json", [](uint64_t, uint64_t) { return true; });
  2670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2671. EXPECT_EQ("Hello World!", res->body);
  2672. EXPECT_EQ(StatusCode::OK_200, res->status);
  2673. }
  2674. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2675. Server svr;
  2676. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2677. res.set_content("Hello World!", "text/plain");
  2678. });
  2679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2680. auto se = detail::scope_exit([&] {
  2681. svr.stop();
  2682. thread.join();
  2683. ASSERT_FALSE(svr.is_running());
  2684. });
  2685. svr.wait_until_ready();
  2686. Client cli(HOST, PORT);
  2687. cli.set_connection_timeout(std::chrono::seconds(5));
  2688. auto res =
  2689. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2690. "application/json", [](uint64_t, uint64_t) { return false; });
  2691. ASSERT_TRUE(!res);
  2692. EXPECT_EQ(Error::Canceled, res.error());
  2693. }
  2694. TEST(CancelTest, WithCancelLargePayloadPut) {
  2695. Server svr;
  2696. svr.set_payload_max_length(200 * 1024 * 1024);
  2697. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2698. res.set_content(LARGE_DATA, "text/plain");
  2699. });
  2700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2701. auto se = detail::scope_exit([&] {
  2702. svr.stop();
  2703. thread.join();
  2704. ASSERT_FALSE(svr.is_running());
  2705. });
  2706. svr.wait_until_ready();
  2707. Client cli(HOST, PORT);
  2708. cli.set_payload_max_length(200 * 1024 * 1024);
  2709. cli.set_connection_timeout(std::chrono::seconds(5));
  2710. auto res =
  2711. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2712. "application/json", [](uint64_t, uint64_t) { return false; });
  2713. ASSERT_TRUE(!res);
  2714. EXPECT_EQ(Error::Canceled, res.error());
  2715. }
  2716. TEST(CancelTest, NoCancelPatch) {
  2717. Server svr;
  2718. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2719. res.set_content("Hello World!", "text/plain");
  2720. });
  2721. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2722. auto se = detail::scope_exit([&] {
  2723. svr.stop();
  2724. thread.join();
  2725. ASSERT_FALSE(svr.is_running());
  2726. });
  2727. svr.wait_until_ready();
  2728. Client cli(HOST, PORT);
  2729. cli.set_connection_timeout(std::chrono::seconds(5));
  2730. auto res =
  2731. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2732. "application/json", [](uint64_t, uint64_t) { return true; });
  2733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2734. EXPECT_EQ("Hello World!", res->body);
  2735. EXPECT_EQ(StatusCode::OK_200, res->status);
  2736. }
  2737. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2738. Server svr;
  2739. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2740. res.set_content("Hello World!", "text/plain");
  2741. });
  2742. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2743. auto se = detail::scope_exit([&] {
  2744. svr.stop();
  2745. thread.join();
  2746. ASSERT_FALSE(svr.is_running());
  2747. });
  2748. svr.wait_until_ready();
  2749. Client cli(HOST, PORT);
  2750. cli.set_connection_timeout(std::chrono::seconds(5));
  2751. auto res =
  2752. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2753. "application/json", [](uint64_t, uint64_t) { return false; });
  2754. ASSERT_TRUE(!res);
  2755. EXPECT_EQ(Error::Canceled, res.error());
  2756. }
  2757. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2758. Server svr;
  2759. svr.set_payload_max_length(200 * 1024 * 1024);
  2760. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2761. res.set_content(LARGE_DATA, "text/plain");
  2762. });
  2763. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2764. auto se = detail::scope_exit([&] {
  2765. svr.stop();
  2766. thread.join();
  2767. ASSERT_FALSE(svr.is_running());
  2768. });
  2769. svr.wait_until_ready();
  2770. Client cli(HOST, PORT);
  2771. cli.set_payload_max_length(200 * 1024 * 1024);
  2772. cli.set_connection_timeout(std::chrono::seconds(5));
  2773. auto res =
  2774. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2775. "application/json", [](uint64_t, uint64_t) { return false; });
  2776. ASSERT_TRUE(!res);
  2777. EXPECT_EQ(Error::Canceled, res.error());
  2778. }
  2779. TEST(CancelTest, NoCancelDelete) {
  2780. Server svr;
  2781. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2782. res.set_content("Hello World!", "text/plain");
  2783. });
  2784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2785. auto se = detail::scope_exit([&] {
  2786. svr.stop();
  2787. thread.join();
  2788. ASSERT_FALSE(svr.is_running());
  2789. });
  2790. svr.wait_until_ready();
  2791. Client cli(HOST, PORT);
  2792. cli.set_connection_timeout(std::chrono::seconds(5));
  2793. auto res =
  2794. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2795. "application/json", [](uint64_t, uint64_t) { return true; });
  2796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2797. EXPECT_EQ("Hello World!", res->body);
  2798. EXPECT_EQ(StatusCode::OK_200, res->status);
  2799. }
  2800. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2801. Server svr;
  2802. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2803. res.set_content("Hello World!", "text/plain");
  2804. });
  2805. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2806. auto se = detail::scope_exit([&] {
  2807. svr.stop();
  2808. thread.join();
  2809. ASSERT_FALSE(svr.is_running());
  2810. });
  2811. svr.wait_until_ready();
  2812. Client cli(HOST, PORT);
  2813. cli.set_connection_timeout(std::chrono::seconds(5));
  2814. auto res =
  2815. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2816. "application/json", [](uint64_t, uint64_t) { return false; });
  2817. ASSERT_TRUE(!res);
  2818. EXPECT_EQ(Error::Canceled, res.error());
  2819. }
  2820. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2821. Server svr;
  2822. svr.set_payload_max_length(200 * 1024 * 1024);
  2823. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2824. res.set_content(LARGE_DATA, "text/plain");
  2825. });
  2826. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2827. auto se = detail::scope_exit([&] {
  2828. svr.stop();
  2829. thread.join();
  2830. ASSERT_FALSE(svr.is_running());
  2831. });
  2832. svr.wait_until_ready();
  2833. Client cli(HOST, PORT);
  2834. cli.set_payload_max_length(200 * 1024 * 1024);
  2835. cli.set_connection_timeout(std::chrono::seconds(5));
  2836. auto res =
  2837. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2838. "application/json", [](uint64_t, uint64_t) { return false; });
  2839. ASSERT_TRUE(!res);
  2840. EXPECT_EQ(Error::Canceled, res.error());
  2841. }
  2842. static std::string remove_whitespace(const std::string &input) {
  2843. std::string output;
  2844. output.reserve(input.size());
  2845. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2846. [](unsigned char c) { return !std::isspace(c); });
  2847. return output;
  2848. }
  2849. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2850. auto host = "httpbingo.org";
  2851. auto path = std::string{"/basic-auth/hello/world"};
  2852. #ifdef CPPHTTPLIB_SSL_ENABLED
  2853. auto port = 443;
  2854. SSLClient cli(host, port);
  2855. #else
  2856. auto port = 80;
  2857. Client cli(host, port);
  2858. #endif
  2859. {
  2860. auto res = cli.Get(path);
  2861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2862. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2863. }
  2864. {
  2865. auto res = cli.Get(
  2866. path, Headers{make_basic_authentication_header("hello", "world")});
  2867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2868. auto body = remove_whitespace(res->body);
  2869. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2870. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2871. EXPECT_EQ(StatusCode::OK_200, res->status);
  2872. }
  2873. {
  2874. cli.set_basic_auth("hello", "world");
  2875. auto res = cli.Get(path);
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. auto body = remove_whitespace(res->body);
  2878. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2879. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2880. EXPECT_EQ(StatusCode::OK_200, res->status);
  2881. }
  2882. {
  2883. cli.set_basic_auth("hello", "bad");
  2884. auto res = cli.Get(path);
  2885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2886. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2887. }
  2888. {
  2889. cli.set_basic_auth("bad", "world");
  2890. auto res = cli.Get(path);
  2891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2892. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2893. }
  2894. }
  2895. #ifdef CPPHTTPLIB_SSL_ENABLED
  2896. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2897. auto host = "httpbingo.org";
  2898. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2899. auto paths = std::vector<std::string>{
  2900. "/digest-auth/auth/hello/world/MD5",
  2901. "/digest-auth/auth/hello/world/SHA-256",
  2902. };
  2903. auto port = 443;
  2904. SSLClient cli(host, port);
  2905. {
  2906. auto res = cli.Get(unauth_path);
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2909. }
  2910. {
  2911. cli.set_digest_auth("hello", "world");
  2912. for (const auto &path : paths) {
  2913. auto res = cli.Get(path.c_str());
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. auto body = remove_whitespace(res->body);
  2916. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2917. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2918. EXPECT_EQ(StatusCode::OK_200, res->status);
  2919. }
  2920. cli.set_digest_auth("hello", "bad");
  2921. for (const auto &path : paths) {
  2922. auto res = cli.Get(path.c_str());
  2923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2924. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2925. }
  2926. }
  2927. }
  2928. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2929. // comma-separated list of challenges, and each challenge may itself carry a
  2930. // comma-separated auth-param list, so a server can legally offer Basic
  2931. // before Digest, either as two field lines or packed into one. Runs one 401
  2932. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2933. // value() joins them in receipt order) and checks that the retry carries a
  2934. // well-formed Digest Authorization header naming expected_realm.
  2935. static void
  2936. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2937. const std::string &expected_realm) {
  2938. std::atomic<int> hits{0};
  2939. Server svr;
  2940. svr.Get("/x", [&](const Request &req, Response &res) {
  2941. if (++hits == 1) {
  2942. res.status = StatusCode::Unauthorized_401;
  2943. for (const auto &challenge : challenges) {
  2944. res.set_header("WWW-Authenticate", challenge);
  2945. }
  2946. } else {
  2947. auto authorization = req.get_header_value("Authorization");
  2948. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2949. EXPECT_NE(std::string::npos,
  2950. authorization.find("realm=\"" + expected_realm + "\""));
  2951. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2952. res.set_content("ok", "text/plain");
  2953. }
  2954. });
  2955. auto port = svr.bind_to_any_port(HOST);
  2956. std::thread t([&]() { svr.listen_after_bind(); });
  2957. auto se = detail::scope_exit([&] {
  2958. svr.stop();
  2959. t.join();
  2960. });
  2961. svr.wait_until_ready();
  2962. Client cli(HOST, port);
  2963. cli.set_digest_auth("hello", "world");
  2964. auto res = cli.Get("/x");
  2965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2966. EXPECT_EQ(2, hits.load());
  2967. }
  2968. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2969. static const char *kDigestChallenge =
  2970. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2971. "algorithm=MD5";
  2972. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2973. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2974. "testrealm");
  2975. }
  2976. // Same challenge list with the schemes in the opposite order, to make sure
  2977. // the fix above didn't just special-case "Basic first".
  2978. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2979. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2980. "testrealm");
  2981. }
  2982. // A comma inside a quoted auth-param value must not be mistaken for the
  2983. // separator between two challenges (or two auth-params).
  2984. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2985. run_digest_challenge_list_test(
  2986. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2987. "algorithm=MD5"},
  2988. "test,realm");
  2989. }
  2990. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2991. // the params and leaves out the fragment.
  2992. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2993. Server svr;
  2994. std::string uri, target;
  2995. svr.Get("/a b", [&](const Request &req, Response &res) {
  2996. auto auth = req.get_header_value("Authorization");
  2997. if (auth.empty()) {
  2998. res.status = StatusCode::Unauthorized_401;
  2999. res.set_header("WWW-Authenticate",
  3000. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3001. return;
  3002. }
  3003. auto b = auth.find("uri=\"") + 5;
  3004. uri = auth.substr(b, auth.find('"', b) - b);
  3005. target = req.target;
  3006. });
  3007. auto port = svr.bind_to_any_port(HOST);
  3008. std::thread t([&]() { svr.listen_after_bind(); });
  3009. auto se = detail::scope_exit([&] {
  3010. svr.stop();
  3011. t.join();
  3012. });
  3013. svr.wait_until_ready();
  3014. Client cli(HOST, port);
  3015. cli.set_digest_auth("hello", "world");
  3016. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3018. EXPECT_EQ("/a%20b?x=1", target);
  3019. EXPECT_EQ(target, uri);
  3020. }
  3021. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3022. // make_digest_authentication_header() dereferences both unconditionally, so
  3023. // a server sending a challenge missing either one must not be treated as
  3024. // usable -- doing so used to crash the client with std::out_of_range.
  3025. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3026. Server svr;
  3027. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3028. res.status = StatusCode::Unauthorized_401;
  3029. res.set_header("WWW-Authenticate", challenge);
  3030. });
  3031. auto port = svr.bind_to_any_port(HOST);
  3032. std::thread t([&]() { svr.listen_after_bind(); });
  3033. auto se = detail::scope_exit([&] {
  3034. svr.stop();
  3035. t.join();
  3036. });
  3037. svr.wait_until_ready();
  3038. Client cli(HOST, port);
  3039. cli.set_digest_auth("hello", "world");
  3040. auto res = cli.Get("/x");
  3041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3042. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3043. }
  3044. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3045. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3046. }
  3047. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3048. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3049. }
  3050. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3051. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3052. }
  3053. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3054. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3055. // when storing the values, so the header builder has to re-escape them (and
  3056. // keep algorithm a bare token); otherwise the value breaks out of its
  3057. // quoted-string and injects extra auth-params into the client's Authorization.
  3058. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3059. std::atomic<int> hits{0};
  3060. std::string authorization;
  3061. Server svr;
  3062. svr.Get("/x", [&](const Request &req, Response &res) {
  3063. if (++hits == 1) {
  3064. res.status = StatusCode::Unauthorized_401;
  3065. // On the wire the quotes embedded in the values are backslash-escaped.
  3066. res.set_header("WWW-Authenticate",
  3067. "Digest realm=\"testrealm\", "
  3068. "nonce=\"n\\\"; injected=\\\"x\", "
  3069. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3070. } else {
  3071. authorization = req.get_header_value("Authorization");
  3072. res.set_content("ok", "text/plain");
  3073. }
  3074. });
  3075. auto port = svr.bind_to_any_port(HOST);
  3076. std::thread t([&]() { svr.listen_after_bind(); });
  3077. auto se = detail::scope_exit([&] {
  3078. svr.stop();
  3079. t.join();
  3080. });
  3081. svr.wait_until_ready();
  3082. Client cli(HOST, port);
  3083. cli.set_digest_auth("hello", "world");
  3084. auto res = cli.Get("/x");
  3085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3086. EXPECT_EQ(2, hits.load());
  3087. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3088. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3089. // inside its quoted-string rather than starting an "injected" auth-param.
  3090. EXPECT_NE(std::string::npos,
  3091. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3092. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3093. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3094. }
  3095. #endif
  3096. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3097. auto host = "google.com";
  3098. auto another_host = "example.com";
  3099. auto wrong_ip = "0.0.0.0";
  3100. #ifdef CPPHTTPLIB_SSL_ENABLED
  3101. SSLClient cli(host);
  3102. #else
  3103. Client cli(host);
  3104. #endif
  3105. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3106. auto res = cli.Get("/");
  3107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3108. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3109. }
  3110. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3111. auto host = "google.com";
  3112. auto wrong_ip = "0.0.0.0";
  3113. #ifdef CPPHTTPLIB_SSL_ENABLED
  3114. SSLClient cli(host);
  3115. #else
  3116. Client cli(host);
  3117. #endif
  3118. cli.set_hostname_addr_map({{host, wrong_ip}});
  3119. auto res = cli.Get("/");
  3120. ASSERT_TRUE(!res);
  3121. EXPECT_EQ(Error::Connection, res.error());
  3122. }
  3123. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3124. // A mapped value that is not an IP literal must be resolved. "localhost"
  3125. // resolves from the hosts file, so this test needs no external DNS.
  3126. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3127. auto host = "target.invalid";
  3128. Server svr;
  3129. std::string received_host;
  3130. svr.Get("/hi", [&](const Request &req, Response &res) {
  3131. received_host = req.get_header_value("Host");
  3132. res.set_content("Hello World!", "text/plain");
  3133. });
  3134. auto port = svr.bind_to_any_port(HOST);
  3135. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3136. auto se = detail::scope_exit([&] {
  3137. svr.stop();
  3138. thread.join();
  3139. ASSERT_FALSE(svr.is_running());
  3140. });
  3141. svr.wait_until_ready();
  3142. Client cli(host, port);
  3143. cli.set_hostname_addr_map({{host, HOST}});
  3144. auto res = cli.Get("/hi");
  3145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3146. EXPECT_EQ(StatusCode::OK_200, res->status);
  3147. // The mapping only redirects the connection; the identity stays host_.
  3148. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3149. }
  3150. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3151. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3152. auto host = "target.invalid";
  3153. Server svr;
  3154. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3155. res.set_content("Hello World!", "text/plain");
  3156. });
  3157. auto port = svr.bind_to_any_port("127.0.0.1");
  3158. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3159. auto se = detail::scope_exit([&] {
  3160. svr.stop();
  3161. thread.join();
  3162. ASSERT_FALSE(svr.is_running());
  3163. });
  3164. svr.wait_until_ready();
  3165. Client cli(host, port);
  3166. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3167. auto res = cli.Get("/hi");
  3168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3169. EXPECT_EQ(StatusCode::OK_200, res->status);
  3170. }
  3171. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3172. // An empty mapped value must leave host_ as the connection target. Without
  3173. // that guard the empty value would become the host argument, getaddrinfo
  3174. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3175. // loopback - silently connecting somewhere the caller never asked for.
  3176. // The server listens on loopback, so such a fallback would succeed and is
  3177. // therefore observable as a failure of this test.
  3178. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3179. Server svr;
  3180. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3181. res.set_content("Hello World!", "text/plain");
  3182. });
  3183. auto port = svr.bind_to_any_port(HOST);
  3184. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3185. auto se = detail::scope_exit([&] {
  3186. svr.stop();
  3187. thread.join();
  3188. ASSERT_FALSE(svr.is_running());
  3189. });
  3190. svr.wait_until_ready();
  3191. Client cli(blackhole, port);
  3192. cli.set_hostname_addr_map({{blackhole, ""}});
  3193. cli.set_connection_timeout(1);
  3194. auto res = cli.Get("/hi");
  3195. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3196. }
  3197. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3198. auto host = "httpbingo.org";
  3199. auto path = std::string{"/absolute-redirect/3"};
  3200. #ifdef CPPHTTPLIB_SSL_ENABLED
  3201. SSLClient cli(host);
  3202. #else
  3203. Client cli(host);
  3204. #endif
  3205. cli.set_follow_location(true);
  3206. auto res = cli.Get(path);
  3207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3208. EXPECT_EQ(StatusCode::OK_200, res->status);
  3209. }
  3210. TEST(RedirectTest, Redirect_Online) {
  3211. auto host = "httpbingo.org";
  3212. auto path = std::string{"/redirect/3"};
  3213. #ifdef CPPHTTPLIB_SSL_ENABLED
  3214. SSLClient cli(host);
  3215. #else
  3216. Client cli(host);
  3217. #endif
  3218. cli.set_follow_location(true);
  3219. auto res = cli.Get(path);
  3220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3221. EXPECT_EQ(StatusCode::OK_200, res->status);
  3222. }
  3223. TEST(RelativeRedirectTest, Redirect_Online) {
  3224. auto host = "httpbingo.org";
  3225. auto path = std::string{"/relative-redirect/3"};
  3226. #ifdef CPPHTTPLIB_SSL_ENABLED
  3227. SSLClient cli(host);
  3228. #else
  3229. Client cli(host);
  3230. #endif
  3231. cli.set_follow_location(true);
  3232. auto res = cli.Get(path);
  3233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3234. EXPECT_EQ(StatusCode::OK_200, res->status);
  3235. }
  3236. TEST(TooManyRedirectTest, Redirect_Online) {
  3237. auto host = "httpbingo.org";
  3238. auto path = std::string{"/redirect/21"};
  3239. #ifdef CPPHTTPLIB_SSL_ENABLED
  3240. SSLClient cli(host);
  3241. #else
  3242. Client cli(host);
  3243. #endif
  3244. cli.set_follow_location(true);
  3245. auto res = cli.Get(path);
  3246. ASSERT_TRUE(!res);
  3247. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3248. }
  3249. #ifdef CPPHTTPLIB_SSL_ENABLED
  3250. TEST(YahooRedirectTest, Redirect_Online) {
  3251. Client cli("yahoo.com");
  3252. auto res = cli.Get("/");
  3253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3254. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3255. cli.set_follow_location(true);
  3256. res = cli.Get("/");
  3257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3258. EXPECT_EQ(StatusCode::OK_200, res->status);
  3259. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3260. }
  3261. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3262. #define REDIR_HOST "httpbingo.org"
  3263. #define REDIR_PATH "/redirect-to"
  3264. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3265. SSLClient cli(REDIR_HOST);
  3266. cli.set_follow_location(true);
  3267. auto res =
  3268. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. EXPECT_EQ(StatusCode::OK_200, res->status);
  3271. }
  3272. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3273. SSLClient cli(REDIR_HOST);
  3274. cli.set_follow_location(true);
  3275. Params params;
  3276. params.emplace("url", "http://example.com");
  3277. params.emplace("status_code", "302");
  3278. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. }
  3282. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3283. SSLClient cli(REDIR_HOST);
  3284. cli.set_follow_location(true);
  3285. Params params;
  3286. params.emplace("url", "http://example.com");
  3287. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3289. EXPECT_EQ(StatusCode::OK_200, res->status);
  3290. }
  3291. TEST(UrlWithSpace, Redirect_Online) {
  3292. SSLClient cli("edge.forgecdn.net");
  3293. cli.set_follow_location(true);
  3294. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3298. }
  3299. #endif
  3300. #if !defined(_WIN32) && !defined(_WIN64)
  3301. TEST(ReceiveSignals, Signal) {
  3302. auto setupSignalHandlers = []() {
  3303. struct sigaction act;
  3304. sigemptyset(&act.sa_mask);
  3305. act.sa_flags = SA_SIGINFO;
  3306. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3307. switch (sig) {
  3308. case SIGINT:
  3309. default: break;
  3310. }
  3311. };
  3312. ::sigaction(SIGINT, &act, nullptr);
  3313. };
  3314. Server svr;
  3315. int port = 0;
  3316. auto thread = std::thread([&]() {
  3317. setupSignalHandlers();
  3318. port = svr.bind_to_any_port(HOST);
  3319. svr.listen_after_bind();
  3320. });
  3321. auto se = detail::scope_exit([&] {
  3322. svr.stop();
  3323. thread.join();
  3324. ASSERT_FALSE(svr.is_running());
  3325. });
  3326. svr.wait_until_ready();
  3327. ASSERT_TRUE(svr.is_running());
  3328. pthread_kill(thread.native_handle(), SIGINT);
  3329. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3330. ASSERT_TRUE(svr.is_running());
  3331. }
  3332. #endif
  3333. TEST(RedirectToDifferentPort, Redirect) {
  3334. Server svr1;
  3335. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3336. res.set_content("Hello World!", "text/plain");
  3337. });
  3338. int svr1_port = 0;
  3339. auto thread1 = std::thread([&]() {
  3340. svr1_port = svr1.bind_to_any_port(HOST);
  3341. svr1.listen_after_bind();
  3342. });
  3343. Server svr2;
  3344. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3345. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3346. });
  3347. int svr2_port = 0;
  3348. auto thread2 = std::thread([&]() {
  3349. svr2_port = svr2.bind_to_any_port(HOST);
  3350. svr2.listen_after_bind();
  3351. });
  3352. auto se = detail::scope_exit([&] {
  3353. svr2.stop();
  3354. thread2.join();
  3355. svr1.stop();
  3356. thread1.join();
  3357. ASSERT_FALSE(svr2.is_running());
  3358. ASSERT_FALSE(svr1.is_running());
  3359. });
  3360. svr1.wait_until_ready();
  3361. svr2.wait_until_ready();
  3362. Client cli("localhost", svr2_port);
  3363. cli.set_follow_location(true);
  3364. auto res = cli.Get("/2");
  3365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3366. EXPECT_EQ(StatusCode::OK_200, res->status);
  3367. EXPECT_EQ("Hello World!", res->body);
  3368. }
  3369. // GET /redir on one server redirects to /target on another port, so the
  3370. // client follows it with a new client.
  3371. static Result
  3372. GetThroughRedirectToDifferentPort(Server::Handler target,
  3373. const std::function<void(Client &)> &setup,
  3374. const Headers &headers = Headers()) {
  3375. Server target_svr;
  3376. target_svr.Get("/target", target);
  3377. int target_port = 0;
  3378. auto target_thread = std::thread([&]() {
  3379. target_port = target_svr.bind_to_any_port(HOST);
  3380. target_svr.listen_after_bind();
  3381. });
  3382. Server origin_svr;
  3383. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3384. res.set_redirect(
  3385. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3386. });
  3387. int origin_port = 0;
  3388. auto origin_thread = std::thread([&]() {
  3389. origin_port = origin_svr.bind_to_any_port(HOST);
  3390. origin_svr.listen_after_bind();
  3391. });
  3392. auto se = detail::scope_exit([&] {
  3393. origin_svr.stop();
  3394. origin_thread.join();
  3395. target_svr.stop();
  3396. target_thread.join();
  3397. });
  3398. target_svr.wait_until_ready();
  3399. origin_svr.wait_until_ready();
  3400. Client cli("localhost", origin_port);
  3401. cli.set_follow_location(true);
  3402. setup(cli);
  3403. return cli.Get("/redir", headers);
  3404. }
  3405. static void
  3406. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3407. std::string captured_authorization;
  3408. auto result = GetThroughRedirectToDifferentPort(
  3409. [&](const Request &req, Response &res) {
  3410. captured_authorization = req.get_header_value("Authorization");
  3411. res.set_content("OK", "text/plain");
  3412. },
  3413. set_auth);
  3414. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3415. EXPECT_EQ(StatusCode::OK_200, result->status);
  3416. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3417. EXPECT_TRUE(captured_authorization.empty());
  3418. }
  3419. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3420. TestDoNotForwardCredentialsOnRedirect(
  3421. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3422. }
  3423. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3424. TestDoNotForwardCredentialsOnRedirect(
  3425. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3426. }
  3427. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3428. std::string captured_cookie;
  3429. auto result = GetThroughRedirectToDifferentPort(
  3430. [&](const Request &req, Response &res) {
  3431. captured_cookie = req.get_header_value("Cookie");
  3432. res.set_content("OK", "text/plain");
  3433. },
  3434. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3435. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3436. EXPECT_EQ(StatusCode::OK_200, result->status);
  3437. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3438. EXPECT_TRUE(captured_cookie.empty());
  3439. }
  3440. TEST(RedirectToSamePort, ForwardCookie) {
  3441. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3442. // header so that ordinary session flows keep working.
  3443. Server svr;
  3444. std::string captured_cookie;
  3445. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3446. res.set_redirect("/target", 302);
  3447. });
  3448. svr.Get("/target", [&](const Request &req, Response &res) {
  3449. captured_cookie = req.get_header_value("Cookie");
  3450. res.set_content("OK", "text/plain");
  3451. });
  3452. auto port = svr.bind_to_any_port(HOST);
  3453. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3454. auto se = detail::scope_exit([&] {
  3455. svr.stop();
  3456. thread.join();
  3457. ASSERT_FALSE(svr.is_running());
  3458. });
  3459. svr.wait_until_ready();
  3460. Client cli(HOST, port);
  3461. cli.set_follow_location(true);
  3462. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3463. auto res = cli.Get("/redir", headers);
  3464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3465. EXPECT_EQ(StatusCode::OK_200, res->status);
  3466. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3467. }
  3468. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3469. std::string authorization;
  3470. std::string trace_id;
  3471. auto result = GetThroughRedirectToDifferentPort(
  3472. [&](const Request &req, Response &res) {
  3473. authorization = req.get_header_value("Authorization");
  3474. trace_id = req.get_header_value("X-Trace-Id");
  3475. res.set_content("OK", "text/plain");
  3476. },
  3477. [](Client &cli) {
  3478. cli.set_default_headers(
  3479. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3480. });
  3481. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3482. EXPECT_EQ(StatusCode::OK_200, result->status);
  3483. // Like a header given with the request, a default one goes along unless it
  3484. // carries credentials (RFC 9110 15.4).
  3485. EXPECT_TRUE(authorization.empty());
  3486. EXPECT_EQ("42", trace_id);
  3487. }
  3488. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3489. auto result = GetThroughRedirectToDifferentPort(
  3490. [](const Request &, Response &res) {
  3491. res.set_content(std::string(2048, 'x'), "text/plain");
  3492. },
  3493. [](Client &cli) { cli.set_payload_max_length(1024); });
  3494. EXPECT_FALSE(result);
  3495. }
  3496. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3497. auto result = GetThroughRedirectToDifferentPort(
  3498. [](const Request &req, Response &res) {
  3499. // Answer after a second, or once the client gives up.
  3500. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3501. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3502. }
  3503. res.set_content("late", "text/plain");
  3504. },
  3505. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3506. ASSERT_FALSE(result);
  3507. EXPECT_EQ(Error::Read, result.error());
  3508. }
  3509. #ifdef CPPHTTPLIB_SSL_ENABLED
  3510. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3511. auto result = GetThroughRedirectToDifferentPort(
  3512. [](const Request &, Response &res) {
  3513. res.status = StatusCode::Unauthorized_401;
  3514. res.set_header("WWW-Authenticate",
  3515. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3516. },
  3517. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3518. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3519. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3520. }
  3521. #endif
  3522. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3523. Server svr;
  3524. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3525. // Port number that overflows int — should not crash
  3526. res.set_redirect("http://localhost:99999999999999999999/target");
  3527. });
  3528. auto port = svr.bind_to_any_port(HOST);
  3529. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3530. auto se = detail::scope_exit([&] {
  3531. svr.stop();
  3532. thread.join();
  3533. ASSERT_FALSE(svr.is_running());
  3534. });
  3535. svr.wait_until_ready();
  3536. Client cli(HOST, port);
  3537. cli.set_follow_location(true);
  3538. auto res = cli.Get("/redir");
  3539. // Should fail gracefully, not crash (no valid response due to bad port)
  3540. EXPECT_FALSE(res);
  3541. }
  3542. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3543. Server svr;
  3544. auto port = svr.bind_to_any_port(HOST);
  3545. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3546. // The server's own port followed by junk must not be followed
  3547. res.set_redirect("http://" + std::string(HOST) + ":" +
  3548. std::to_string(port) + "junk/target");
  3549. });
  3550. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3551. res.set_content("target", "text/plain");
  3552. });
  3553. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3554. auto se = detail::scope_exit([&] {
  3555. svr.stop();
  3556. thread.join();
  3557. ASSERT_FALSE(svr.is_running());
  3558. });
  3559. svr.wait_until_ready();
  3560. Client cli(HOST, port);
  3561. cli.set_follow_location(true);
  3562. auto res = cli.Get("/redir");
  3563. EXPECT_FALSE(res);
  3564. }
  3565. TEST(RedirectFromPageWithContent, Redirect) {
  3566. Server svr;
  3567. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3568. res.set_content("___", "text/plain");
  3569. res.set_redirect("/2");
  3570. });
  3571. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3572. res.set_content("Hello World!", "text/plain");
  3573. });
  3574. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3575. auto se = detail::scope_exit([&] {
  3576. svr.stop();
  3577. th.join();
  3578. ASSERT_FALSE(svr.is_running());
  3579. });
  3580. svr.wait_until_ready();
  3581. {
  3582. Client cli("localhost", PORT);
  3583. cli.set_follow_location(true);
  3584. std::string body;
  3585. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3586. body.append(data, data_length);
  3587. return true;
  3588. });
  3589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3590. EXPECT_EQ(StatusCode::OK_200, res->status);
  3591. EXPECT_EQ("Hello World!", body);
  3592. }
  3593. {
  3594. Client cli("localhost", PORT);
  3595. std::string body;
  3596. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3597. body.append(data, data_length);
  3598. return true;
  3599. });
  3600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3601. EXPECT_EQ(StatusCode::Found_302, res->status);
  3602. EXPECT_EQ("___", body);
  3603. }
  3604. }
  3605. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3606. Server svr;
  3607. auto port_str = std::to_string(PORT);
  3608. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3609. auto expected_host = "[::1]:" + port_str;
  3610. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3611. res.set_content("___", "text/plain");
  3612. // res.set_redirect("/2");
  3613. res.set_redirect(redirect_url);
  3614. });
  3615. svr.Get("/2", [&](const Request &req, Response &res) {
  3616. auto host_header = req.headers.find("Host");
  3617. ASSERT_TRUE(host_header != req.headers.end());
  3618. EXPECT_EQ(expected_host, host_header->second);
  3619. res.set_content("Hello World!", "text/plain");
  3620. });
  3621. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3622. auto se = detail::scope_exit([&] {
  3623. svr.stop();
  3624. th.join();
  3625. ASSERT_FALSE(svr.is_running());
  3626. });
  3627. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3628. // actually starts anything, so the condition !svr.is_running() will
  3629. // always remain true, and the loop never stops.
  3630. // This basically counts how many milliseconds have passed since the
  3631. // call to svr.listen(), and if after 5 seconds nothing started yet
  3632. // aborts the test.
  3633. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3634. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3635. ASSERT_LT(milliseconds, 5000U);
  3636. }
  3637. {
  3638. Client cli("::1", PORT);
  3639. cli.set_follow_location(true);
  3640. std::string body;
  3641. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3642. body.append(data, data_length);
  3643. return true;
  3644. });
  3645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3646. EXPECT_EQ(StatusCode::OK_200, res->status);
  3647. EXPECT_EQ("Hello World!", body);
  3648. }
  3649. {
  3650. Client cli("::1", PORT);
  3651. std::string body;
  3652. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3653. body.append(data, data_length);
  3654. return true;
  3655. });
  3656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3657. EXPECT_EQ(StatusCode::Found_302, res->status);
  3658. EXPECT_EQ("___", body);
  3659. }
  3660. }
  3661. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3662. Server svr;
  3663. svr.Get("/foo", [](const Request &req, Response &res) {
  3664. auto a = req.params.find("a");
  3665. if (a != req.params.end()) {
  3666. res.set_content((*a).second, "text/plain");
  3667. res.status = StatusCode::OK_200;
  3668. } else {
  3669. res.status = StatusCode::BadRequest_400;
  3670. }
  3671. });
  3672. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3673. auto se = detail::scope_exit([&] {
  3674. svr.stop();
  3675. thread.join();
  3676. ASSERT_FALSE(svr.is_running());
  3677. });
  3678. svr.wait_until_ready();
  3679. {
  3680. Client cli(HOST, PORT);
  3681. cli.set_path_encode(false);
  3682. auto res = cli.Get("/foo?a=explicitly+encoded");
  3683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3684. EXPECT_EQ(StatusCode::OK_200, res->status);
  3685. // This expects it back with a space, as the `+` won't have been
  3686. // url-encoded, and server-side the params get decoded turning `+`
  3687. // into spaces.
  3688. EXPECT_EQ("explicitly encoded", res->body);
  3689. }
  3690. }
  3691. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3692. // When path encoding is disabled the client must transmit the supplied
  3693. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3694. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3695. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3696. // than a space (0x20). Assert on the raw wire target to catch this.
  3697. Server svr;
  3698. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3699. svr.Get("/foo", [&](const Request &req, Response &res) {
  3700. EXPECT_EQ(expected_target, req.target);
  3701. res.status = StatusCode::OK_200;
  3702. });
  3703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3704. auto se = detail::scope_exit([&] {
  3705. svr.stop();
  3706. thread.join();
  3707. ASSERT_FALSE(svr.is_running());
  3708. });
  3709. svr.wait_until_ready();
  3710. {
  3711. Client cli(HOST, PORT);
  3712. cli.set_path_encode(false);
  3713. auto res = cli.Get(expected_target.c_str());
  3714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3715. EXPECT_EQ(StatusCode::OK_200, res->status);
  3716. }
  3717. }
  3718. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3719. // `open_stream()` used to skip the path encoding that the buffered send
  3720. // path applies, so the same `path` produced different bytes in the request
  3721. // line depending on which API was used. Assert the two agree.
  3722. Server svr;
  3723. std::string target;
  3724. svr.Get(".*", [&](const Request &req, Response &res) {
  3725. target = req.target;
  3726. res.status = StatusCode::OK_200;
  3727. });
  3728. auto port = svr.bind_to_any_port(HOST);
  3729. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3730. auto se = detail::scope_exit([&] {
  3731. svr.stop();
  3732. thread.join();
  3733. ASSERT_FALSE(svr.is_running());
  3734. });
  3735. svr.wait_until_ready();
  3736. struct {
  3737. const char *path;
  3738. const char *expected;
  3739. } cases[] = {
  3740. {"/a b?x=1", "/a%20b?x=1"},
  3741. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3742. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3743. // Characters RFC 3986 doesn't allow in a path.
  3744. {"/\"<>\\^`{|}[]", "/%22%3C%3E%5C%5E%60%7B%7C%7D%5B%5D"},
  3745. // Escapes and the rest of pchar are kept.
  3746. {"/a%20b/!$&()*=:@~", "/a%20b/!$&()*=:@~"},
  3747. };
  3748. for (const auto &c : cases) {
  3749. Client cli(HOST, port);
  3750. target.clear();
  3751. auto res = cli.Get(c.path);
  3752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3753. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3754. auto buffered_target = target;
  3755. target.clear();
  3756. auto handle = cli.open_stream("GET", c.path);
  3757. EXPECT_TRUE(handle.is_valid())
  3758. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3759. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3760. }
  3761. }
  3762. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3763. // The `set_path_encode(false)` contract — transmit the supplied target
  3764. // verbatim — must hold for the streaming API too.
  3765. Server svr;
  3766. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3767. std::string target;
  3768. svr.Get("/foo", [&](const Request &req, Response &res) {
  3769. target = req.target;
  3770. res.status = StatusCode::OK_200;
  3771. });
  3772. auto port = svr.bind_to_any_port(HOST);
  3773. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3774. auto se = detail::scope_exit([&] {
  3775. svr.stop();
  3776. thread.join();
  3777. ASSERT_FALSE(svr.is_running());
  3778. });
  3779. svr.wait_until_ready();
  3780. {
  3781. Client cli(HOST, port);
  3782. cli.set_path_encode(false);
  3783. auto handle = cli.open_stream("GET", expected_target);
  3784. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3785. EXPECT_EQ(expected_target, target);
  3786. }
  3787. }
  3788. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3789. // With path encoding enabled a CR/LF in the target is percent-encoded
  3790. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3791. // write_request_line still backstops `set_path_encode(false)`, which is
  3792. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3793. Server svr;
  3794. // Captured before routing: the decoded path contains a newline, which a
  3795. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3796. std::string target;
  3797. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3798. target = req.target;
  3799. res.status = StatusCode::OK_200;
  3800. return Server::HandlerResponse::Handled;
  3801. });
  3802. auto port = svr.bind_to_any_port(HOST);
  3803. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3804. auto se = detail::scope_exit([&] {
  3805. svr.stop();
  3806. thread.join();
  3807. ASSERT_FALSE(svr.is_running());
  3808. });
  3809. svr.wait_until_ready();
  3810. {
  3811. Client cli(HOST, port);
  3812. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3813. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3814. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3815. }
  3816. }
  3817. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3818. // Every control character is percent-encoded, not just CR/LF, so the target
  3819. // passes the request-target check in write_request_line.
  3820. Server svr;
  3821. std::string target;
  3822. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3823. target = req.target;
  3824. res.status = StatusCode::OK_200;
  3825. return Server::HandlerResponse::Handled;
  3826. });
  3827. auto port = svr.bind_to_any_port(HOST);
  3828. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3829. auto se = detail::scope_exit([&] {
  3830. svr.stop();
  3831. thread.join();
  3832. ASSERT_FALSE(svr.is_running());
  3833. });
  3834. svr.wait_until_ready();
  3835. {
  3836. Client cli(HOST, port);
  3837. auto res = cli.Get("/a\tb\x1b\x7f");
  3838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3839. EXPECT_EQ("/a%09b%1B%7F", target);
  3840. // An embedded NUL doesn't cut the path short.
  3841. res = cli.Get(std::string("/a\0b", 4));
  3842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3843. EXPECT_EQ("/a%00b", target);
  3844. }
  3845. }
  3846. TEST(PathUrlEncodeTest, HostInProxyTargetIsNotEncoded) {
  3847. // Only the path of a target sent to a proxy is encoded, so the brackets of
  3848. // an IPv6 host stay.
  3849. Server proxy;
  3850. std::string target;
  3851. proxy.set_pre_routing_handler([&](const Request &req, Response &res) {
  3852. target = req.target;
  3853. res.status = StatusCode::Forbidden_403;
  3854. return Server::HandlerResponse::Handled;
  3855. });
  3856. auto port = proxy.bind_to_any_port(HOST);
  3857. auto thread = std::thread([&]() { proxy.listen_after_bind(); });
  3858. auto se = detail::scope_exit([&] {
  3859. proxy.stop();
  3860. thread.join();
  3861. ASSERT_FALSE(proxy.is_running());
  3862. });
  3863. proxy.wait_until_ready();
  3864. {
  3865. Client cli("::1", 8080);
  3866. cli.set_proxy(HOST, port);
  3867. auto res = cli.Get("/a b");
  3868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3869. EXPECT_EQ("http://[::1]:8080/a%20b", target);
  3870. }
  3871. #ifdef CPPHTTPLIB_SSL_ENABLED
  3872. {
  3873. SSLClient cli("::1", 8443);
  3874. cli.set_proxy(HOST, port);
  3875. auto res = cli.Get("/");
  3876. EXPECT_EQ(Error::ProxyConnection, res.error());
  3877. EXPECT_EQ("[::1]:8443", target);
  3878. }
  3879. #endif
  3880. }
  3881. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3882. // Nothing may reach the wire: a raw CR/LF target would split the request
  3883. // line and inject headers.
  3884. Server svr;
  3885. // Pre-routing so that "not called" means nothing reached the server at all,
  3886. // rather than merely failing to match a handler pattern.
  3887. auto handler_called = false;
  3888. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3889. handler_called = true;
  3890. res.status = StatusCode::OK_200;
  3891. return Server::HandlerResponse::Handled;
  3892. });
  3893. auto port = svr.bind_to_any_port(HOST);
  3894. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3895. auto se = detail::scope_exit([&] {
  3896. svr.stop();
  3897. thread.join();
  3898. ASSERT_FALSE(svr.is_running());
  3899. });
  3900. svr.wait_until_ready();
  3901. {
  3902. Client cli(HOST, port);
  3903. cli.set_path_encode(false);
  3904. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3905. EXPECT_FALSE(handle.is_valid());
  3906. EXPECT_EQ(Error::Write, handle.error);
  3907. EXPECT_FALSE(handler_called);
  3908. }
  3909. }
  3910. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3911. // Which of the two branches runs is decided by whether the query component
  3912. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3913. // an empty query and must still fall back to building one from
  3914. // `req.params`, while a non-empty query must win over `req.params`.
  3915. Server svr;
  3916. std::string target;
  3917. svr.Get("/foo", [&](const Request &req, Response &res) {
  3918. target = req.target;
  3919. res.status = StatusCode::OK_200;
  3920. });
  3921. auto port = svr.bind_to_any_port(HOST);
  3922. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3923. auto se = detail::scope_exit([&] {
  3924. svr.stop();
  3925. thread.join();
  3926. ASSERT_FALSE(svr.is_running());
  3927. });
  3928. svr.wait_until_ready();
  3929. {
  3930. // Trailing `?` -> empty query component -> `req.params` is used.
  3931. Client cli(HOST, port);
  3932. Request req;
  3933. req.method = "GET";
  3934. req.path = "/foo?";
  3935. req.params.emplace("a", "1");
  3936. target.clear();
  3937. auto res = cli.send(req);
  3938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3939. EXPECT_EQ("/foo?a=1", target);
  3940. }
  3941. {
  3942. // Non-empty query in `req.path` -> `req.params` is not appended.
  3943. Client cli(HOST, port);
  3944. Request req;
  3945. req.method = "GET";
  3946. req.path = "/foo?b=2";
  3947. req.params.emplace("a", "1");
  3948. target.clear();
  3949. auto res = cli.send(req);
  3950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3951. EXPECT_EQ("/foo?b=2", target);
  3952. }
  3953. }
  3954. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3955. Server svr;
  3956. svr.Get("/", [](const Request &req, Response &) {
  3957. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3958. });
  3959. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3960. auto se = detail::scope_exit([&] {
  3961. svr.stop();
  3962. thread.join();
  3963. ASSERT_FALSE(svr.is_running());
  3964. });
  3965. svr.wait_until_ready();
  3966. {
  3967. Client cli(HOST, PORT);
  3968. cli.set_path_encode(false);
  3969. auto res = cli.Get("/?something=%0A");
  3970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3971. EXPECT_EQ(StatusCode::OK_200, res->status);
  3972. }
  3973. }
  3974. TEST(BindServerTest, BindDualStack) {
  3975. Server svr;
  3976. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3977. res.set_content("Hello World!", "text/plain");
  3978. });
  3979. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3980. auto se = detail::scope_exit([&] {
  3981. svr.stop();
  3982. thread.join();
  3983. ASSERT_FALSE(svr.is_running());
  3984. });
  3985. svr.wait_until_ready();
  3986. {
  3987. Client cli("127.0.0.1", PORT);
  3988. auto res = cli.Get("/1");
  3989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3990. EXPECT_EQ(StatusCode::OK_200, res->status);
  3991. EXPECT_EQ("Hello World!", res->body);
  3992. }
  3993. {
  3994. Client cli("::1", PORT);
  3995. auto res = cli.Get("/1");
  3996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3997. EXPECT_EQ(StatusCode::OK_200, res->status);
  3998. EXPECT_EQ("Hello World!", res->body);
  3999. }
  4000. }
  4001. TEST(BindServerTest, BindAndListenSeparately) {
  4002. Server svr;
  4003. int port = svr.bind_to_any_port("0.0.0.0");
  4004. ASSERT_TRUE(svr.is_valid());
  4005. ASSERT_TRUE(port > 0);
  4006. svr.stop();
  4007. }
  4008. // Reports whether anything is still listening on a loopback port. A plain
  4009. // connect() is used instead of a Client request because a socket left bound by
  4010. // mistake accepts the connection into its backlog and never answers, which
  4011. // would hang the test instead of failing it.
  4012. static bool is_loopback_port_accepting(int port) {
  4013. sockaddr_in addr{};
  4014. addr.sin_family = AF_INET;
  4015. addr.sin_port = htons(static_cast<uint16_t>(port));
  4016. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4017. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4018. EXPECT_NE(sock, INVALID_SOCKET);
  4019. if (sock == INVALID_SOCKET) { return false; }
  4020. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4021. static_cast<socklen_t>(sizeof(addr)));
  4022. detail::close_socket(sock);
  4023. return ret == 0;
  4024. }
  4025. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4026. Server svr;
  4027. auto port = svr.bind_to_any_port("127.0.0.1");
  4028. ASSERT_TRUE(port > 0);
  4029. svr.stop();
  4030. // bind_to_any_port() already called listen(2), so until stop() closed the
  4031. // descriptor the port kept accepting connections into the backlog. ASSERT
  4032. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4033. // below blocks forever in the accept loop.
  4034. ASSERT_FALSE(is_loopback_port_accepting(port));
  4035. // Nothing is left to accept on, so listen_after_bind() must report failure
  4036. // instead of returning success without ever serving.
  4037. EXPECT_FALSE(svr.listen_after_bind());
  4038. // The failed listen marks the server decommissioned, so a waiter returns
  4039. // instead of spinning forever.
  4040. svr.wait_until_ready();
  4041. }
  4042. #ifdef CPPHTTPLIB_SSL_ENABLED
  4043. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4044. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4045. CLIENT_CA_CERT_DIR);
  4046. int port = svr.bind_to_any_port("0.0.0.0");
  4047. ASSERT_TRUE(svr.is_valid());
  4048. ASSERT_TRUE(port > 0);
  4049. svr.stop();
  4050. }
  4051. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4052. // or a rejected CustomRoute() registration would not stop the server binding.
  4053. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4054. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4055. CLIENT_CA_CERT_DIR);
  4056. ASSERT_TRUE(svr.is_valid());
  4057. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4058. EXPECT_FALSE(svr.is_valid());
  4059. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4060. }
  4061. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4062. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4063. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4064. int port = svr.bind_to_any_port("0.0.0.0");
  4065. ASSERT_TRUE(svr.is_valid());
  4066. ASSERT_TRUE(port > 0);
  4067. svr.stop();
  4068. }
  4069. TEST(BindServerTest, UpdateCertsPem) {
  4070. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4071. int port = svr.bind_to_any_port("0.0.0.0");
  4072. ASSERT_TRUE(svr.is_valid());
  4073. ASSERT_TRUE(port > 0);
  4074. // Read PEM files
  4075. std::string cert_pem, key_pem, ca_pem;
  4076. read_file(SERVER_CERT_FILE, cert_pem);
  4077. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4078. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4079. // Update server certificates using PEM API
  4080. ASSERT_TRUE(
  4081. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4082. ASSERT_TRUE(svr.is_valid());
  4083. svr.stop();
  4084. }
  4085. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4086. // Start server with client CA (enables client auth)
  4087. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4088. ASSERT_TRUE(svr.is_valid());
  4089. bool handler_called = false;
  4090. svr.Get("/test", [&](const Request &req, Response &res) {
  4091. handler_called = true;
  4092. // Verify client certificate is present
  4093. auto cert = req.peer_cert();
  4094. EXPECT_TRUE(static_cast<bool>(cert));
  4095. res.set_content("ok", "text/plain");
  4096. });
  4097. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4098. auto se = detail::scope_exit([&] {
  4099. svr.stop();
  4100. t.join();
  4101. ASSERT_FALSE(svr.is_running());
  4102. });
  4103. svr.wait_until_ready();
  4104. // Read PEM files
  4105. std::string cert_pem, key_pem, ca_pem;
  4106. read_file(SERVER_CERT_FILE, cert_pem);
  4107. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4108. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4109. // Update server certificates and client CA using PEM API while server running
  4110. ASSERT_TRUE(
  4111. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4112. // Connect with client certificate
  4113. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4114. cli.enable_server_certificate_verification(false);
  4115. cli.set_connection_timeout(30);
  4116. auto res = cli.Get("/test");
  4117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4118. ASSERT_EQ(StatusCode::OK_200, res->status);
  4119. ASSERT_TRUE(handler_called);
  4120. EXPECT_EQ("ok", res->body);
  4121. }
  4122. // Puts a CA that did not sign the client's certificate in the old one's place.
  4123. static bool replace_client_ca(SSLServer &svr) {
  4124. std::string cert_pem, key_pem, ca_pem;
  4125. read_file(SERVER_CERT_FILE, cert_pem);
  4126. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4127. read_file(SERVER_CERT2_FILE, ca_pem);
  4128. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4129. ca_pem.c_str());
  4130. }
  4131. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4132. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4133. ASSERT_TRUE(svr.is_valid());
  4134. svr.Get("/test", [](const Request &, Response &res) {
  4135. res.set_content("ok", "text/plain");
  4136. });
  4137. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4138. auto se = detail::scope_exit([&] {
  4139. svr.stop();
  4140. t.join();
  4141. ASSERT_FALSE(svr.is_running());
  4142. });
  4143. svr.wait_until_ready();
  4144. auto get = [] {
  4145. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4146. cli.enable_server_certificate_verification(false);
  4147. return cli.Get("/test");
  4148. };
  4149. ASSERT_TRUE(get());
  4150. ASSERT_TRUE(replace_client_ca(svr));
  4151. EXPECT_FALSE(get());
  4152. }
  4153. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4154. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4155. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4156. ASSERT_TRUE(svr.is_valid());
  4157. tls::set_verify_callback(svr.tls_context(),
  4158. [](const tls::VerifyContext &) -> bool {
  4159. throw std::runtime_error("verify");
  4160. });
  4161. svr.Get("/test", [](const Request &, Response &res) {
  4162. res.set_content("ok", "text/plain");
  4163. });
  4164. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4165. auto se = detail::scope_exit([&] {
  4166. svr.stop();
  4167. t.join();
  4168. ASSERT_FALSE(svr.is_running());
  4169. });
  4170. svr.wait_until_ready();
  4171. auto get = [] {
  4172. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4173. cli.enable_server_certificate_verification(false);
  4174. return cli.Get("/test");
  4175. };
  4176. EXPECT_FALSE(get());
  4177. // The handshake is over, so an update does not wait for it.
  4178. std::string cert_pem, key_pem;
  4179. read_file(SERVER_CERT_FILE, cert_pem);
  4180. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4181. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4182. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4183. return v.preverify_ok;
  4184. });
  4185. auto res = get();
  4186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4187. EXPECT_EQ("ok", res->body);
  4188. }
  4189. #endif
  4190. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4191. // Sends each request over a new connection with a client certificate,
  4192. // resuming the session of the one before when there is one.
  4193. class ResumingClient {
  4194. public:
  4195. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4196. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4197. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4198. SSL_FILETYPE_PEM);
  4199. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4200. // callback, not through SSL_get1_session().
  4201. SSL_CTX_set_app_data(ctx_, this);
  4202. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4203. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4204. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4205. auto self = static_cast<ResumingClient *>(
  4206. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4207. SSL_SESSION_free(self->session_);
  4208. self->session_ = session;
  4209. return 1; // Keeps the reference
  4210. });
  4211. }
  4212. ~ResumingClient() {
  4213. SSL_SESSION_free(session_);
  4214. SSL_CTX_free(ctx_);
  4215. }
  4216. // Tells whether the request was answered.
  4217. bool get() {
  4218. auto error = Error::Success;
  4219. auto sock = detail::create_client_socket(
  4220. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4221. /*connection_timeout_sec=*/5, 0,
  4222. /*read_timeout_sec=*/5, 0,
  4223. /*write_timeout_sec=*/5, 0, std::string(), error);
  4224. if (sock == INVALID_SOCKET) { return false; }
  4225. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4226. auto ssl = SSL_new(ctx_);
  4227. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4228. SSL_set_fd(ssl, static_cast<int>(sock));
  4229. if (session_) { SSL_set_session(ssl, session_); }
  4230. if (SSL_connect(ssl) != 1) { return false; }
  4231. reused_ = SSL_session_reused(ssl) == 1;
  4232. // Reading the response also takes in a TLS 1.3 session ticket.
  4233. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4234. "Connection: close\r\n\r\n";
  4235. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4236. std::string res;
  4237. char buf[256];
  4238. int n;
  4239. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4240. res.append(buf, static_cast<size_t>(n));
  4241. }
  4242. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4243. SSL_shutdown(ssl);
  4244. return res.find("200 OK") != std::string::npos;
  4245. }
  4246. // Whether the last connection resumed a session
  4247. bool reused() const { return reused_; }
  4248. private:
  4249. SSL_CTX *ctx_;
  4250. SSL_SESSION *session_ = nullptr;
  4251. bool reused_ = false;
  4252. };
  4253. // A client that resumes its session gets through, but not once the client CA
  4254. // has changed, as a resumed session does not show the certificate again.
  4255. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4256. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4257. ASSERT_TRUE(svr.is_valid());
  4258. svr.Get("/test", [](const Request &, Response &res) {
  4259. res.set_content("ok", "text/plain");
  4260. });
  4261. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4262. auto se = detail::scope_exit([&] {
  4263. svr.stop();
  4264. t.join();
  4265. ASSERT_FALSE(svr.is_running());
  4266. });
  4267. svr.wait_until_ready();
  4268. ResumingClient cli;
  4269. ASSERT_TRUE(cli.get());
  4270. ASSERT_TRUE(cli.get());
  4271. EXPECT_TRUE(cli.reused());
  4272. ASSERT_TRUE(replace_client_ca(svr));
  4273. EXPECT_FALSE(cli.get());
  4274. }
  4275. // A resumed session does not show the certificate again, so the server does
  4276. // not resume one with a verify callback to run on it.
  4277. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4278. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4279. ASSERT_TRUE(svr.is_valid());
  4280. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4281. return v.preverify_ok;
  4282. });
  4283. svr.Get("/test", [](const Request &, Response &res) {
  4284. res.set_content("ok", "text/plain");
  4285. });
  4286. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4287. auto se = detail::scope_exit([&] {
  4288. svr.stop();
  4289. t.join();
  4290. ASSERT_FALSE(svr.is_running());
  4291. });
  4292. svr.wait_until_ready();
  4293. ResumingClient cli;
  4294. ASSERT_TRUE(cli.get());
  4295. ASSERT_TRUE(cli.get());
  4296. EXPECT_FALSE(cli.reused());
  4297. }
  4298. #endif
  4299. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4300. // wolfSSL shares its session cache between contexts, so a resumed session
  4301. // could carry a client certificate checked against another server's CA, or
  4302. // against a client CA since replaced.
  4303. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4304. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4305. ASSERT_TRUE(svr.is_valid());
  4306. // Trusts a CA that did not sign the client's certificate.
  4307. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4308. ASSERT_TRUE(other.is_valid());
  4309. for (auto s : {&svr, &other}) {
  4310. s->Get("/test", [](const Request &, Response &res) {
  4311. res.set_content("ok", "text/plain");
  4312. });
  4313. }
  4314. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4315. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4316. auto se = detail::scope_exit([&] {
  4317. other.stop();
  4318. svr.stop();
  4319. t2.join();
  4320. t.join();
  4321. });
  4322. svr.wait_until_ready();
  4323. other.wait_until_ready();
  4324. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4325. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4326. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4327. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4328. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4329. ASSERT_EQ(WOLFSSL_SUCCESS,
  4330. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4331. WOLFSSL_FILETYPE_PEM));
  4332. WOLFSSL_SESSION *session = nullptr;
  4333. auto session_se = detail::scope_exit([&] {
  4334. if (session) { wolfSSL_SESSION_free(session); }
  4335. });
  4336. // A request over a new connection, resuming `session` when there is one and
  4337. // keeping the connection's own in its place. Tells whether it was answered.
  4338. auto get = [&](int port) {
  4339. auto error = Error::Success;
  4340. auto sock = detail::create_client_socket(
  4341. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4342. /*connection_timeout_sec=*/5, 0,
  4343. /*read_timeout_sec=*/5, 0,
  4344. /*write_timeout_sec=*/5, 0, std::string(), error);
  4345. if (sock == INVALID_SOCKET) { return false; }
  4346. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4347. auto ssl = wolfSSL_new(ctx);
  4348. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4349. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4350. if (session) { wolfSSL_set_session(ssl, session); }
  4351. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4352. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4353. "Connection: close\r\n\r\n";
  4354. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4355. std::string res;
  4356. char buf[256];
  4357. int n;
  4358. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4359. res.append(buf, static_cast<size_t>(n));
  4360. }
  4361. wolfSSL_shutdown(ssl);
  4362. if (session) { wolfSSL_SESSION_free(session); }
  4363. session = wolfSSL_get1_session(ssl);
  4364. return res.find("200 OK") != std::string::npos;
  4365. };
  4366. ASSERT_TRUE(get(PORT));
  4367. EXPECT_FALSE(get(PORT + 1));
  4368. ASSERT_TRUE(get(PORT));
  4369. ASSERT_TRUE(replace_client_ca(svr));
  4370. EXPECT_FALSE(get(PORT));
  4371. }
  4372. #endif
  4373. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4374. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4375. ASSERT_TRUE(svr.is_valid());
  4376. svr.Get("/test", [](const Request &, Response &res) {
  4377. res.set_content("ok", "text/plain");
  4378. });
  4379. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4380. auto se = detail::scope_exit([&] {
  4381. svr.stop();
  4382. t.join();
  4383. ASSERT_FALSE(svr.is_running());
  4384. });
  4385. svr.wait_until_ready();
  4386. // A connection that sends no ClientHello keeps its handshake in progress,
  4387. // once the server has had a moment to start it.
  4388. auto error = Error::Success;
  4389. auto sock = detail::create_client_socket(
  4390. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4391. /*connection_timeout_sec=*/5, 0,
  4392. /*read_timeout_sec=*/5, 0,
  4393. /*write_timeout_sec=*/5, 0, std::string(), error);
  4394. ASSERT_NE(INVALID_SOCKET, sock);
  4395. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4396. std::string cert_pem, key_pem;
  4397. read_file(SERVER_CERT_FILE, cert_pem);
  4398. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4399. auto update = std::async(std::launch::async, [&]() {
  4400. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4401. });
  4402. EXPECT_EQ(std::future_status::timeout,
  4403. update.wait_for(std::chrono::milliseconds(200)));
  4404. detail::close_socket(sock);
  4405. EXPECT_TRUE(update.get());
  4406. SSLClient cli(HOST, PORT);
  4407. cli.enable_server_certificate_verification(false);
  4408. auto res = cli.Get("/test");
  4409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4410. EXPECT_EQ(StatusCode::OK_200, res->status);
  4411. }
  4412. #endif
  4413. TEST(ErrorHandlerTest, ContentLength) {
  4414. Server svr;
  4415. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4416. res.status = StatusCode::OK_200;
  4417. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4418. "text/html"); // <= Content-Length still 13
  4419. });
  4420. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4421. res.set_content("Hello World!\n", "text/plain");
  4422. res.status = 524;
  4423. });
  4424. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4425. auto se = detail::scope_exit([&] {
  4426. svr.stop();
  4427. thread.join();
  4428. ASSERT_FALSE(svr.is_running());
  4429. });
  4430. svr.wait_until_ready();
  4431. {
  4432. Client cli(HOST, PORT);
  4433. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4435. EXPECT_EQ(StatusCode::OK_200, res->status);
  4436. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4437. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4438. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4439. }
  4440. }
  4441. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4442. TEST(ExceptionTest, WithoutExceptionHandler) {
  4443. Server svr;
  4444. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4445. throw std::runtime_error("exception...");
  4446. });
  4447. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4448. throw std::runtime_error("exception\r\n...");
  4449. });
  4450. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4451. auto se = detail::scope_exit([&] {
  4452. svr.stop();
  4453. listen_thread.join();
  4454. ASSERT_FALSE(svr.is_running());
  4455. });
  4456. svr.wait_until_ready();
  4457. Client cli("localhost", PORT);
  4458. {
  4459. auto res = cli.Get("/exception");
  4460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4461. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4462. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4463. }
  4464. {
  4465. auto res = cli.Get("/unknown");
  4466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4467. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4468. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4469. }
  4470. }
  4471. TEST(ExceptionTest, WithExceptionHandler) {
  4472. Server svr;
  4473. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4474. std::exception_ptr ep) {
  4475. EXPECT_FALSE(ep == nullptr);
  4476. try {
  4477. std::rethrow_exception(ep);
  4478. } catch (std::exception &e) {
  4479. EXPECT_EQ("abc", std::string(e.what()));
  4480. } catch (...) {}
  4481. res.status = StatusCode::InternalServerError_500;
  4482. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4483. "text/html"); // <= Content-Length still 13 at this point
  4484. });
  4485. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4486. res.set_content("Hello World!\n", "text/plain");
  4487. throw std::runtime_error("abc");
  4488. });
  4489. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4490. auto se = detail::scope_exit([&] {
  4491. svr.stop();
  4492. thread.join();
  4493. ASSERT_FALSE(svr.is_running());
  4494. });
  4495. svr.wait_until_ready();
  4496. for (size_t i = 0; i < 10; i++) {
  4497. Client cli(HOST, PORT);
  4498. for (size_t j = 0; j < 100; j++) {
  4499. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4501. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4502. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4503. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4504. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4505. }
  4506. cli.set_keep_alive(true);
  4507. for (size_t j = 0; j < 100; j++) {
  4508. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4510. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4511. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4512. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4513. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4514. }
  4515. }
  4516. }
  4517. TEST(ExceptionTest, AndErrorHandler) {
  4518. Server svr;
  4519. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4520. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4521. });
  4522. svr.set_exception_handler(
  4523. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4524. EXPECT_FALSE(ep == nullptr);
  4525. try {
  4526. std::rethrow_exception(ep);
  4527. } catch (std::exception &e) {
  4528. res.set_content(e.what(), "text/html");
  4529. } catch (...) {}
  4530. res.status = StatusCode::InternalServerError_500;
  4531. });
  4532. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4533. throw std::runtime_error("EXCEPTION");
  4534. });
  4535. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4536. res.set_content("ERROR", "text/html");
  4537. res.status = StatusCode::InternalServerError_500;
  4538. });
  4539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4540. auto se = detail::scope_exit([&] {
  4541. svr.stop();
  4542. thread.join();
  4543. ASSERT_FALSE(svr.is_running());
  4544. });
  4545. svr.wait_until_ready();
  4546. Client cli(HOST, PORT);
  4547. {
  4548. auto res = cli.Get("/exception");
  4549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4550. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4551. EXPECT_EQ("EXCEPTION", res->body);
  4552. }
  4553. {
  4554. auto res = cli.Get("/error");
  4555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4556. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4557. EXPECT_EQ("ERROR", res->body);
  4558. }
  4559. {
  4560. auto res = cli.Get("/invalid");
  4561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4562. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4563. EXPECT_EQ("NOT_FOUND", res->body);
  4564. }
  4565. }
  4566. #endif
  4567. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4568. // process_request() wraps only routing() in a try/catch, so an exception from
  4569. // any other user callback used to unwind into the task queue - which does not
  4570. // catch - and terminate the process. Each test below runs the server on a
  4571. // single worker thread: a guard that catches the exception but still loses the
  4572. // thread would otherwise be hidden by a spare worker serving the follow-up
  4573. // request. Note that a regression here aborts the whole test binary rather
  4574. // than failing one test.
  4575. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4576. Server svr;
  4577. svr.new_task_queue = [] { return new ThreadPool(1); };
  4578. std::atomic<int> reported{0};
  4579. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4580. if (err == Error::UserCallbackException) { reported++; }
  4581. });
  4582. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4583. res.set_content_provider(
  4584. 1024, "text/plain",
  4585. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4586. sink.write("hello", 5);
  4587. throw std::runtime_error("from the content provider");
  4588. });
  4589. });
  4590. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4591. res.set_content("ok", "text/plain");
  4592. });
  4593. auto port = svr.bind_to_any_port(HOST);
  4594. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4595. auto se = detail::scope_exit([&] {
  4596. svr.stop();
  4597. listen_thread.join();
  4598. ASSERT_FALSE(svr.is_running());
  4599. });
  4600. svr.wait_until_ready();
  4601. {
  4602. Client cli(HOST, port);
  4603. cli.set_read_timeout(5, 0);
  4604. EXPECT_FALSE(cli.Get("/throw"));
  4605. }
  4606. EXPECT_TRUE(svr.is_running());
  4607. EXPECT_EQ(1, reported.load());
  4608. // A request on a fresh connection is still served.
  4609. {
  4610. Client cli(HOST, port);
  4611. auto res = cli.Get("/ok");
  4612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. EXPECT_EQ("ok", res->body);
  4615. }
  4616. }
  4617. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4618. Server svr;
  4619. svr.new_task_queue = [] { return new ThreadPool(1); };
  4620. std::atomic<bool> should_throw{true};
  4621. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4622. res.set_content("hi", "text/plain");
  4623. });
  4624. svr.set_post_routing_handler(
  4625. [&](const Request & /*req*/, Response & /*res*/) {
  4626. if (should_throw) {
  4627. throw std::runtime_error("from the post-routing handler");
  4628. }
  4629. });
  4630. auto port = svr.bind_to_any_port(HOST);
  4631. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4632. auto se = detail::scope_exit([&] {
  4633. svr.stop();
  4634. listen_thread.join();
  4635. ASSERT_FALSE(svr.is_running());
  4636. });
  4637. svr.wait_until_ready();
  4638. {
  4639. Client cli(HOST, port);
  4640. cli.set_read_timeout(5, 0);
  4641. EXPECT_FALSE(cli.Get("/hi"));
  4642. }
  4643. EXPECT_TRUE(svr.is_running());
  4644. should_throw = false;
  4645. {
  4646. Client cli(HOST, port);
  4647. auto res = cli.Get("/hi");
  4648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4649. EXPECT_EQ(StatusCode::OK_200, res->status);
  4650. EXPECT_EQ("hi", res->body);
  4651. }
  4652. }
  4653. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4654. // The guard reports the caught exception through the error logger, which is
  4655. // a user callback too. A logger that throws has to be contained as well, or
  4656. // the process would terminate from inside the catch.
  4657. Server svr;
  4658. svr.new_task_queue = [] { return new ThreadPool(1); };
  4659. std::atomic<int> reported{0};
  4660. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4661. if (err == Error::UserCallbackException) {
  4662. reported++;
  4663. throw std::runtime_error("from the error logger");
  4664. }
  4665. });
  4666. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4667. res.set_content_provider(
  4668. 1024, "text/plain",
  4669. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4670. sink.write("hello", 5);
  4671. throw std::runtime_error("from the content provider");
  4672. });
  4673. });
  4674. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4675. res.set_content("ok", "text/plain");
  4676. });
  4677. auto port = svr.bind_to_any_port(HOST);
  4678. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4679. auto se = detail::scope_exit([&] {
  4680. svr.stop();
  4681. listen_thread.join();
  4682. ASSERT_FALSE(svr.is_running());
  4683. });
  4684. svr.wait_until_ready();
  4685. {
  4686. Client cli(HOST, port);
  4687. cli.set_read_timeout(5, 0);
  4688. EXPECT_FALSE(cli.Get("/throw"));
  4689. }
  4690. EXPECT_TRUE(svr.is_running());
  4691. EXPECT_EQ(1, reported.load());
  4692. {
  4693. Client cli(HOST, port);
  4694. auto res = cli.Get("/ok");
  4695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4696. EXPECT_EQ(StatusCode::OK_200, res->status);
  4697. EXPECT_EQ("ok", res->body);
  4698. }
  4699. }
  4700. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4701. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4702. // so the exception unwinds through the ws::WebSocket object on its way to
  4703. // the guard. None of the HTTP cases above cross that.
  4704. Server svr;
  4705. svr.new_task_queue = [] { return new ThreadPool(1); };
  4706. std::atomic<int> reported{0};
  4707. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4708. if (err == Error::UserCallbackException) { reported++; }
  4709. });
  4710. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4711. throw std::runtime_error("from the WebSocket handler");
  4712. });
  4713. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4714. res.set_content("ok", "text/plain");
  4715. });
  4716. auto port = svr.bind_to_any_port(HOST);
  4717. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4718. auto se = detail::scope_exit([&] {
  4719. svr.stop();
  4720. listen_thread.join();
  4721. ASSERT_FALSE(svr.is_running());
  4722. });
  4723. svr.wait_until_ready();
  4724. {
  4725. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4726. "/ws");
  4727. auto res = client.connect();
  4728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4729. // The server dropped the connection instead of dying.
  4730. std::string msg;
  4731. EXPECT_FALSE(client.read(msg));
  4732. client.close();
  4733. }
  4734. EXPECT_TRUE(svr.is_running());
  4735. EXPECT_EQ(1, reported.load());
  4736. {
  4737. Client cli(HOST, port);
  4738. auto res = cli.Get("/ok");
  4739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4740. EXPECT_EQ(StatusCode::OK_200, res->status);
  4741. EXPECT_EQ("ok", res->body);
  4742. }
  4743. }
  4744. #ifdef CPPHTTPLIB_SSL_ENABLED
  4745. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4746. // SSLServer::process_and_close_socket() is a separate overload with its own
  4747. // guard, so it is exercised on its own.
  4748. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4749. ASSERT_TRUE(svr.is_valid());
  4750. svr.new_task_queue = [] { return new ThreadPool(1); };
  4751. std::atomic<int> reported{0};
  4752. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4753. if (err == Error::UserCallbackException) { reported++; }
  4754. });
  4755. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4756. res.set_content_provider(
  4757. 1024, "text/plain",
  4758. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4759. sink.write("hello", 5);
  4760. throw std::runtime_error("from the content provider");
  4761. });
  4762. });
  4763. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4764. res.set_content("ok", "text/plain");
  4765. });
  4766. auto port = svr.bind_to_any_port(HOST);
  4767. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4768. auto se = detail::scope_exit([&] {
  4769. svr.stop();
  4770. listen_thread.join();
  4771. ASSERT_FALSE(svr.is_running());
  4772. });
  4773. svr.wait_until_ready();
  4774. {
  4775. SSLClient cli(HOST, port);
  4776. cli.enable_server_certificate_verification(false);
  4777. cli.set_read_timeout(5, 0);
  4778. EXPECT_FALSE(cli.Get("/throw"));
  4779. }
  4780. EXPECT_TRUE(svr.is_running());
  4781. EXPECT_EQ(1, reported.load());
  4782. {
  4783. SSLClient cli(HOST, port);
  4784. cli.enable_server_certificate_verification(false);
  4785. auto res = cli.Get("/ok");
  4786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4787. EXPECT_EQ(StatusCode::OK_200, res->status);
  4788. EXPECT_EQ("ok", res->body);
  4789. }
  4790. }
  4791. #endif
  4792. #endif
  4793. TEST(NoContentTest, ContentLength) {
  4794. Server svr;
  4795. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4796. res.status = StatusCode::NoContent_204;
  4797. });
  4798. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4799. auto se = detail::scope_exit([&] {
  4800. svr.stop();
  4801. thread.join();
  4802. ASSERT_FALSE(svr.is_running());
  4803. });
  4804. svr.wait_until_ready();
  4805. {
  4806. Client cli(HOST, PORT);
  4807. auto res = cli.Get("/hi");
  4808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4809. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4810. // RFC 9110 8.6: none in a 204 response
  4811. EXPECT_FALSE(res->has_header("Content-Length"));
  4812. }
  4813. }
  4814. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4815. Server svr;
  4816. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4817. res.set_header("Content-Length", "5");
  4818. res.set_content("hello world", "text/plain");
  4819. });
  4820. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4821. // A body that reads as the last chunk, were it taken as chunked
  4822. res.set_header("Transfer-Encoding", "chunked");
  4823. res.set_content("0\r\n\r\n", "text/plain");
  4824. });
  4825. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4826. res.set_header("Content-Length", "2");
  4827. res.set_content_provider(5, "text/plain",
  4828. [](size_t offset, size_t length, DataSink &sink) {
  4829. sink.write(&"hello"[offset], length);
  4830. return true;
  4831. });
  4832. });
  4833. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4834. res.set_header("Content-Length", "1234");
  4835. });
  4836. thread t = thread([&] { svr.listen(HOST, PORT); });
  4837. auto se = detail::scope_exit([&] {
  4838. svr.stop();
  4839. t.join();
  4840. ASSERT_FALSE(svr.is_running());
  4841. });
  4842. svr.wait_until_ready();
  4843. Client cli(HOST, PORT);
  4844. cli.set_read_timeout(1, 0);
  4845. auto expect_body = [&](const Result &res, const std::string &body) {
  4846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4847. EXPECT_EQ(body, res->body);
  4848. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4849. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4850. };
  4851. Headers identity{{"Accept-Encoding", ""}};
  4852. expect_body(cli.Get("/body", identity), "hello world");
  4853. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4854. expect_body(cli.Get("/body",
  4855. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4856. "he");
  4857. expect_body(cli.Get("/provider", identity), "hello");
  4858. expect_body(cli.Get("/empty", identity), "");
  4859. // A HEAD response may give the length of the body a GET would get.
  4860. auto res = cli.Head("/empty");
  4861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4862. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4863. }
  4864. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4865. Server svr;
  4866. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4867. res.set_content("short", "text/plain");
  4868. });
  4869. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4870. res.body += " with a footer";
  4871. res.set_header("Transfer-Encoding", "chunked");
  4872. });
  4873. thread t = thread([&] { svr.listen(HOST, PORT); });
  4874. auto se = detail::scope_exit([&] {
  4875. svr.stop();
  4876. t.join();
  4877. ASSERT_FALSE(svr.is_running());
  4878. });
  4879. svr.wait_until_ready();
  4880. Client cli(HOST, PORT);
  4881. cli.set_read_timeout(1, 0);
  4882. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4884. EXPECT_EQ("short with a footer", res->body);
  4885. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4886. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4887. }
  4888. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4889. Server svr;
  4890. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4891. res.set_header("Content-Length", "3");
  4892. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4893. sink.write("abc", 3);
  4894. sink.done();
  4895. return true;
  4896. });
  4897. });
  4898. thread t = thread([&] { svr.listen(HOST, PORT); });
  4899. auto se = detail::scope_exit([&] {
  4900. svr.stop();
  4901. t.join();
  4902. ASSERT_FALSE(svr.is_running());
  4903. });
  4904. svr.wait_until_ready();
  4905. Client cli(HOST, PORT);
  4906. cli.set_keep_alive(true);
  4907. auto res = cli.Get("/");
  4908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4909. EXPECT_EQ("abc", res->body);
  4910. EXPECT_FALSE(res->has_header("Content-Length"));
  4911. EXPECT_EQ("close", res->get_header_value("Connection"));
  4912. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4913. // No body to delimit
  4914. auto head = cli.Head("/");
  4915. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4916. EXPECT_FALSE(head->has_header("Connection"));
  4917. }
  4918. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4919. #ifdef CPPHTTPLIB_SSL_ENABLED
  4920. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4921. ASSERT_TRUE(svr.is_valid());
  4922. #else
  4923. Server svr;
  4924. #endif
  4925. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4926. if (req.path == "/routing_handler") {
  4927. res.set_header("PRE_ROUTING", "on");
  4928. res.set_content("Routing Handler", "text/plain");
  4929. return httplib::Server::HandlerResponse::Handled;
  4930. }
  4931. return httplib::Server::HandlerResponse::Unhandled;
  4932. });
  4933. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4934. res.set_content("Error", "text/html");
  4935. });
  4936. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4937. if (req.path == "/routing_handler") {
  4938. res.set_header("POST_ROUTING", "on");
  4939. }
  4940. });
  4941. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4942. res.set_content("Hello World!\n", "text/plain");
  4943. });
  4944. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4945. auto se = detail::scope_exit([&] {
  4946. svr.stop();
  4947. thread.join();
  4948. ASSERT_FALSE(svr.is_running());
  4949. });
  4950. svr.wait_until_ready();
  4951. {
  4952. #ifdef CPPHTTPLIB_SSL_ENABLED
  4953. SSLClient cli(HOST, PORT);
  4954. cli.enable_server_certificate_verification(false);
  4955. #else
  4956. Client cli(HOST, PORT);
  4957. #endif
  4958. auto res = cli.Get("/routing_handler");
  4959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4960. EXPECT_EQ(StatusCode::OK_200, res->status);
  4961. EXPECT_EQ("Routing Handler", res->body);
  4962. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4963. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4964. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4965. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4966. }
  4967. {
  4968. #ifdef CPPHTTPLIB_SSL_ENABLED
  4969. SSLClient cli(HOST, PORT);
  4970. cli.enable_server_certificate_verification(false);
  4971. #else
  4972. Client cli(HOST, PORT);
  4973. #endif
  4974. auto res = cli.Get("/hi");
  4975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4976. EXPECT_EQ(StatusCode::OK_200, res->status);
  4977. EXPECT_EQ("Hello World!\n", res->body);
  4978. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4979. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4980. }
  4981. {
  4982. #ifdef CPPHTTPLIB_SSL_ENABLED
  4983. SSLClient cli(HOST, PORT);
  4984. cli.enable_server_certificate_verification(false);
  4985. #else
  4986. Client cli(HOST, PORT);
  4987. #endif
  4988. auto res = cli.Get("/aaa");
  4989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4990. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4991. EXPECT_EQ("Error", res->body);
  4992. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4993. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4994. }
  4995. }
  4996. TEST(RequestHandlerTest, PreRequestHandler) {
  4997. auto route_path = "/user/:user";
  4998. Server svr;
  4999. svr.Get("/hi", [](const Request &, Response &res) {
  5000. res.set_content("hi", "text/plain");
  5001. });
  5002. svr.Get(route_path, [](const Request &req, Response &res) {
  5003. res.set_content(req.path_params.at("user"), "text/plain");
  5004. });
  5005. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5006. if (req.matched_route == route_path) {
  5007. auto user = req.path_params.at("user");
  5008. if (user != "john") {
  5009. res.status = StatusCode::Forbidden_403;
  5010. res.set_content("error", "text/html");
  5011. return Server::HandlerResponse::Handled;
  5012. }
  5013. }
  5014. return Server::HandlerResponse::Unhandled;
  5015. });
  5016. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5017. auto se = detail::scope_exit([&] {
  5018. svr.stop();
  5019. thread.join();
  5020. ASSERT_FALSE(svr.is_running());
  5021. });
  5022. svr.wait_until_ready();
  5023. Client cli(HOST, PORT);
  5024. {
  5025. auto res = cli.Get("/hi");
  5026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5027. EXPECT_EQ(StatusCode::OK_200, res->status);
  5028. EXPECT_EQ("hi", res->body);
  5029. }
  5030. {
  5031. auto res = cli.Get("/user/john");
  5032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5033. EXPECT_EQ(StatusCode::OK_200, res->status);
  5034. EXPECT_EQ("john", res->body);
  5035. }
  5036. {
  5037. auto res = cli.Get("/user/invalid-user");
  5038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5039. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5040. EXPECT_EQ("error", res->body);
  5041. }
  5042. }
  5043. // The pre-request handler must run before the request body is read, so a
  5044. // rejected request never forces the server to buffer a (potentially large)
  5045. // body. Here the posted body is larger than the payload limit: if the body
  5046. // were read first the server would answer 413, but because the pre-request
  5047. // handler runs first it answers 403 and the body is never read.
  5048. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5049. Server svr;
  5050. svr.set_payload_max_length(8);
  5051. auto handler_ran = false;
  5052. svr.Post("/reject", [&](const Request &req, Response &res) {
  5053. handler_ran = true;
  5054. res.set_content(req.body, "text/plain");
  5055. });
  5056. svr.Post("/accept", [](const Request &req, Response &res) {
  5057. res.set_content(req.body, "text/plain");
  5058. });
  5059. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5060. if (req.matched_route == "/reject") {
  5061. res.status = StatusCode::Forbidden_403;
  5062. res.set_content("denied", "text/plain");
  5063. return Server::HandlerResponse::Handled;
  5064. }
  5065. return Server::HandlerResponse::Unhandled;
  5066. });
  5067. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5068. auto se = detail::scope_exit([&] {
  5069. svr.stop();
  5070. thread.join();
  5071. ASSERT_FALSE(svr.is_running());
  5072. });
  5073. svr.wait_until_ready();
  5074. Client cli(HOST, PORT);
  5075. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5076. // rejects with 403 before the body is read, so 413 is never reached.
  5077. {
  5078. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5080. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5081. EXPECT_EQ("denied", res->body);
  5082. EXPECT_FALSE(handler_ran);
  5083. }
  5084. // An approved route still reads the body and enforces the payload limit.
  5085. {
  5086. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5088. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5089. }
  5090. }
  5091. TEST(UserDataTest, BasicOperations) {
  5092. httplib::UserData ud;
  5093. // Initially empty
  5094. EXPECT_FALSE(ud.has("key"));
  5095. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5096. // set and get
  5097. ud.set("key", 42);
  5098. EXPECT_TRUE(ud.has("key"));
  5099. auto *p = ud.get<int>("key");
  5100. ASSERT_NE(nullptr, p);
  5101. EXPECT_EQ(42, *p);
  5102. // Type mismatch → nullptr
  5103. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5104. // Overwrite with different type
  5105. ud.set("key", std::string("hello"));
  5106. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5107. auto *s = ud.get<std::string>("key");
  5108. ASSERT_NE(nullptr, s);
  5109. EXPECT_EQ("hello", *s);
  5110. // erase
  5111. ud.erase("key");
  5112. EXPECT_FALSE(ud.has("key"));
  5113. // clear
  5114. ud.set("a", 1);
  5115. ud.set("b", 2);
  5116. ud.clear();
  5117. EXPECT_FALSE(ud.has("a"));
  5118. EXPECT_FALSE(ud.has("b"));
  5119. }
  5120. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5121. struct AuthCtx {
  5122. std::string user_id;
  5123. };
  5124. Server svr;
  5125. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5126. res.user_data.set("auth", AuthCtx{"alice"});
  5127. return Server::HandlerResponse::Unhandled;
  5128. });
  5129. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5130. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5131. ASSERT_NE(nullptr, ctx);
  5132. res.set_content("Hello " + ctx->user_id, "text/plain");
  5133. });
  5134. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5135. auto se = detail::scope_exit([&] {
  5136. svr.stop();
  5137. thread.join();
  5138. ASSERT_FALSE(svr.is_running());
  5139. });
  5140. svr.wait_until_ready();
  5141. Client cli(HOST, PORT);
  5142. auto res = cli.Get("/me");
  5143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5144. EXPECT_EQ(StatusCode::OK_200, res->status);
  5145. EXPECT_EQ("Hello alice", res->body);
  5146. }
  5147. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5148. struct RoleCtx {
  5149. std::string role;
  5150. };
  5151. Server svr;
  5152. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5153. res.user_data.set("role", RoleCtx{"admin"});
  5154. return Server::HandlerResponse::Unhandled;
  5155. });
  5156. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5157. auto *ctx = res.user_data.get<RoleCtx>("role");
  5158. ASSERT_NE(nullptr, ctx);
  5159. res.set_content(ctx->role, "text/plain");
  5160. });
  5161. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5162. auto se = detail::scope_exit([&] {
  5163. svr.stop();
  5164. thread.join();
  5165. ASSERT_FALSE(svr.is_running());
  5166. });
  5167. svr.wait_until_ready();
  5168. Client cli(HOST, PORT);
  5169. auto res = cli.Get("/role");
  5170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5171. EXPECT_EQ(StatusCode::OK_200, res->status);
  5172. EXPECT_EQ("admin", res->body);
  5173. }
  5174. TEST(InvalidFormatTest, StatusCode) {
  5175. Server svr;
  5176. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5177. res.set_content("Hello World!\n", "text/plain");
  5178. res.status = 9999; // Status should be a three-digit code...
  5179. });
  5180. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5181. auto se = detail::scope_exit([&] {
  5182. svr.stop();
  5183. thread.join();
  5184. ASSERT_FALSE(svr.is_running());
  5185. });
  5186. svr.wait_until_ready();
  5187. {
  5188. Client cli(HOST, PORT);
  5189. auto res = cli.Get("/hi");
  5190. ASSERT_FALSE(res);
  5191. }
  5192. }
  5193. TEST(URLFragmentTest, WithFragment) {
  5194. Server svr;
  5195. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5196. EXPECT_TRUE(req.target == "/hi");
  5197. });
  5198. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5199. auto se = detail::scope_exit([&] {
  5200. svr.stop();
  5201. thread.join();
  5202. ASSERT_FALSE(svr.is_running());
  5203. });
  5204. svr.wait_until_ready();
  5205. {
  5206. Client cli(HOST, PORT);
  5207. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5208. EXPECT_TRUE(res);
  5209. EXPECT_EQ(StatusCode::OK_200, res->status);
  5210. res = cli.Get("/hi%23key1=val1=key2=val2");
  5211. EXPECT_TRUE(res);
  5212. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5213. }
  5214. }
  5215. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5216. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5217. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5218. Server svr;
  5219. std::vector<std::string> targets;
  5220. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5221. targets.push_back(req.target);
  5222. });
  5223. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5224. auto se = detail::scope_exit([&] {
  5225. svr.stop();
  5226. thread.join();
  5227. ASSERT_FALSE(svr.is_running());
  5228. });
  5229. svr.wait_until_ready();
  5230. Client cli(HOST, PORT);
  5231. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5232. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5233. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5234. // A '?' after the '#' belongs to the fragment, not to the query.
  5235. Request req;
  5236. req.method = "GET";
  5237. req.path = "/hi#f?x=1";
  5238. req.params.emplace("a", "1");
  5239. Response res;
  5240. auto error = Error::Success;
  5241. EXPECT_TRUE(cli.send(req, res, error));
  5242. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5243. "/hi?a=1"}),
  5244. targets);
  5245. }
  5246. TEST(HeaderWriter, SetHeaderWriter) {
  5247. Server svr;
  5248. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5249. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5250. return detail::write_headers(strm, hdrs);
  5251. });
  5252. svr.Get("/hi", [](const Request &req, Response &res) {
  5253. auto it = req.headers.find("CustomClientHeader");
  5254. EXPECT_TRUE(it != req.headers.end());
  5255. EXPECT_EQ(it->second, "CustomClientValue");
  5256. res.set_content("Hello World!\n", "text/plain");
  5257. });
  5258. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5259. auto se = detail::scope_exit([&] {
  5260. svr.stop();
  5261. thread.join();
  5262. ASSERT_FALSE(svr.is_running());
  5263. });
  5264. svr.wait_until_ready();
  5265. {
  5266. Client cli(HOST, PORT);
  5267. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5268. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5269. return detail::write_headers(strm, hdrs);
  5270. });
  5271. auto res = cli.Get("/hi");
  5272. EXPECT_TRUE(res);
  5273. EXPECT_EQ(StatusCode::OK_200, res->status);
  5274. auto it = res->headers.find("CustomServerHeader");
  5275. EXPECT_TRUE(it != res->headers.end());
  5276. EXPECT_EQ(it->second, "CustomServerValue");
  5277. }
  5278. }
  5279. class ServerTest : public ::testing::Test {
  5280. protected:
  5281. ServerTest()
  5282. : cli_(HOST, PORT)
  5283. #ifdef CPPHTTPLIB_SSL_ENABLED
  5284. ,
  5285. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5286. #endif
  5287. {
  5288. #ifdef CPPHTTPLIB_SSL_ENABLED
  5289. cli_.enable_server_certificate_verification(false);
  5290. #endif
  5291. // Allow LARGE_DATA (100MB) responses
  5292. cli_.set_payload_max_length(200 * 1024 * 1024);
  5293. }
  5294. virtual void SetUp() {
  5295. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5296. svr_.set_payload_max_length(200 * 1024 * 1024);
  5297. svr_.set_mount_point("/", "./www");
  5298. svr_.set_mount_point("/mount", "./www2");
  5299. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5300. svr_.Get("/hi",
  5301. [&](const Request & /*req*/, Response &res) {
  5302. res.set_content("Hello World!", "text/plain");
  5303. })
  5304. .Get("/file_content",
  5305. [&](const Request & /*req*/, Response &res) {
  5306. res.set_file_content("./www/dir/test.html");
  5307. })
  5308. .Get("/file_content_with_content_type",
  5309. [&](const Request & /*req*/, Response &res) {
  5310. res.set_file_content("./www/file", "text/plain");
  5311. })
  5312. .Get("/invalid_file_content",
  5313. [&](const Request & /*req*/, Response &res) {
  5314. res.set_file_content("./www/dir/invalid_file_path");
  5315. })
  5316. .Get("/http_response_splitting",
  5317. [&](const Request & /*req*/, Response &res) {
  5318. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5319. EXPECT_EQ(0U, res.headers.size());
  5320. EXPECT_FALSE(res.has_header("a"));
  5321. res.set_header("a", "1\nSet-Cookie: a=1");
  5322. EXPECT_EQ(0U, res.headers.size());
  5323. EXPECT_FALSE(res.has_header("a"));
  5324. res.set_header("a", "1\rSet-Cookie: a=1");
  5325. EXPECT_EQ(0U, res.headers.size());
  5326. EXPECT_FALSE(res.has_header("a"));
  5327. res.set_header("a\r\nb", "0");
  5328. EXPECT_EQ(0U, res.headers.size());
  5329. EXPECT_FALSE(res.has_header("a"));
  5330. res.set_header("a\rb", "0");
  5331. EXPECT_EQ(0U, res.headers.size());
  5332. EXPECT_FALSE(res.has_header("a"));
  5333. res.set_header("a\nb", "0");
  5334. EXPECT_EQ(0U, res.headers.size());
  5335. EXPECT_FALSE(res.has_header("a"));
  5336. res.set_redirect("1\r\nSet-Cookie: a=1");
  5337. EXPECT_EQ(0U, res.headers.size());
  5338. EXPECT_FALSE(res.has_header("Location"));
  5339. })
  5340. .Get("/slow",
  5341. [&](const Request & /*req*/, Response &res) {
  5342. std::this_thread::sleep_for(std::chrono::seconds(4));
  5343. res.set_content("slow", "text/plain");
  5344. })
  5345. #if 0
  5346. .Post("/slowpost",
  5347. [&](const Request & /*req*/, Response &res) {
  5348. std::this_thread::sleep_for(std::chrono::seconds(2));
  5349. res.set_content("slow", "text/plain");
  5350. })
  5351. #endif
  5352. .Get("/remote_addr",
  5353. [&](const Request &req, Response &res) {
  5354. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5355. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5356. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5357. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5358. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5359. #endif
  5360. res.set_content(req.remote_addr, "text/plain");
  5361. })
  5362. .Get("/local_addr",
  5363. [&](const Request &req, Response &res) {
  5364. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5365. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5366. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5367. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5368. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5369. #endif
  5370. auto local_addr = req.local_addr;
  5371. auto local_port = std::to_string(req.local_port);
  5372. res.set_content(local_addr.append(":").append(local_port),
  5373. "text/plain");
  5374. })
  5375. .Get("/endwith%",
  5376. [&](const Request & /*req*/, Response &res) {
  5377. res.set_content("Hello World!", "text/plain");
  5378. })
  5379. .Get("/a\\+\\+b",
  5380. [&](const Request &req, Response &res) {
  5381. ASSERT_TRUE(req.has_param("a +b"));
  5382. auto val = req.get_param_value("a +b");
  5383. res.set_content(val, "text/plain");
  5384. })
  5385. .Get("/", [&](const Request & /*req*/,
  5386. Response &res) { res.set_redirect("/hi"); })
  5387. .Post("/1",
  5388. [](const Request & /*req*/, Response &res) {
  5389. res.set_redirect("/2", StatusCode::SeeOther_303);
  5390. })
  5391. .Get("/2",
  5392. [](const Request & /*req*/, Response &res) {
  5393. res.set_content("redirected.", "text/plain");
  5394. res.status = StatusCode::OK_200;
  5395. })
  5396. .Post("/person",
  5397. [&](const Request &req, Response &res) {
  5398. if (req.has_param("name") && req.has_param("note")) {
  5399. persons_[req.get_param_value("name")] =
  5400. req.get_param_value("note");
  5401. } else {
  5402. res.status = StatusCode::BadRequest_400;
  5403. }
  5404. })
  5405. .Put("/person",
  5406. [&](const Request &req, Response &res) {
  5407. if (req.has_param("name") && req.has_param("note")) {
  5408. persons_[req.get_param_value("name")] =
  5409. req.get_param_value("note");
  5410. } else {
  5411. res.status = StatusCode::BadRequest_400;
  5412. }
  5413. })
  5414. .Get("/person/(.*)",
  5415. [&](const Request &req, Response &res) {
  5416. string name = req.matches[1];
  5417. if (persons_.find(name) != persons_.end()) {
  5418. auto note = persons_[name];
  5419. res.set_content(note, "text/plain");
  5420. } else {
  5421. res.status = StatusCode::NotFound_404;
  5422. }
  5423. })
  5424. .Delete("/person",
  5425. [&](const Request &req, Response &res) {
  5426. if (req.has_param("name")) {
  5427. string name = req.get_param_value("name");
  5428. if (persons_.find(name) != persons_.end()) {
  5429. persons_.erase(name);
  5430. res.set_content("DELETED", "text/plain");
  5431. } else {
  5432. res.status = StatusCode::NotFound_404;
  5433. }
  5434. } else {
  5435. res.status = StatusCode::BadRequest_400;
  5436. }
  5437. })
  5438. .Post("/x-www-form-urlencoded-json",
  5439. [&](const Request &req, Response &res) {
  5440. auto json = req.get_param_value("json");
  5441. ASSERT_EQ(JSON_DATA, json);
  5442. res.set_content(json, "appliation/json");
  5443. res.status = StatusCode::OK_200;
  5444. })
  5445. .Get("/streamed-chunked",
  5446. [&](const Request & /*req*/, Response &res) {
  5447. res.set_chunked_content_provider(
  5448. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5449. sink.os << "123";
  5450. sink.os << "456";
  5451. sink.os << "789";
  5452. sink.done();
  5453. return true;
  5454. });
  5455. })
  5456. .Get("/streamed-chunked-with-prohibited-trailer",
  5457. [&](const Request & /*req*/, Response &res) {
  5458. auto i = new int(0);
  5459. // Declare both a prohibited trailer (Content-Length) and an
  5460. // allowed one
  5461. res.set_header("Trailer", "Content-Length, X-Allowed");
  5462. res.set_chunked_content_provider(
  5463. "text/plain",
  5464. [i](size_t /*offset*/, DataSink &sink) {
  5465. switch (*i) {
  5466. case 0: sink.os << "123"; break;
  5467. case 1: sink.os << "456"; break;
  5468. case 2: sink.os << "789"; break;
  5469. case 3: {
  5470. sink.done_with_trailer(
  5471. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5472. } break;
  5473. }
  5474. (*i)++;
  5475. return true;
  5476. },
  5477. [i](bool success) {
  5478. EXPECT_TRUE(success);
  5479. delete i;
  5480. });
  5481. })
  5482. .Get("/streamed-chunked2",
  5483. [&](const Request & /*req*/, Response &res) {
  5484. auto i = new int(0);
  5485. res.set_chunked_content_provider(
  5486. "text/plain",
  5487. [i](size_t /*offset*/, DataSink &sink) {
  5488. switch (*i) {
  5489. case 0: sink.os << "123"; break;
  5490. case 1: sink.os << "456"; break;
  5491. case 2: sink.os << "789"; break;
  5492. case 3: sink.done(); break;
  5493. }
  5494. (*i)++;
  5495. return true;
  5496. },
  5497. [i](bool success) {
  5498. EXPECT_TRUE(success);
  5499. delete i;
  5500. });
  5501. })
  5502. .Get("/streamed-chunked-with-trailer",
  5503. [&](const Request & /*req*/, Response &res) {
  5504. auto i = new int(0);
  5505. res.set_header("Trailer", "Dummy1, Dummy2");
  5506. res.set_chunked_content_provider(
  5507. "text/plain",
  5508. [i](size_t /*offset*/, DataSink &sink) {
  5509. switch (*i) {
  5510. case 0: sink.os << "123"; break;
  5511. case 1: sink.os << "456"; break;
  5512. case 2: sink.os << "789"; break;
  5513. case 3: {
  5514. sink.done_with_trailer(
  5515. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5516. } break;
  5517. }
  5518. (*i)++;
  5519. return true;
  5520. },
  5521. [i](bool success) {
  5522. EXPECT_TRUE(success);
  5523. delete i;
  5524. });
  5525. })
  5526. .Get("/streamed",
  5527. [&](const Request & /*req*/, Response &res) {
  5528. res.set_content_provider(
  5529. 6, "text/plain",
  5530. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5531. sink.os << (offset < 3 ? "a" : "b");
  5532. return true;
  5533. });
  5534. })
  5535. .Get("/streamed-without-length",
  5536. [&](const Request & /*req*/, Response &res) {
  5537. auto data = new std::string("abcdefg");
  5538. res.set_content_provider(
  5539. "text/plain",
  5540. [data](size_t offset, DataSink &sink) {
  5541. if (offset < data->size()) {
  5542. sink.os << data->substr(offset);
  5543. }
  5544. sink.done();
  5545. return true;
  5546. },
  5547. [data](bool success) {
  5548. EXPECT_TRUE(success);
  5549. delete data;
  5550. });
  5551. })
  5552. .Get("/streamed-with-range",
  5553. [&](const Request &req, Response &res) {
  5554. auto data = new std::string("abcdefg");
  5555. // An explicit status keeps the server from picking the 206 it
  5556. // would otherwise choose for a ranged request, so the response
  5557. // is not a partial representation.
  5558. auto status = req.get_param_value("status");
  5559. if (status == "200") {
  5560. res.status = StatusCode::OK_200;
  5561. } else if (status == "403") {
  5562. res.status = StatusCode::Forbidden_403;
  5563. }
  5564. res.set_content_provider(
  5565. data->size(), "text/plain",
  5566. [data](size_t offset, size_t length, DataSink &sink) {
  5567. size_t DATA_CHUNK_SIZE = 4;
  5568. const auto &d = *data;
  5569. auto out_len =
  5570. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5571. auto ret =
  5572. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5573. EXPECT_TRUE(ret);
  5574. return true;
  5575. },
  5576. [data, &req](bool success) {
  5577. EXPECT_EQ(success, !req.has_param("error"));
  5578. delete data;
  5579. });
  5580. })
  5581. .Get("/streamed-cancel",
  5582. [&](const Request & /*req*/, Response &res) {
  5583. res.set_content_provider(
  5584. size_t(-1), "text/plain",
  5585. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5586. sink.os << "data_chunk";
  5587. return true;
  5588. });
  5589. })
  5590. .Get("/regex-with-delimiter",
  5591. [&](const Request &req, Response & /*res*/) {
  5592. ASSERT_TRUE(req.has_param("key"));
  5593. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5594. })
  5595. .Get("/with-range",
  5596. [&](const Request & /*req*/, Response &res) {
  5597. res.set_content("abcdefg", "text/plain");
  5598. })
  5599. .Get("/test-start-time",
  5600. [&](const Request &req, Response & /*res*/) {
  5601. EXPECT_NE(req.start_time_,
  5602. std::chrono::steady_clock::time_point::min());
  5603. })
  5604. .Get("/with-range-customized-response",
  5605. [&](const Request & /*req*/, Response &res) {
  5606. res.status = StatusCode::BadRequest_400;
  5607. res.set_content(JSON_DATA, "application/json");
  5608. })
  5609. .Post("/chunked",
  5610. [&](const Request &req, Response & /*res*/) {
  5611. EXPECT_EQ(req.body, "dechunked post body");
  5612. })
  5613. .Post("/large-chunked",
  5614. [&](const Request &req, Response & /*res*/) {
  5615. std::string expected(6 * 30 * 1024u, 'a');
  5616. EXPECT_EQ(req.body, expected);
  5617. })
  5618. .Post("/multipart",
  5619. [&](const Request &req, Response & /*res*/) {
  5620. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5621. req.form.get_field_count("text2") +
  5622. req.form.get_field_count("file3") +
  5623. req.form.get_field_count("file4"));
  5624. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5625. req.form.get_file_count("file2"));
  5626. ASSERT_TRUE(!req.form.has_file("???"));
  5627. ASSERT_TRUE(!req.form.has_field("???"));
  5628. ASSERT_TRUE(req.body.empty());
  5629. {
  5630. const auto &text = req.form.get_field("text1");
  5631. EXPECT_EQ("text default", text);
  5632. }
  5633. {
  5634. const auto &text = req.form.get_field("text2");
  5635. EXPECT_EQ("aωb", text);
  5636. }
  5637. {
  5638. const auto &file = req.form.get_file("file1");
  5639. EXPECT_EQ("hello.txt", file.filename);
  5640. EXPECT_EQ("text/plain", file.content_type);
  5641. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5642. }
  5643. {
  5644. const auto &file = req.form.get_file("file2");
  5645. EXPECT_EQ("world.json", file.filename);
  5646. EXPECT_EQ("application/json", file.content_type);
  5647. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5648. }
  5649. {
  5650. const auto &text = req.form.get_field("file3");
  5651. EXPECT_EQ(0u, text.size());
  5652. }
  5653. {
  5654. const auto &text = req.form.get_field("file4");
  5655. EXPECT_EQ(0u, text.size());
  5656. }
  5657. })
  5658. .Post("/multipart/multi_file_values",
  5659. [&](const Request &req, Response & /*res*/) {
  5660. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5661. req.form.get_field_count("multi_text1"));
  5662. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5663. ASSERT_TRUE(!req.form.has_file("???"));
  5664. ASSERT_TRUE(!req.form.has_field("???"));
  5665. ASSERT_TRUE(req.body.empty());
  5666. {
  5667. const auto &text = req.form.get_field("text");
  5668. EXPECT_EQ("default text", text);
  5669. }
  5670. {
  5671. const auto &text1_values = req.form.get_fields("multi_text1");
  5672. EXPECT_EQ(2u, text1_values.size());
  5673. EXPECT_EQ("aaaaa", text1_values[0]);
  5674. EXPECT_EQ("bbbbb", text1_values[1]);
  5675. }
  5676. {
  5677. const auto &file1_values = req.form.get_files("multi_file1");
  5678. EXPECT_EQ(2u, file1_values.size());
  5679. auto file1 = file1_values[0];
  5680. EXPECT_EQ(file1.filename, "hello.txt");
  5681. EXPECT_EQ(file1.content_type, "text/plain");
  5682. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5683. auto file2 = file1_values[1];
  5684. EXPECT_EQ(file2.filename, "world.json");
  5685. EXPECT_EQ(file2.content_type, "application/json");
  5686. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5687. }
  5688. })
  5689. .Post("/empty",
  5690. [&](const Request &req, Response &res) {
  5691. EXPECT_EQ(req.body, "");
  5692. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5693. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5694. res.set_content("empty", "text/plain");
  5695. })
  5696. .Post("/empty-no-content-type",
  5697. [&](const Request &req, Response &res) {
  5698. EXPECT_EQ(req.body, "");
  5699. EXPECT_FALSE(req.has_header("Content-Type"));
  5700. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5701. res.set_content("empty-no-content-type", "text/plain");
  5702. })
  5703. .Post("/path-only",
  5704. [&](const Request &req, Response &res) {
  5705. EXPECT_EQ(req.body, "");
  5706. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5707. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5708. res.set_content("path-only", "text/plain");
  5709. })
  5710. .Post("/path-headers-only",
  5711. [&](const Request &req, Response &res) {
  5712. EXPECT_EQ(req.body, "");
  5713. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5714. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5715. EXPECT_EQ("world", req.get_header_value("hello"));
  5716. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5717. res.set_content("path-headers-only", "text/plain");
  5718. })
  5719. .Post("/post-large",
  5720. [&](const Request &req, Response &res) {
  5721. EXPECT_EQ(req.body, LARGE_DATA);
  5722. res.set_content(req.body, "text/plain");
  5723. })
  5724. .Post("/post-loopback",
  5725. [&](const Request &, Response &res,
  5726. ContentReader const &content_reader) {
  5727. std::string body;
  5728. content_reader([&](const char *data, size_t data_length) {
  5729. body.append(data, data_length);
  5730. return true;
  5731. });
  5732. res.set_content(body, "text/plain");
  5733. })
  5734. .Put("/put-loopback",
  5735. [&](const Request &, Response &res,
  5736. ContentReader const &content_reader) {
  5737. std::string body;
  5738. content_reader([&](const char *data, size_t data_length) {
  5739. body.append(data, data_length);
  5740. return true;
  5741. });
  5742. res.set_content(body, "text/plain");
  5743. })
  5744. .Patch("/patch-loopback",
  5745. [&](const Request &, Response &res,
  5746. ContentReader const &content_reader) {
  5747. std::string body;
  5748. content_reader([&](const char *data, size_t data_length) {
  5749. body.append(data, data_length);
  5750. return true;
  5751. });
  5752. res.set_content(body, "text/plain");
  5753. })
  5754. .Put("/empty-no-content-type",
  5755. [&](const Request &req, Response &res) {
  5756. EXPECT_EQ(req.body, "");
  5757. EXPECT_FALSE(req.has_header("Content-Type"));
  5758. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5759. res.set_content("empty-no-content-type", "text/plain");
  5760. })
  5761. .Put("/put",
  5762. [&](const Request &req, Response &res) {
  5763. EXPECT_EQ(req.body, "PUT");
  5764. res.set_content(req.body, "text/plain");
  5765. })
  5766. .Put("/put-large",
  5767. [&](const Request &req, Response &res) {
  5768. EXPECT_EQ(req.body, LARGE_DATA);
  5769. res.set_content(req.body, "text/plain");
  5770. })
  5771. .Patch("/patch",
  5772. [&](const Request &req, Response &res) {
  5773. EXPECT_EQ(req.body, "PATCH");
  5774. res.set_content(req.body, "text/plain");
  5775. })
  5776. .Delete("/delete",
  5777. [&](const Request & /*req*/, Response &res) {
  5778. res.set_content("DELETE", "text/plain");
  5779. })
  5780. .Delete("/delete-body",
  5781. [&](const Request &req, Response &res) {
  5782. EXPECT_EQ(req.body, "content");
  5783. res.set_content(req.body, "text/plain");
  5784. })
  5785. .Options(R"(\*)",
  5786. [&](const Request & /*req*/, Response &res) {
  5787. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5788. })
  5789. .CustomRoute("PROPFIND", "/dav/:id",
  5790. [&](const Request &req, Response &res) {
  5791. res.set_header("x-body-size",
  5792. std::to_string(req.body.size()));
  5793. res.set_header("x-matched-route", req.matched_route);
  5794. res.set_header("x-dav-id", req.path_params.at("id"));
  5795. res.status = StatusCode::MultiStatus_207;
  5796. res.set_content(req.body, "application/xml");
  5797. })
  5798. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5799. [&](const Request &req, Response &res) {
  5800. res.set_header("x-dav-match", req.matches[1]);
  5801. res.status = StatusCode::MultiStatus_207;
  5802. })
  5803. .CustomRoute("MKCOL", "/dav-mkcol",
  5804. [&](const Request &req, Response &res) {
  5805. EXPECT_TRUE(req.body.empty());
  5806. res.status = StatusCode::Created_201;
  5807. })
  5808. .CustomRoute(
  5809. "REPORT", "/dav-report",
  5810. [&](const Request & /*req*/, Response &res,
  5811. const ContentReader &content_reader) {
  5812. std::string body;
  5813. content_reader([&](const char *data, size_t data_length) {
  5814. body.append(data, data_length);
  5815. return true;
  5816. });
  5817. res.set_header("x-body-size", std::to_string(body.size()));
  5818. res.status = StatusCode::MultiStatus_207;
  5819. res.set_content(body, "application/xml");
  5820. })
  5821. .Get("/request-target",
  5822. [&](const Request &req, Response & /*res*/) {
  5823. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5824. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5825. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5826. })
  5827. .Get("/long-query-value",
  5828. [&](const Request &req, Response & /*res*/) {
  5829. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5830. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5831. })
  5832. .Get("/too-long-query-value",
  5833. [&](const Request &req, Response & /*res*/) {
  5834. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5835. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5836. })
  5837. .Get("/array-param",
  5838. [&](const Request &req, Response & /*res*/) {
  5839. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5840. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5841. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5842. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5843. })
  5844. .Get("/array-param-values",
  5845. [&](const Request &req, Response & /*res*/) {
  5846. auto values = req.get_param_values("array");
  5847. EXPECT_EQ(3u, values.size());
  5848. EXPECT_EQ("value1", values[0]);
  5849. EXPECT_EQ("value2", values[1]);
  5850. EXPECT_EQ("value3", values[2]);
  5851. auto empty = req.get_param_values("nonexistent");
  5852. EXPECT_TRUE(empty.empty());
  5853. })
  5854. .Post("/validate-no-multiple-headers",
  5855. [&](const Request &req, Response & /*res*/) {
  5856. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5857. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5858. })
  5859. .Post("/content_receiver",
  5860. [&](const Request &req, Response &res,
  5861. const ContentReader &content_reader) {
  5862. if (req.is_multipart_form_data()) {
  5863. std::vector<FormData> items;
  5864. content_reader(
  5865. [&](const FormData &file) {
  5866. items.push_back(file);
  5867. return true;
  5868. },
  5869. [&](const char *data, size_t data_length) {
  5870. items.back().content.append(data, data_length);
  5871. return true;
  5872. });
  5873. EXPECT_EQ(5u, items.size());
  5874. {
  5875. const auto &file = get_file_value(items, "text1");
  5876. EXPECT_TRUE(file.filename.empty());
  5877. EXPECT_EQ("text default", file.content);
  5878. }
  5879. {
  5880. const auto &file = get_file_value(items, "text2");
  5881. EXPECT_TRUE(file.filename.empty());
  5882. EXPECT_EQ("aωb", file.content);
  5883. }
  5884. {
  5885. const auto &file = get_file_value(items, "file1");
  5886. EXPECT_EQ("hello.txt", file.filename);
  5887. EXPECT_EQ("text/plain", file.content_type);
  5888. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5889. }
  5890. {
  5891. const auto &file = get_file_value(items, "file2");
  5892. EXPECT_EQ("world.json", file.filename);
  5893. EXPECT_EQ("application/json", file.content_type);
  5894. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5895. }
  5896. {
  5897. const auto &file = get_file_value(items, "file3");
  5898. EXPECT_TRUE(file.filename.empty());
  5899. EXPECT_EQ("application/octet-stream", file.content_type);
  5900. EXPECT_EQ(0u, file.content.size());
  5901. }
  5902. } else {
  5903. std::string body;
  5904. content_reader([&](const char *data, size_t data_length) {
  5905. EXPECT_EQ(7U, data_length);
  5906. body.append(data, data_length);
  5907. return true;
  5908. });
  5909. EXPECT_EQ(body, "content");
  5910. res.set_content(body, "text/plain");
  5911. }
  5912. })
  5913. .Put("/content_receiver",
  5914. [&](const Request & /*req*/, Response &res,
  5915. const ContentReader &content_reader) {
  5916. std::string body;
  5917. content_reader([&](const char *data, size_t data_length) {
  5918. body.append(data, data_length);
  5919. return true;
  5920. });
  5921. EXPECT_EQ(body, "content");
  5922. res.set_content(body, "text/plain");
  5923. })
  5924. .Patch("/content_receiver",
  5925. [&](const Request & /*req*/, Response &res,
  5926. const ContentReader &content_reader) {
  5927. std::string body;
  5928. content_reader([&](const char *data, size_t data_length) {
  5929. body.append(data, data_length);
  5930. return true;
  5931. });
  5932. EXPECT_EQ(body, "content");
  5933. res.set_content(body, "text/plain");
  5934. })
  5935. .Post("/query-string-and-body",
  5936. [&](const Request &req, Response & /*res*/) {
  5937. ASSERT_TRUE(req.has_param("key"));
  5938. EXPECT_EQ(req.get_param_value("key"), "value");
  5939. EXPECT_EQ(req.body, "content");
  5940. })
  5941. .Get("/last-request",
  5942. [&](const Request &req, Response & /*res*/) {
  5943. EXPECT_EQ("close", req.get_header_value("Connection"));
  5944. })
  5945. .Get(R"(/redirect/(\d+))",
  5946. [&](const Request &req, Response &res) {
  5947. auto num = std::stoi(req.matches[1]) + 1;
  5948. std::string url = "/redirect/" + std::to_string(num);
  5949. res.set_redirect(url);
  5950. })
  5951. .Post("/binary",
  5952. [&](const Request &req, Response &res) {
  5953. EXPECT_EQ(4U, req.body.size());
  5954. EXPECT_EQ("application/octet-stream",
  5955. req.get_header_value("Content-Type"));
  5956. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5957. res.set_content(req.body, "application/octet-stream");
  5958. })
  5959. .Put("/binary",
  5960. [&](const Request &req, Response &res) {
  5961. EXPECT_EQ(4U, req.body.size());
  5962. EXPECT_EQ("application/octet-stream",
  5963. req.get_header_value("Content-Type"));
  5964. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5965. res.set_content(req.body, "application/octet-stream");
  5966. })
  5967. .Patch("/binary",
  5968. [&](const Request &req, Response &res) {
  5969. EXPECT_EQ(4U, req.body.size());
  5970. EXPECT_EQ("application/octet-stream",
  5971. req.get_header_value("Content-Type"));
  5972. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5973. res.set_content(req.body, "application/octet-stream");
  5974. })
  5975. .Delete("/binary",
  5976. [&](const Request &req, Response &res) {
  5977. EXPECT_EQ(4U, req.body.size());
  5978. EXPECT_EQ("application/octet-stream",
  5979. req.get_header_value("Content-Type"));
  5980. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5981. res.set_content(req.body, "application/octet-stream");
  5982. })
  5983. .Get("/issue1772",
  5984. [&](const Request & /*req*/, Response &res) {
  5985. res.status = 401;
  5986. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5987. })
  5988. .Delete("/issue609",
  5989. [](const httplib::Request &, httplib::Response &res,
  5990. const httplib::ContentReader &) {
  5991. res.set_content("ok", "text/plain");
  5992. })
  5993. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5994. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5995. .Get("/compress",
  5996. [&](const Request & /*req*/, Response &res) {
  5997. res.set_content(
  5998. "12345678901234567890123456789012345678901234567890123456789"
  5999. "01234567890123456789012345678901234567890",
  6000. "text/plain");
  6001. })
  6002. .Get("/compress-with-charset",
  6003. [&](const Request & /*req*/, Response &res) {
  6004. res.set_content(
  6005. "12345678901234567890123456789012345678901234567890123456789"
  6006. "01234567890123456789012345678901234567890",
  6007. "application/json; charset=utf-8");
  6008. })
  6009. .Get("/nocompress",
  6010. [&](const Request & /*req*/, Response &res) {
  6011. res.set_content(
  6012. "12345678901234567890123456789012345678901234567890123456789"
  6013. "01234567890123456789012345678901234567890",
  6014. "application/octet-stream");
  6015. })
  6016. .Post("/compress-multipart",
  6017. [&](const Request &req, Response & /*res*/) {
  6018. EXPECT_EQ(2u, req.form.fields.size());
  6019. ASSERT_TRUE(!req.form.has_field("???"));
  6020. {
  6021. const auto &text = req.form.get_field("key1");
  6022. EXPECT_EQ("test", text);
  6023. }
  6024. {
  6025. const auto &text = req.form.get_field("key2");
  6026. EXPECT_EQ("--abcdefg123", text);
  6027. }
  6028. })
  6029. #endif
  6030. ;
  6031. persons_["john"] = "programmer";
  6032. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6033. svr_.wait_until_ready();
  6034. }
  6035. virtual void TearDown() {
  6036. svr_.stop();
  6037. if (!request_threads_.empty()) {
  6038. std::this_thread::sleep_for(std::chrono::seconds(1));
  6039. for (auto &t : request_threads_) {
  6040. t.join();
  6041. }
  6042. }
  6043. t_.join();
  6044. }
  6045. map<string, string> persons_;
  6046. #ifdef CPPHTTPLIB_SSL_ENABLED
  6047. SSLClient cli_;
  6048. SSLServer svr_;
  6049. #else
  6050. Client cli_;
  6051. Server svr_;
  6052. #endif
  6053. thread t_;
  6054. std::vector<thread> request_threads_;
  6055. };
  6056. TEST_F(ServerTest, GetMethod200) {
  6057. auto res = cli_.Get("/hi");
  6058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6059. EXPECT_EQ("HTTP/1.1", res->version);
  6060. EXPECT_EQ(StatusCode::OK_200, res->status);
  6061. EXPECT_EQ("OK", res->reason);
  6062. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6063. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6064. EXPECT_EQ("Hello World!", res->body);
  6065. }
  6066. TEST_F(ServerTest, GetEmptyFile) {
  6067. auto res = cli_.Get("/empty_file");
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. EXPECT_EQ(StatusCode::OK_200, res->status);
  6070. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6071. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6072. EXPECT_EQ("", res->body);
  6073. }
  6074. TEST_F(ServerTest, GetFileContent) {
  6075. auto res = cli_.Get("/file_content");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. EXPECT_EQ(StatusCode::OK_200, res->status);
  6078. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6079. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6080. EXPECT_EQ("test.html", res->body);
  6081. }
  6082. TEST_F(ServerTest, GetFileContentWithRange) {
  6083. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6085. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6086. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6087. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6088. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6089. EXPECT_EQ("est", res->body);
  6090. }
  6091. TEST_F(ServerTest, GetFileContentWithContentType) {
  6092. auto res = cli_.Get("/file_content_with_content_type");
  6093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6094. EXPECT_EQ(StatusCode::OK_200, res->status);
  6095. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6096. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6097. EXPECT_EQ("file\n", res->body);
  6098. }
  6099. TEST_F(ServerTest, GetInvalidFileContent) {
  6100. auto res = cli_.Get("/invalid_file_content");
  6101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6102. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6103. }
  6104. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6105. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6107. EXPECT_EQ("HTTP/1.1", res->version);
  6108. EXPECT_EQ(StatusCode::OK_200, res->status);
  6109. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6110. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6111. EXPECT_EQ("Hello World!", res->body);
  6112. }
  6113. TEST_F(ServerTest, GetMethod302) {
  6114. auto res = cli_.Get("/");
  6115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6116. EXPECT_EQ(StatusCode::Found_302, res->status);
  6117. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6118. }
  6119. TEST_F(ServerTest, GetMethod302Redirect) {
  6120. cli_.set_follow_location(true);
  6121. auto res = cli_.Get("/");
  6122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6123. EXPECT_EQ(StatusCode::OK_200, res->status);
  6124. EXPECT_EQ("Hello World!", res->body);
  6125. EXPECT_EQ("/hi", res->location);
  6126. }
  6127. TEST_F(ServerTest, GetMethod404) {
  6128. auto res = cli_.Get("/invalid");
  6129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6130. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6131. }
  6132. TEST_F(ServerTest, HeadMethod200) {
  6133. auto res = cli_.Head("/hi");
  6134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6135. EXPECT_EQ(StatusCode::OK_200, res->status);
  6136. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6137. EXPECT_TRUE(res->body.empty());
  6138. }
  6139. TEST_F(ServerTest, HeadMethod200Static) {
  6140. auto res = cli_.Head("/mount/dir/index.html");
  6141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6142. EXPECT_EQ(StatusCode::OK_200, res->status);
  6143. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6144. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6145. EXPECT_TRUE(res->body.empty());
  6146. }
  6147. TEST_F(ServerTest, HeadMethod404) {
  6148. auto res = cli_.Head("/invalid");
  6149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6150. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6151. EXPECT_TRUE(res->body.empty());
  6152. }
  6153. TEST_F(ServerTest, GetMethodPersonJohn) {
  6154. auto res = cli_.Get("/person/john");
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. EXPECT_EQ(StatusCode::OK_200, res->status);
  6157. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6158. EXPECT_EQ("programmer", res->body);
  6159. }
  6160. TEST_F(ServerTest, PostMethod1) {
  6161. auto res = cli_.Get("/person/john1");
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6164. res = cli_.Post("/person", "name=john1&note=coder",
  6165. "application/x-www-form-urlencoded");
  6166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6167. ASSERT_EQ(StatusCode::OK_200, res->status);
  6168. res = cli_.Get("/person/john1");
  6169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6170. ASSERT_EQ(StatusCode::OK_200, res->status);
  6171. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6172. ASSERT_EQ("coder", res->body);
  6173. }
  6174. TEST_F(ServerTest, PostMethod2) {
  6175. auto res = cli_.Get("/person/john2");
  6176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6177. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6178. Params params;
  6179. params.emplace("name", "john2");
  6180. params.emplace("note", "coder");
  6181. res = cli_.Post("/person", params);
  6182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6183. ASSERT_EQ(StatusCode::OK_200, res->status);
  6184. res = cli_.Get("/person/john2");
  6185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6186. ASSERT_EQ(StatusCode::OK_200, res->status);
  6187. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6188. ASSERT_EQ("coder", res->body);
  6189. }
  6190. TEST_F(ServerTest, PutMethod3) {
  6191. auto res = cli_.Get("/person/john3");
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6194. Params params;
  6195. params.emplace("name", "john3");
  6196. params.emplace("note", "coder");
  6197. res = cli_.Put("/person", params);
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. ASSERT_EQ(StatusCode::OK_200, res->status);
  6200. res = cli_.Get("/person/john3");
  6201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6202. ASSERT_EQ(StatusCode::OK_200, res->status);
  6203. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6204. ASSERT_EQ("coder", res->body);
  6205. }
  6206. TEST_F(ServerTest, DeleteMethod1) {
  6207. auto res = cli_.Get("/person/john4");
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6210. Params params;
  6211. params.emplace("name", "john4");
  6212. params.emplace("note", "coder");
  6213. res = cli_.Post("/person", params);
  6214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6215. ASSERT_EQ(StatusCode::OK_200, res->status);
  6216. res = cli_.Get("/person/john4");
  6217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6218. ASSERT_EQ(StatusCode::OK_200, res->status);
  6219. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6220. ASSERT_EQ("coder", res->body);
  6221. Params delete_params;
  6222. delete_params.emplace("name", "john4");
  6223. res = cli_.Delete("/person", delete_params);
  6224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6225. ASSERT_EQ(StatusCode::OK_200, res->status);
  6226. ASSERT_EQ("DELETED", res->body);
  6227. res = cli_.Get("/person/john4");
  6228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6229. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6230. }
  6231. TEST_F(ServerTest, DeleteMethod2) {
  6232. auto res = cli_.Get("/person/john5");
  6233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6234. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6235. Params params;
  6236. params.emplace("name", "john5");
  6237. params.emplace("note", "developer");
  6238. res = cli_.Post("/person", params);
  6239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6240. ASSERT_EQ(StatusCode::OK_200, res->status);
  6241. res = cli_.Get("/person/john5");
  6242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6243. ASSERT_EQ(StatusCode::OK_200, res->status);
  6244. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6245. ASSERT_EQ("developer", res->body);
  6246. Params delete_params;
  6247. delete_params.emplace("name", "john5");
  6248. Headers headers;
  6249. headers.emplace("Custom-Header", "test-value");
  6250. res = cli_.Delete("/person", headers, delete_params);
  6251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6252. ASSERT_EQ(StatusCode::OK_200, res->status);
  6253. ASSERT_EQ("DELETED", res->body);
  6254. res = cli_.Get("/person/john5");
  6255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6256. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6257. }
  6258. TEST_F(ServerTest, DeleteMethod3) {
  6259. auto res = cli_.Get("/person/john6");
  6260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6261. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6262. Params params;
  6263. params.emplace("name", "john6");
  6264. params.emplace("note", "tester");
  6265. res = cli_.Post("/person", params);
  6266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6267. ASSERT_EQ(StatusCode::OK_200, res->status);
  6268. res = cli_.Get("/person/john6");
  6269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6270. ASSERT_EQ(StatusCode::OK_200, res->status);
  6271. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6272. ASSERT_EQ("tester", res->body);
  6273. Params delete_params;
  6274. delete_params.emplace("name", "john6");
  6275. Headers headers;
  6276. headers.emplace("Custom-Header", "test-value");
  6277. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. ASSERT_EQ(StatusCode::OK_200, res->status);
  6280. ASSERT_EQ("DELETED", res->body);
  6281. res = cli_.Get("/person/john6");
  6282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6283. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6284. }
  6285. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6286. Params params;
  6287. params.emplace("json", JSON_DATA);
  6288. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. ASSERT_EQ(StatusCode::OK_200, res->status);
  6291. ASSERT_EQ(JSON_DATA, res->body);
  6292. }
  6293. TEST_F(ServerTest, PostEmptyContent) {
  6294. auto res = cli_.Post("/empty", "", "text/plain");
  6295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6296. ASSERT_EQ(StatusCode::OK_200, res->status);
  6297. ASSERT_EQ("empty", res->body);
  6298. }
  6299. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6300. auto res = cli_.Post("/empty-no-content-type");
  6301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6302. ASSERT_EQ(StatusCode::OK_200, res->status);
  6303. ASSERT_EQ("empty-no-content-type", res->body);
  6304. }
  6305. TEST_F(ServerTest, PostPathOnly) {
  6306. auto res = cli_.Post("/path-only");
  6307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6308. ASSERT_EQ(StatusCode::OK_200, res->status);
  6309. ASSERT_EQ("path-only", res->body);
  6310. }
  6311. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6312. auto res = cli_.Post("/path-headers-only",
  6313. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6315. ASSERT_EQ(StatusCode::OK_200, res->status);
  6316. ASSERT_EQ("path-headers-only", res->body);
  6317. }
  6318. TEST_F(ServerTest, PostLarge) {
  6319. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6321. ASSERT_EQ(StatusCode::OK_200, res->status);
  6322. EXPECT_EQ(LARGE_DATA, res->body);
  6323. }
  6324. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6325. auto res = cli_.Put("/empty-no-content-type");
  6326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6327. ASSERT_EQ(StatusCode::OK_200, res->status);
  6328. ASSERT_EQ("empty-no-content-type", res->body);
  6329. }
  6330. TEST_F(ServerTest, GetMethodDir) {
  6331. auto res = cli_.Get("/dir/");
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::OK_200, res->status);
  6334. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6335. auto body = R"(<html>
  6336. <head>
  6337. </head>
  6338. <body>
  6339. <a href="/dir/test.html">Test</a>
  6340. <a href="/hi">hi</a>
  6341. </body>
  6342. </html>
  6343. )";
  6344. EXPECT_EQ(body, res->body);
  6345. }
  6346. TEST_F(ServerTest, GetMethodDirTest) {
  6347. auto res = cli_.Get("/dir/test.html");
  6348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6349. EXPECT_EQ(StatusCode::OK_200, res->status);
  6350. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6351. EXPECT_EQ("test.html", res->body);
  6352. }
  6353. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6354. auto res = cli_.Get("/dir/../dir/test.html");
  6355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6356. EXPECT_EQ(StatusCode::OK_200, res->status);
  6357. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6358. EXPECT_EQ("test.html", res->body);
  6359. }
  6360. TEST_F(ServerTest, GetMethodInvalidPath) {
  6361. auto res = cli_.Get("/dir/../test.html");
  6362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6363. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6364. }
  6365. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6366. auto res = cli_.Get("/../www/dir/test.html");
  6367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6368. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6369. }
  6370. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6371. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6373. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6374. }
  6375. TEST_F(ServerTest, GetMethodDirMountTest) {
  6376. auto res = cli_.Get("/mount/dir/test.html");
  6377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6378. EXPECT_EQ(StatusCode::OK_200, res->status);
  6379. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6380. EXPECT_EQ("test.html", res->body);
  6381. }
  6382. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6383. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6385. EXPECT_EQ(StatusCode::OK_200, res->status);
  6386. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6387. EXPECT_EQ("test.html", res->body);
  6388. }
  6389. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6390. auto res = cli_.Get("/mount/dir/../test.html");
  6391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6392. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6393. }
  6394. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6395. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6397. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6398. }
  6399. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6400. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6402. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6403. }
  6404. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6405. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6407. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6408. }
  6409. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6410. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6412. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6413. }
  6414. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6415. auto res = cli_.Get("/mount/dir");
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6418. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6419. }
  6420. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6421. auto res = cli_.Get("//dir");
  6422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6423. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6424. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6425. }
  6426. TEST_F(ServerTest, PostMethod303) {
  6427. auto res = cli_.Post("/1", "body", "text/plain");
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6430. EXPECT_EQ("/2", res->get_header_value("Location"));
  6431. }
  6432. TEST_F(ServerTest, PostMethod303Redirect) {
  6433. cli_.set_follow_location(true);
  6434. auto res = cli_.Post("/1", "body", "text/plain");
  6435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6436. EXPECT_EQ(StatusCode::OK_200, res->status);
  6437. EXPECT_EQ("redirected.", res->body);
  6438. EXPECT_EQ("/2", res->location);
  6439. }
  6440. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6441. auto res = cli_.Get("/dir/test.abcde");
  6442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6443. EXPECT_EQ(StatusCode::OK_200, res->status);
  6444. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6445. EXPECT_EQ("abcde", res->body);
  6446. }
  6447. TEST_F(ServerTest, StaticFileRange) {
  6448. auto res =
  6449. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6451. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6452. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6453. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6454. EXPECT_EQ(true, res->has_header("Content-Range"));
  6455. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6456. EXPECT_EQ(std::string("cd"), res->body);
  6457. }
  6458. TEST_F(ServerTest, StaticFileRanges) {
  6459. auto res = cli_.Get("/dir/test.abcde",
  6460. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6462. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6463. EXPECT_TRUE(
  6464. res->get_header_value("Content-Type")
  6465. .find(
  6466. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6467. 0);
  6468. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6469. }
  6470. TEST_F(ServerTest, StaticFileRangeHead) {
  6471. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6474. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6475. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6476. EXPECT_EQ(true, res->has_header("Content-Range"));
  6477. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6478. }
  6479. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6480. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6482. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6484. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6485. EXPECT_EQ(true, res->has_header("Content-Range"));
  6486. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6487. res->get_header_value("Content-Range"));
  6488. EXPECT_EQ("LAST\n", res->body);
  6489. }
  6490. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6491. auto res =
  6492. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6494. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6495. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6496. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6497. EXPECT_EQ(true, res->has_header("Content-Range"));
  6498. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6499. }
  6500. TEST_F(ServerTest, StaticFileBigFile) {
  6501. auto res = cli_.Get("/dir/1MB.txt");
  6502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6503. EXPECT_EQ(StatusCode::OK_200, res->status);
  6504. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6505. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6506. }
  6507. TEST_F(ServerTest, InvalidBaseDirMount) {
  6508. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6509. }
  6510. TEST_F(ServerTest, Binary) {
  6511. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6512. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6513. "application/octet-stream");
  6514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6515. ASSERT_EQ(StatusCode::OK_200, res->status);
  6516. ASSERT_EQ(4U, res->body.size());
  6517. res = cli_.Put("/binary", binary.data(), binary.size(),
  6518. "application/octet-stream");
  6519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6520. ASSERT_EQ(StatusCode::OK_200, res->status);
  6521. ASSERT_EQ(4U, res->body.size());
  6522. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6523. "application/octet-stream");
  6524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6525. ASSERT_EQ(StatusCode::OK_200, res->status);
  6526. ASSERT_EQ(4U, res->body.size());
  6527. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6528. "application/octet-stream");
  6529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6530. ASSERT_EQ(StatusCode::OK_200, res->status);
  6531. ASSERT_EQ(4U, res->body.size());
  6532. }
  6533. TEST_F(ServerTest, BinaryString) {
  6534. auto binary = std::string("\x00\x01\x02\x03", 4);
  6535. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6537. ASSERT_EQ(StatusCode::OK_200, res->status);
  6538. ASSERT_EQ(4U, res->body.size());
  6539. res = cli_.Put("/binary", binary, "application/octet-stream");
  6540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6541. ASSERT_EQ(StatusCode::OK_200, res->status);
  6542. ASSERT_EQ(4U, res->body.size());
  6543. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6545. ASSERT_EQ(StatusCode::OK_200, res->status);
  6546. ASSERT_EQ(4U, res->body.size());
  6547. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6549. ASSERT_EQ(StatusCode::OK_200, res->status);
  6550. ASSERT_EQ(4U, res->body.size());
  6551. }
  6552. TEST_F(ServerTest, EmptyRequest) {
  6553. auto res = cli_.Get("");
  6554. ASSERT_TRUE(!res);
  6555. EXPECT_EQ(Error::Connection, res.error());
  6556. }
  6557. TEST_F(ServerTest, LongRequest) {
  6558. std::string request;
  6559. for (size_t i = 0; i < 545; i++) {
  6560. request += "/TooLongRequest";
  6561. }
  6562. request += "OK";
  6563. auto res = cli_.Get(request.c_str());
  6564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6565. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6566. }
  6567. TEST_F(ServerTest, TooLongRequest) {
  6568. std::string request;
  6569. for (size_t i = 0; i < 546; i++) {
  6570. request += "/TooLongRequest";
  6571. }
  6572. request += "_NG";
  6573. auto start = std::chrono::high_resolution_clock::now();
  6574. cli_.set_keep_alive(true);
  6575. auto res = cli_.Get(request.c_str());
  6576. auto end = std::chrono::high_resolution_clock::now();
  6577. auto elapsed =
  6578. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6579. .count();
  6580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6581. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6582. EXPECT_LE(elapsed, 1000);
  6583. EXPECT_EQ("close", res->get_header_value("Connection"));
  6584. EXPECT_FALSE(cli_.is_socket_open());
  6585. }
  6586. TEST_F(ServerTest, AlmostTooLongRequest) {
  6587. // test for #2046 - URI length check shouldn't include other content on req
  6588. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6589. // leading /, space, HTTP/1.1)
  6590. std::string request =
  6591. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6592. auto res = cli_.Get(request.c_str());
  6593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6594. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6595. }
  6596. TEST_F(ServerTest, LongHeader) {
  6597. Request req;
  6598. req.method = "GET";
  6599. req.path = "/hi";
  6600. std::string host_and_port;
  6601. host_and_port += HOST;
  6602. host_and_port += ":";
  6603. host_and_port += std::to_string(PORT);
  6604. req.headers.emplace("Host", host_and_port.c_str());
  6605. req.headers.emplace("Accept", "*/*");
  6606. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6607. req.headers.emplace(
  6608. "Header-Name",
  6609. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6610. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6611. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6632. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6635. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6637. "@@@@@@@@@@@@@@@@");
  6638. auto res = std::make_shared<Response>();
  6639. auto error = Error::Success;
  6640. auto ret = cli_.send(req, *res, error);
  6641. ASSERT_TRUE(ret);
  6642. EXPECT_EQ(StatusCode::OK_200, res->status);
  6643. }
  6644. TEST_F(ServerTest, LongQueryValue) {
  6645. auto start = std::chrono::high_resolution_clock::now();
  6646. cli_.set_keep_alive(true);
  6647. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6648. auto end = std::chrono::high_resolution_clock::now();
  6649. auto elapsed =
  6650. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6651. .count();
  6652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6653. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6654. EXPECT_LE(elapsed, 1000);
  6655. EXPECT_EQ("close", res->get_header_value("Connection"));
  6656. EXPECT_FALSE(cli_.is_socket_open());
  6657. }
  6658. TEST_F(ServerTest, TooLongQueryValue) {
  6659. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6660. ASSERT_FALSE(res);
  6661. EXPECT_EQ(Error::Read, res.error());
  6662. }
  6663. TEST_F(ServerTest, TooLongHeader) {
  6664. Request req;
  6665. req.method = "GET";
  6666. req.path = "/hi";
  6667. std::string host_and_port;
  6668. host_and_port += HOST;
  6669. host_and_port += ":";
  6670. host_and_port += std::to_string(PORT);
  6671. req.headers.emplace("Host", host_and_port.c_str());
  6672. req.headers.emplace("Accept", "*/*");
  6673. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6674. req.headers.emplace(
  6675. "Header-Name",
  6676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6691. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6692. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6695. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6696. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6697. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6698. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6699. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6700. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6701. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6704. "@@@@@@@@@@@@@@@@@");
  6705. auto res = std::make_shared<Response>();
  6706. auto error = Error::Success;
  6707. auto ret = cli_.send(req, *res, error);
  6708. ASSERT_TRUE(ret);
  6709. EXPECT_EQ(StatusCode::OK_200, res->status);
  6710. }
  6711. TEST_F(ServerTest, HeaderCountAtLimit) {
  6712. // Test with headers just under the 100 limit
  6713. httplib::Headers headers;
  6714. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6715. // This should keep us just under the 100 header limit
  6716. for (int i = 0; i < 95; i++) {
  6717. std::string name = "X-Test-Header-" + std::to_string(i);
  6718. std::string value = "value" + std::to_string(i);
  6719. headers.emplace(name, value);
  6720. }
  6721. // This should work fine as we're under the limit
  6722. auto res = cli_.Get("/hi", headers);
  6723. EXPECT_TRUE(res);
  6724. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6725. }
  6726. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6727. // Test with many headers to exceed the 100 limit
  6728. httplib::Headers headers;
  6729. // Add 150 headers to definitely exceed the 100 limit
  6730. for (int i = 0; i < 150; i++) {
  6731. std::string name = "X-Test-Header-" + std::to_string(i);
  6732. std::string value = "value" + std::to_string(i);
  6733. headers.emplace(name, value);
  6734. }
  6735. // This should fail due to exceeding header count limit
  6736. cli_.set_keep_alive(true);
  6737. auto res = cli_.Get("/hi", headers);
  6738. // The server should respond with 400 Bad Request
  6739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6740. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6741. EXPECT_EQ("close", res->get_header_value("Connection"));
  6742. EXPECT_FALSE(cli_.is_socket_open());
  6743. }
  6744. TEST_F(ServerTest, PercentEncoding) {
  6745. auto res = cli_.Get("/e%6edwith%");
  6746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6747. EXPECT_EQ(StatusCode::OK_200, res->status);
  6748. }
  6749. TEST_F(ServerTest, PercentEncodingUnicode) {
  6750. auto res = cli_.Get("/e%u006edwith%");
  6751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6752. EXPECT_EQ(StatusCode::OK_200, res->status);
  6753. }
  6754. TEST_F(ServerTest, InvalidPercentEncoding) {
  6755. auto res = cli_.Get("/%endwith%");
  6756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6757. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6758. }
  6759. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6760. auto res = cli_.Get("/%uendwith%");
  6761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6762. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6763. }
  6764. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6765. auto res = cli_.Get("/hello?aaa=bbb%");
  6766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6767. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6768. }
  6769. TEST_F(ServerTest, PlusSignEncoding) {
  6770. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::OK_200, res->status);
  6773. EXPECT_EQ("a +b", res->body);
  6774. }
  6775. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6776. // This test simulates a potential DoS attack using many headers
  6777. // to verify our security fix prevents memory exhaustion
  6778. httplib::Headers attack_headers;
  6779. // Attempt to add many headers like an attacker would (200 headers to far
  6780. // exceed limit)
  6781. for (int i = 0; i < 200; i++) {
  6782. std::string name = "X-Attack-Header-" + std::to_string(i);
  6783. std::string value = "attack_payload_" + std::to_string(i);
  6784. attack_headers.emplace(name, value);
  6785. }
  6786. // Try to POST with excessive headers
  6787. cli_.set_keep_alive(true);
  6788. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6789. // Should either fail or return 400 Bad Request due to security limit
  6790. if (res) {
  6791. // If we get a response, it should be 400 Bad Request
  6792. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6793. EXPECT_EQ("close", res->get_header_value("Connection"));
  6794. }
  6795. EXPECT_FALSE(cli_.is_socket_open());
  6796. }
  6797. TEST_F(ServerTest, MultipartFormData) {
  6798. UploadFormDataItems items = {
  6799. {"text1", "text default", "", ""},
  6800. {"text2", "aωb", "", ""},
  6801. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6802. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6803. {"file3", "", "", "application/octet-stream"},
  6804. {"file4", "", "", " application/json tmp-string "}};
  6805. auto res = cli_.Post("/multipart", items);
  6806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. }
  6809. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6810. UploadFormDataItems items = {
  6811. {"text", "default text", "", ""},
  6812. {"multi_text1", "aaaaa", "", ""},
  6813. {"multi_text1", "bbbbb", "", ""},
  6814. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6815. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6816. "application/json"},
  6817. };
  6818. auto res = cli_.Post("/multipart/multi_file_values", items);
  6819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6820. EXPECT_EQ(StatusCode::OK_200, res->status);
  6821. }
  6822. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6823. auto res = cli_.Get("/hi");
  6824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6825. EXPECT_EQ(StatusCode::OK_200, res->status);
  6826. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6827. EXPECT_EQ("Hello World!", res->body);
  6828. }
  6829. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6830. Request req;
  6831. req.method = "POST";
  6832. req.path = "/chunked";
  6833. std::string host_and_port;
  6834. host_and_port += HOST;
  6835. host_and_port += ":";
  6836. host_and_port += std::to_string(PORT);
  6837. req.headers.emplace("Host", host_and_port.c_str());
  6838. req.headers.emplace("Accept", "*/*");
  6839. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6840. req.headers.emplace("Content-Type", "text/plain");
  6841. req.headers.emplace("Content-Length", "0");
  6842. req.headers.emplace(
  6843. "Transfer-Encoding",
  6844. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6845. // Client does not chunk, so make a chunked body manually.
  6846. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6847. auto res = std::make_shared<Response>();
  6848. auto error = Error::Success;
  6849. auto ret = cli_.send(req, *res, error);
  6850. ASSERT_TRUE(ret);
  6851. EXPECT_EQ(StatusCode::OK_200, res->status);
  6852. }
  6853. template <typename ClientT>
  6854. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6855. int expected_status) {
  6856. Request req;
  6857. req.method = "POST";
  6858. req.path = "/chunked";
  6859. std::string host_and_port;
  6860. host_and_port += HOST;
  6861. host_and_port += ":";
  6862. host_and_port += std::to_string(PORT);
  6863. req.headers.emplace("Host", host_and_port.c_str());
  6864. req.headers.emplace("Content-Length", "0");
  6865. req.headers.emplace("Transfer-Encoding", "chunked");
  6866. req.body = body;
  6867. auto res = std::make_shared<Response>();
  6868. auto error = Error::Success;
  6869. ASSERT_TRUE(cli.send(req, *res, error));
  6870. EXPECT_EQ(expected_status, res->status);
  6871. }
  6872. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6873. // rather than treat them as valid lengths.
  6874. template <typename ClientT>
  6875. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6876. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6877. }
  6878. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6879. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6880. }
  6881. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6882. expect_chunked_body_rejected(
  6883. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6884. }
  6885. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6886. // chunk-size line carries no CR, LF or other control character ahead of its
  6887. // terminator. Such a line must be refused rather than read as extension text.
  6888. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6889. expect_chunked_body_rejected(
  6890. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6891. }
  6892. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6893. expect_chunked_body_rejected(
  6894. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6895. }
  6896. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6897. expect_chunked_body_rejected(
  6898. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6899. }
  6900. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6901. // The literal stays split: a hex escape consumes every hex digit that
  6902. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6903. expect_chunked_body_rejected(
  6904. cli_, "4;a\x01"
  6905. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6906. }
  6907. TEST_F(ServerTest, AcceptsChunkExtension) {
  6908. expect_chunked_body_status(cli_,
  6909. "4;name=value\r\ndech\r\n"
  6910. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6911. "0;last\r\n\r\n",
  6912. StatusCode::OK_200);
  6913. }
  6914. TEST_F(ServerTest, GetStreamed2) {
  6915. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6917. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6918. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6919. EXPECT_EQ(true, res->has_header("Content-Range"));
  6920. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6921. EXPECT_EQ(std::string("ab"), res->body);
  6922. }
  6923. TEST_F(ServerTest, GetStreamed) {
  6924. auto res = cli_.Get("/streamed");
  6925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6926. EXPECT_EQ(StatusCode::OK_200, res->status);
  6927. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6928. EXPECT_EQ(std::string("aaabbb"), res->body);
  6929. }
  6930. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6931. auto res = cli_.Get("/streamed-without-length",
  6932. Headers{make_range_header({{0, -1}})});
  6933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6934. EXPECT_EQ(StatusCode::OK_200, res->status);
  6935. EXPECT_EQ(false, res->has_header("Content-Length"));
  6936. EXPECT_EQ(false, res->has_header("Content-Range"));
  6937. EXPECT_EQ(std::string("abcdefg"), res->body);
  6938. }
  6939. TEST_F(ServerTest, GetStreamedWithRange1) {
  6940. auto res =
  6941. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6944. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6945. EXPECT_EQ(true, res->has_header("Content-Range"));
  6946. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6947. EXPECT_EQ(std::string("def"), res->body);
  6948. }
  6949. TEST_F(ServerTest, GetStreamedWithRange2) {
  6950. auto res =
  6951. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6953. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6954. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6955. EXPECT_EQ(true, res->has_header("Content-Range"));
  6956. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6957. EXPECT_EQ(std::string("bcdefg"), res->body);
  6958. }
  6959. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6960. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6963. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6964. EXPECT_EQ(true, res->has_header("Content-Range"));
  6965. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6966. EXPECT_EQ(std::string("efg"), res->body);
  6967. }
  6968. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6969. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6970. // the entire representation.
  6971. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6972. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6974. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6975. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6976. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6977. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6978. }
  6979. }
  6980. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6981. auto res =
  6982. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6984. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6985. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6986. EXPECT_EQ(false, res->has_header("Content-Range"));
  6987. EXPECT_EQ(0U, res->body.size());
  6988. }
  6989. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6990. // Only a 206 is served as a partial representation. Under any other status
  6991. // `apply_ranges()` reported the full content length, so the body must match
  6992. // that header, and the content provider must never be asked for an offset
  6993. // outside the representation.
  6994. auto check = [&](int status, const char *range) {
  6995. auto path =
  6996. std::string("/streamed-with-range?status=") + std::to_string(status);
  6997. auto ctx = path + " Range: " + range;
  6998. auto res = cli_.Get(path, Headers{{"Range", range}});
  6999. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7000. EXPECT_EQ(status, res->status) << ctx;
  7001. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7002. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7003. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7004. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7005. };
  7006. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7007. check(403, "bytes=3-5");
  7008. // The offset is far past the representation.
  7009. check(403, "bytes=100000-100200");
  7010. // `first_pos` is still -1 here, and the bounds asserts in
  7011. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7012. check(403, "bytes=-3");
  7013. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7014. // multipart branch would have written one that is empty.
  7015. check(403, "bytes=1-2, 4-5");
  7016. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7017. // covers the whole representation.
  7018. check(200, "bytes=3-5");
  7019. check(200, "bytes=1-2, 4-5");
  7020. }
  7021. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7022. auto res =
  7023. cli_.Get("/streamed-with-range",
  7024. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7025. "92233720368547758079223372036854775807"}});
  7026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7027. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7028. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7029. EXPECT_EQ(false, res->has_header("Content-Range"));
  7030. EXPECT_EQ(0U, res->body.size());
  7031. }
  7032. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7033. auto res = cli_.Get(
  7034. "/with-range",
  7035. Headers{{"Range",
  7036. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7037. {"Accept-Encoding", ""}});
  7038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7039. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7040. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7041. EXPECT_EQ(true, res->has_header("Content-Range"));
  7042. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7043. EXPECT_EQ(std::string("abcdefg"), res->body);
  7044. }
  7045. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7046. auto res = cli_.Get("/with-range", Headers{
  7047. {"Range", "bytes=0-"},
  7048. {"Accept-Encoding", ""},
  7049. });
  7050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7051. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7052. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7053. EXPECT_EQ(true, res->has_header("Content-Range"));
  7054. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7055. EXPECT_EQ(std::string("abcdefg"), res->body);
  7056. }
  7057. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7058. auto res = cli_.Get("/streamed-with-range",
  7059. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7062. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7063. EXPECT_EQ(false, res->has_header("Content-Range"));
  7064. EXPECT_EQ(267U, res->body.size());
  7065. // Check that both range contents are present
  7066. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7067. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7068. // Check that Content-Range headers are present for both ranges
  7069. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7070. std::string::npos);
  7071. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7072. std::string::npos);
  7073. }
  7074. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7075. Ranges ranges;
  7076. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7077. ranges.emplace_back(0, -1);
  7078. }
  7079. auto res = cli_.Get("/streamed-with-range?error",
  7080. Headers{{make_range_header(ranges)}});
  7081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7082. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7083. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7084. EXPECT_EQ(false, res->has_header("Content-Range"));
  7085. EXPECT_EQ(0U, res->body.size());
  7086. }
  7087. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7088. auto res = cli_.Get("/streamed-with-range",
  7089. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7091. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7092. EXPECT_EQ(5U, res->body.size());
  7093. // Check that overlapping ranges are coalesced into a single range
  7094. EXPECT_EQ("bcdef", res->body);
  7095. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7096. // Should be single range, not multipart
  7097. EXPECT_TRUE(res->has_header("Content-Range"));
  7098. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7099. }
  7100. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7101. auto res = cli_.Get("/streamed-with-range",
  7102. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7104. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7105. EXPECT_EQ(268U, res->body.size());
  7106. // Check that both range contents are present
  7107. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7108. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7109. // Check that Content-Range headers are present for both ranges
  7110. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7111. std::string::npos);
  7112. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7113. std::string::npos);
  7114. }
  7115. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7116. auto res = cli_.Get("/streamed-with-range",
  7117. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7119. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7120. EXPECT_EQ(269U, res->body.size());
  7121. // Check that both duplicate range contents are present
  7122. size_t first_abc = res->body.find("abc\r\n");
  7123. EXPECT_TRUE(first_abc != std::string::npos);
  7124. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7125. EXPECT_TRUE(second_abc != std::string::npos);
  7126. // Check that Content-Range headers are present for both ranges
  7127. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7128. EXPECT_TRUE(first_range != std::string::npos);
  7129. size_t second_range =
  7130. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7131. EXPECT_TRUE(second_range != std::string::npos);
  7132. }
  7133. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7134. auto res =
  7135. cli_.Get("/streamed-with-range?error",
  7136. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7139. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7140. EXPECT_EQ(false, res->has_header("Content-Range"));
  7141. EXPECT_EQ(0U, res->body.size());
  7142. }
  7143. TEST_F(ServerTest, GetStreamedEndless) {
  7144. uint64_t offset = 0;
  7145. auto res = cli_.Get("/streamed-cancel",
  7146. [&](const char * /*data*/, uint64_t data_length) {
  7147. if (offset < 100) {
  7148. offset += data_length;
  7149. return true;
  7150. }
  7151. return false;
  7152. });
  7153. ASSERT_TRUE(!res);
  7154. EXPECT_EQ(Error::Canceled, res.error());
  7155. }
  7156. TEST_F(ServerTest, ClientStop) {
  7157. std::atomic_size_t count{4};
  7158. std::vector<std::thread> threads;
  7159. for (auto i = count.load(); i != 0; --i) {
  7160. threads.emplace_back([&]() {
  7161. auto res = cli_.Get("/streamed-cancel",
  7162. [&](const char *, uint64_t) { return true; });
  7163. --count;
  7164. ASSERT_TRUE(!res);
  7165. EXPECT_TRUE(res.error() == Error::Canceled ||
  7166. res.error() == Error::Read || res.error() == Error::Write);
  7167. });
  7168. }
  7169. std::this_thread::sleep_for(std::chrono::seconds(2));
  7170. while (count != 0) {
  7171. cli_.stop();
  7172. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7173. }
  7174. for (auto &t : threads) {
  7175. t.join();
  7176. }
  7177. }
  7178. TEST_F(ServerTest, GetWithRange1) {
  7179. auto res = cli_.Get("/with-range", Headers{
  7180. make_range_header({{3, 5}}),
  7181. {"Accept-Encoding", ""},
  7182. });
  7183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7184. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7185. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7186. EXPECT_EQ(true, res->has_header("Content-Range"));
  7187. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7188. EXPECT_EQ(std::string("def"), res->body);
  7189. }
  7190. TEST_F(ServerTest, GetWithRange2) {
  7191. auto res = cli_.Get("/with-range", Headers{
  7192. make_range_header({{1, -1}}),
  7193. {"Accept-Encoding", ""},
  7194. });
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7197. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7198. EXPECT_EQ(true, res->has_header("Content-Range"));
  7199. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7200. EXPECT_EQ(std::string("bcdefg"), res->body);
  7201. }
  7202. TEST_F(ServerTest, GetWithRange3) {
  7203. auto res = cli_.Get("/with-range", Headers{
  7204. make_range_header({{0, 0}}),
  7205. {"Accept-Encoding", ""},
  7206. });
  7207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7208. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7209. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7210. EXPECT_EQ(true, res->has_header("Content-Range"));
  7211. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7212. EXPECT_EQ(std::string("a"), res->body);
  7213. }
  7214. TEST_F(ServerTest, GetWithRange4) {
  7215. auto res = cli_.Get("/with-range", Headers{
  7216. make_range_header({{-1, 2}}),
  7217. {"Accept-Encoding", ""},
  7218. });
  7219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7221. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7222. EXPECT_EQ(true, res->has_header("Content-Range"));
  7223. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7224. EXPECT_EQ(std::string("fg"), res->body);
  7225. }
  7226. TEST_F(ServerTest, GetWithRange5) {
  7227. auto res = cli_.Get("/with-range", Headers{
  7228. make_range_header({{0, 5}}),
  7229. {"Accept-Encoding", ""},
  7230. });
  7231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7232. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7233. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7234. EXPECT_EQ(true, res->has_header("Content-Range"));
  7235. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7236. EXPECT_EQ(std::string("abcdef"), res->body);
  7237. }
  7238. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7239. auto res =
  7240. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7242. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7243. }
  7244. TEST_F(ServerTest, GetWithRangeMultipart) {
  7245. auto res =
  7246. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7248. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7249. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7250. EXPECT_EQ(false, res->has_header("Content-Range"));
  7251. EXPECT_EQ(267U, res->body.size());
  7252. }
  7253. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7254. auto res = cli_.Get("/with-range",
  7255. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7257. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7258. }
  7259. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7260. auto res = cli_.Get("/with-range-customized-response",
  7261. Headers{{make_range_header({{1, 2}})}});
  7262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7263. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7264. EXPECT_EQ(true, res->has_header("Content-Length"));
  7265. EXPECT_EQ(false, res->has_header("Content-Range"));
  7266. EXPECT_EQ(JSON_DATA, res->body);
  7267. }
  7268. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7269. auto res = cli_.Get("/with-range-customized-response",
  7270. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7272. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7273. EXPECT_EQ(true, res->has_header("Content-Length"));
  7274. EXPECT_EQ(false, res->has_header("Content-Range"));
  7275. EXPECT_EQ(JSON_DATA, res->body);
  7276. }
  7277. TEST_F(ServerTest, Issue1772) {
  7278. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7280. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7281. }
  7282. TEST_F(ServerTest, Issue609) {
  7283. auto res = cli_.Delete("/issue609");
  7284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7285. EXPECT_EQ(StatusCode::OK_200, res->status);
  7286. EXPECT_EQ(std::string("ok"), res->body);
  7287. }
  7288. TEST_F(ServerTest, GetStreamedChunked) {
  7289. auto res = cli_.Get("/streamed-chunked");
  7290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7291. EXPECT_EQ(StatusCode::OK_200, res->status);
  7292. EXPECT_EQ(std::string("123456789"), res->body);
  7293. }
  7294. TEST_F(ServerTest, GetStreamedChunked2) {
  7295. auto res = cli_.Get("/streamed-chunked2");
  7296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7297. EXPECT_EQ(StatusCode::OK_200, res->status);
  7298. EXPECT_EQ(std::string("123456789"), res->body);
  7299. }
  7300. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7301. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7303. EXPECT_EQ(StatusCode::OK_200, res->status);
  7304. EXPECT_EQ(std::string("123456789"), res->body);
  7305. EXPECT_TRUE(res->has_header("Trailer"));
  7306. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7307. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7308. // Trailers are now stored separately from headers (security fix)
  7309. EXPECT_EQ(2U, res->trailers.size());
  7310. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7311. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7312. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7313. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7314. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7315. // Verify trailers are NOT in headers (security verification)
  7316. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7317. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7318. }
  7319. TEST_F(ServerTest, LargeChunkedPost) {
  7320. Request req;
  7321. req.method = "POST";
  7322. req.path = "/large-chunked";
  7323. std::string host_and_port;
  7324. host_and_port += HOST;
  7325. host_and_port += ":";
  7326. host_and_port += std::to_string(PORT);
  7327. req.headers.emplace("Host", host_and_port.c_str());
  7328. req.headers.emplace("Accept", "*/*");
  7329. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7330. req.headers.emplace("Content-Type", "text/plain");
  7331. req.headers.emplace("Content-Length", "0");
  7332. req.headers.emplace("Transfer-Encoding", "chunked");
  7333. std::string long_string(30 * 1024u, 'a');
  7334. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7335. // Attempt to make a large enough post to exceed OS buffers, to test that
  7336. // the server handles short reads if the full chunk data isn't available.
  7337. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7338. auto res = std::make_shared<Response>();
  7339. auto error = Error::Success;
  7340. auto ret = cli_.send(req, *res, error);
  7341. ASSERT_TRUE(ret);
  7342. EXPECT_EQ(StatusCode::OK_200, res->status);
  7343. }
  7344. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7345. auto res = cli_.Get("/remote_addr");
  7346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7347. EXPECT_EQ(StatusCode::OK_200, res->status);
  7348. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7349. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7350. }
  7351. TEST_F(ServerTest, GetMethodLocalAddr) {
  7352. auto res = cli_.Get("/local_addr");
  7353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7354. EXPECT_EQ(StatusCode::OK_200, res->status);
  7355. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7356. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7357. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7358. }
  7359. TEST_F(ServerTest, HTTPResponseSplitting) {
  7360. auto res = cli_.Get("/http_response_splitting");
  7361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7362. EXPECT_EQ(StatusCode::OK_200, res->status);
  7363. }
  7364. TEST_F(ServerTest, SlowRequest) {
  7365. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7366. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7367. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7368. }
  7369. #if 0
  7370. TEST_F(ServerTest, SlowPost) {
  7371. char buffer[64 * 1024];
  7372. memset(buffer, 0x42, sizeof(buffer));
  7373. auto res = cli_.Post(
  7374. "/slowpost", 64 * 1024 * 1024,
  7375. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7376. auto ret = sink.write(buffer, sizeof(buffer));
  7377. EXPECT_TRUE(ret);
  7378. return true;
  7379. },
  7380. "text/plain");
  7381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7382. EXPECT_EQ(StatusCode::OK_200, res->status);
  7383. }
  7384. TEST_F(ServerTest, SlowPostFail) {
  7385. char buffer[64 * 1024];
  7386. memset(buffer, 0x42, sizeof(buffer));
  7387. cli_.set_write_timeout(std::chrono::seconds(0));
  7388. auto res = cli_.Post(
  7389. "/slowpost", 64 * 1024 * 1024,
  7390. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7391. sink.write(buffer, sizeof(buffer));
  7392. return true;
  7393. },
  7394. "text/plain");
  7395. ASSERT_TRUE(!res);
  7396. EXPECT_EQ(Error::Write, res.error());
  7397. }
  7398. #endif
  7399. TEST_F(ServerTest, Put) {
  7400. auto res = cli_.Put("/put", "PUT", "text/plain");
  7401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7402. EXPECT_EQ(StatusCode::OK_200, res->status);
  7403. EXPECT_EQ("PUT", res->body);
  7404. }
  7405. TEST_F(ServerTest, PutWithContentProvider) {
  7406. auto res = cli_.Put(
  7407. "/put", 3,
  7408. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7409. sink.os << "PUT";
  7410. return true;
  7411. },
  7412. "text/plain");
  7413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7414. EXPECT_EQ(StatusCode::OK_200, res->status);
  7415. EXPECT_EQ("PUT", res->body);
  7416. }
  7417. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7418. auto res = cli_.Post(
  7419. "/post", 42,
  7420. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7421. return false;
  7422. },
  7423. "text/plain");
  7424. ASSERT_TRUE(!res);
  7425. EXPECT_EQ(Error::Canceled, res.error());
  7426. }
  7427. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7428. auto res = cli_.Put(
  7429. "/put",
  7430. [](size_t /*offset*/, DataSink &sink) {
  7431. sink.os << "PUT";
  7432. sink.done();
  7433. return true;
  7434. },
  7435. "text/plain");
  7436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7437. EXPECT_EQ(StatusCode::OK_200, res->status);
  7438. EXPECT_EQ("PUT", res->body);
  7439. }
  7440. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7441. auto res = cli_.Post(
  7442. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7443. "text/plain");
  7444. ASSERT_TRUE(!res);
  7445. EXPECT_EQ(Error::Canceled, res.error());
  7446. }
  7447. TEST_F(ServerTest, PostLoopBack) {
  7448. std::string body;
  7449. auto res = cli_.Post(
  7450. "/post-loopback", 9,
  7451. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7452. EXPECT_EQ(9u, length);
  7453. sink.write("123", 3);
  7454. sink.write("456", 3);
  7455. sink.write("789", 3);
  7456. return true;
  7457. },
  7458. "text/plain",
  7459. [&body](const char *data, size_t data_length) {
  7460. body.append(data, data_length);
  7461. return true;
  7462. });
  7463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7464. EXPECT_EQ(StatusCode::OK_200, res->status);
  7465. EXPECT_EQ("123456789", body);
  7466. }
  7467. TEST_F(ServerTest, PutLoopBack) {
  7468. std::string body;
  7469. auto res = cli_.Put(
  7470. "/put-loopback", 9,
  7471. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7472. EXPECT_EQ(9u, length);
  7473. sink.write("123", 3);
  7474. sink.write("456", 3);
  7475. sink.write("789", 3);
  7476. return true;
  7477. },
  7478. "text/plain",
  7479. [&body](const char *data, size_t data_length) {
  7480. body.append(data, data_length);
  7481. return true;
  7482. });
  7483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7484. EXPECT_EQ(StatusCode::OK_200, res->status);
  7485. EXPECT_EQ("123456789", body);
  7486. }
  7487. TEST_F(ServerTest, PatchLoopBack) {
  7488. std::string body;
  7489. auto res = cli_.Patch(
  7490. "/patch-loopback", 9,
  7491. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7492. EXPECT_EQ(9u, length);
  7493. sink.write("123", 3);
  7494. sink.write("456", 3);
  7495. sink.write("789", 3);
  7496. return true;
  7497. },
  7498. "text/plain",
  7499. [&body](const char *data, size_t data_length) {
  7500. body.append(data, data_length);
  7501. return true;
  7502. });
  7503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7504. EXPECT_EQ(StatusCode::OK_200, res->status);
  7505. EXPECT_EQ("123456789", body);
  7506. }
  7507. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7508. std::string body;
  7509. auto res = cli_.Post(
  7510. "/post-loopback",
  7511. [](size_t /*offset*/, DataSink &sink) {
  7512. sink.write("123", 3);
  7513. sink.write("456", 3);
  7514. sink.write("789", 3);
  7515. sink.done();
  7516. return true;
  7517. },
  7518. "text/plain",
  7519. [&body](const char *data, size_t data_length) {
  7520. body.append(data, data_length);
  7521. return true;
  7522. });
  7523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7524. EXPECT_EQ(StatusCode::OK_200, res->status);
  7525. EXPECT_EQ("123456789", body);
  7526. }
  7527. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7528. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7529. cli_.set_compress(true);
  7530. auto res = cli_.Put(
  7531. "/put", 3,
  7532. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7533. sink.os << "PUT";
  7534. return true;
  7535. },
  7536. "text/plain");
  7537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7538. EXPECT_EQ(StatusCode::OK_200, res->status);
  7539. EXPECT_EQ("PUT", res->body);
  7540. }
  7541. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7542. cli_.set_compress(true);
  7543. auto res = cli_.Post(
  7544. "/post", 42,
  7545. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7546. return false;
  7547. },
  7548. "text/plain");
  7549. ASSERT_TRUE(!res);
  7550. EXPECT_EQ(Error::Canceled, res.error());
  7551. }
  7552. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7553. cli_.set_compress(true);
  7554. auto res = cli_.Put(
  7555. "/put",
  7556. [](size_t /*offset*/, DataSink &sink) {
  7557. sink.os << "PUT";
  7558. sink.done();
  7559. return true;
  7560. },
  7561. "text/plain");
  7562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7563. EXPECT_EQ(StatusCode::OK_200, res->status);
  7564. EXPECT_EQ("PUT", res->body);
  7565. }
  7566. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7567. cli_.set_compress(true);
  7568. auto res = cli_.Post(
  7569. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7570. "text/plain");
  7571. ASSERT_TRUE(!res);
  7572. EXPECT_EQ(Error::Canceled, res.error());
  7573. }
  7574. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7575. cli_.set_compress(true);
  7576. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7578. EXPECT_EQ(StatusCode::OK_200, res->status);
  7579. EXPECT_EQ(LARGE_DATA, res->body);
  7580. }
  7581. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7582. #ifdef CPPHTTPLIB_SSL_ENABLED
  7583. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7584. Client cli(s.c_str());
  7585. cli.enable_server_certificate_verification(false);
  7586. #else
  7587. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7588. Client cli(s.c_str());
  7589. #endif
  7590. cli.set_compress(true);
  7591. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7593. EXPECT_EQ(StatusCode::OK_200, res->status);
  7594. EXPECT_EQ(LARGE_DATA, res->body);
  7595. // The compressed size should be less than a 10th of the original. May vary
  7596. // depending on the zlib library.
  7597. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7598. static_cast<uint64_t>(10 * 1024 * 1024));
  7599. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7600. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7601. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7602. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7603. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7604. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7605. #endif
  7606. }
  7607. TEST_F(ServerTest, PutContentWithDeflate) {
  7608. cli_.set_compress(false);
  7609. Headers headers;
  7610. headers.emplace("Content-Encoding", "deflate");
  7611. // PUT in deflate format:
  7612. auto res = cli_.Put("/put", headers,
  7613. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7615. EXPECT_EQ(StatusCode::OK_200, res->status);
  7616. EXPECT_EQ("PUT", res->body);
  7617. }
  7618. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7619. Headers headers;
  7620. headers.emplace("Accept-Encoding", "gzip, deflate");
  7621. auto res = cli_.Get("/streamed-chunked", headers);
  7622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7623. EXPECT_EQ(StatusCode::OK_200, res->status);
  7624. EXPECT_EQ(std::string("123456789"), res->body);
  7625. }
  7626. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7627. Headers headers;
  7628. headers.emplace("Accept-Encoding", "gzip, deflate");
  7629. auto res = cli_.Get("/streamed-chunked2", headers);
  7630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7631. EXPECT_EQ(StatusCode::OK_200, res->status);
  7632. EXPECT_EQ(std::string("123456789"), res->body);
  7633. }
  7634. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7635. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7637. EXPECT_EQ(StatusCode::OK_200, res->status);
  7638. }
  7639. TEST(GzipDecompressor, ChunkedDecompression) {
  7640. std::string data;
  7641. for (size_t i = 0; i < 32 * 1024; ++i) {
  7642. data.push_back(static_cast<char>('a' + i % 26));
  7643. }
  7644. std::string compressed_data;
  7645. {
  7646. httplib::detail::gzip_compressor compressor;
  7647. bool result = compressor.compress(
  7648. data.data(), data.size(),
  7649. /*last=*/true,
  7650. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7651. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7652. compressed_data_size);
  7653. return true;
  7654. });
  7655. ASSERT_TRUE(result);
  7656. }
  7657. std::string decompressed_data;
  7658. {
  7659. httplib::detail::gzip_decompressor decompressor;
  7660. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7661. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7662. size_t chunk_size = 130;
  7663. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7664. chunk_begin += chunk_size) {
  7665. size_t current_chunk_size =
  7666. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7667. bool result = decompressor.decompress(
  7668. compressed_data.data() + chunk_begin, current_chunk_size,
  7669. [&](const char *decompressed_data_chunk,
  7670. size_t decompressed_data_chunk_size) {
  7671. decompressed_data.insert(decompressed_data.size(),
  7672. decompressed_data_chunk,
  7673. decompressed_data_chunk_size);
  7674. return true;
  7675. });
  7676. ASSERT_TRUE(result);
  7677. }
  7678. }
  7679. ASSERT_EQ(data, decompressed_data);
  7680. }
  7681. TEST(GzipDecompressor, DeflateDecompression) {
  7682. std::string original_text = "Raw deflate without gzip";
  7683. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7684. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7685. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7686. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7687. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7688. std::string decompressed_data;
  7689. {
  7690. httplib::detail::gzip_decompressor decompressor;
  7691. bool result = decompressor.decompress(
  7692. compressed_data.data(), compressed_data.size(),
  7693. [&](const char *decompressed_data_chunk,
  7694. size_t decompressed_data_chunk_size) {
  7695. decompressed_data.insert(decompressed_data.size(),
  7696. decompressed_data_chunk,
  7697. decompressed_data_chunk_size);
  7698. return true;
  7699. });
  7700. ASSERT_TRUE(result);
  7701. }
  7702. ASSERT_EQ(original_text, decompressed_data);
  7703. }
  7704. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7705. std::string original_text = "Raw deflate without gzip";
  7706. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7707. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7708. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7709. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7710. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7711. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7712. std::string decompressed_data;
  7713. {
  7714. httplib::detail::gzip_decompressor decompressor;
  7715. bool result = decompressor.decompress(
  7716. compressed_data.data(), compressed_data.size(),
  7717. [&](const char *decompressed_data_chunk,
  7718. size_t decompressed_data_chunk_size) {
  7719. decompressed_data.insert(decompressed_data.size(),
  7720. decompressed_data_chunk,
  7721. decompressed_data_chunk_size);
  7722. return true;
  7723. });
  7724. ASSERT_TRUE(result);
  7725. }
  7726. ASSERT_EQ(original_text, decompressed_data);
  7727. }
  7728. #endif
  7729. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7730. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7731. Headers headers;
  7732. headers.emplace("Accept-Encoding", "br");
  7733. auto res = cli_.Get("/streamed-chunked", headers);
  7734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7735. EXPECT_EQ(StatusCode::OK_200, res->status);
  7736. EXPECT_EQ(std::string("123456789"), res->body);
  7737. }
  7738. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7739. Headers headers;
  7740. headers.emplace("Accept-Encoding", "br");
  7741. auto res = cli_.Get("/streamed-chunked2", headers);
  7742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7743. EXPECT_EQ(StatusCode::OK_200, res->status);
  7744. EXPECT_EQ(std::string("123456789"), res->body);
  7745. }
  7746. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7747. cli_.set_compress(true);
  7748. auto res = cli_.Put(
  7749. "/put", 3,
  7750. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7751. sink.os << "PUT";
  7752. return true;
  7753. },
  7754. "text/plain");
  7755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7756. EXPECT_EQ(StatusCode::OK_200, res->status);
  7757. EXPECT_EQ("PUT", res->body);
  7758. }
  7759. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7760. cli_.set_compress(true);
  7761. auto res = cli_.Put(
  7762. "/put",
  7763. [](size_t /*offset*/, DataSink &sink) {
  7764. sink.os << "PUT";
  7765. sink.done();
  7766. return true;
  7767. },
  7768. "text/plain");
  7769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7770. EXPECT_EQ(StatusCode::OK_200, res->status);
  7771. EXPECT_EQ("PUT", res->body);
  7772. }
  7773. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7774. cli_.set_compress(true);
  7775. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7777. EXPECT_EQ(StatusCode::OK_200, res->status);
  7778. EXPECT_EQ(LARGE_DATA, res->body);
  7779. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7780. }
  7781. #endif
  7782. TEST_F(ServerTest, Patch) {
  7783. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7785. EXPECT_EQ(StatusCode::OK_200, res->status);
  7786. EXPECT_EQ("PATCH", res->body);
  7787. }
  7788. TEST_F(ServerTest, Delete) {
  7789. auto res = cli_.Delete("/delete");
  7790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7791. EXPECT_EQ(StatusCode::OK_200, res->status);
  7792. EXPECT_EQ("DELETE", res->body);
  7793. }
  7794. TEST_F(ServerTest, DeleteContentReceiver) {
  7795. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7797. EXPECT_EQ(StatusCode::OK_200, res->status);
  7798. EXPECT_EQ("content", res->body);
  7799. }
  7800. TEST_F(ServerTest, Options) {
  7801. auto res = cli_.Options("*");
  7802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7803. EXPECT_EQ(StatusCode::OK_200, res->status);
  7804. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7805. EXPECT_TRUE(res->body.empty());
  7806. }
  7807. TEST_F(ServerTest, URL) {
  7808. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7810. EXPECT_EQ(StatusCode::OK_200, res->status);
  7811. }
  7812. TEST_F(ServerTest, ArrayParam) {
  7813. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7815. EXPECT_EQ(StatusCode::OK_200, res->status);
  7816. }
  7817. TEST_F(ServerTest, ArrayParamValues) {
  7818. auto res =
  7819. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7821. EXPECT_EQ(StatusCode::OK_200, res->status);
  7822. }
  7823. TEST_F(ServerTest, NoMultipleHeaders) {
  7824. Headers headers = {{"Content-Length", "5"}};
  7825. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7826. "text/plain");
  7827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7828. EXPECT_EQ(StatusCode::OK_200, res->status);
  7829. }
  7830. TEST_F(ServerTest, PostContentReceiver) {
  7831. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7833. ASSERT_EQ(StatusCode::OK_200, res->status);
  7834. ASSERT_EQ("content", res->body);
  7835. }
  7836. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7837. UploadFormDataItems items = {
  7838. {"text1", "text default", "", ""},
  7839. {"text2", "aωb", "", ""},
  7840. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7841. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7842. {"file3", "", "", "application/octet-stream"},
  7843. };
  7844. auto res = cli_.Post("/content_receiver", items);
  7845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7846. EXPECT_EQ(StatusCode::OK_200, res->status);
  7847. }
  7848. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7849. UploadFormDataItems items = {
  7850. {"text1", "text default", "", ""},
  7851. {"text2", "aωb", "", ""},
  7852. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7853. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7854. {"file3", "", "", "application/octet-stream"},
  7855. };
  7856. auto boundary = std::string("+++++");
  7857. std::string body;
  7858. for (const auto &item : items) {
  7859. body += "--" + boundary + "\r\n";
  7860. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7861. if (!item.filename.empty()) {
  7862. body += "; filename=\"" + item.filename + "\"";
  7863. }
  7864. body += "\r\n";
  7865. if (!item.content_type.empty()) {
  7866. body += "Content-Type: " + item.content_type + "\r\n";
  7867. }
  7868. body += "\r\n";
  7869. body += item.content + "\r\n";
  7870. }
  7871. body += "--" + boundary + "--\r\n";
  7872. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7873. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7875. EXPECT_EQ(StatusCode::OK_200, res->status);
  7876. }
  7877. TEST(MultipartFormDataTest, FieldEscaping) {
  7878. Server svr;
  7879. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7880. const ContentReader &content_reader) {
  7881. ASSERT_TRUE(req.is_multipart_form_data());
  7882. std::vector<FormData> received;
  7883. content_reader(
  7884. [&](const FormData &file) {
  7885. received.push_back(file);
  7886. return true;
  7887. },
  7888. [&](const char *data, size_t data_length) {
  7889. received.back().content.append(data, data_length);
  7890. return true;
  7891. });
  7892. // '"', CR and LF in names and filenames are escaped following the
  7893. // WHATWG HTML standard, so each part still parses as a single part
  7894. // with no injected headers. Content types get CR/LF escaped too,
  7895. // while '"' (legal there, e.g. quoted charset) is preserved.
  7896. ASSERT_EQ(4U, received.size());
  7897. EXPECT_EQ("na%22me", received[0].name);
  7898. EXPECT_EQ("quoted name", received[0].content);
  7899. EXPECT_EQ("file", received[1].name);
  7900. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7901. received[1].filename);
  7902. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7903. EXPECT_EQ("injected", received[1].content);
  7904. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7905. EXPECT_EQ("my%22file.txt", received[2].filename);
  7906. EXPECT_EQ("cr lf name", received[2].content);
  7907. EXPECT_EQ("typed", received[3].name);
  7908. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7909. received[3].content_type);
  7910. EXPECT_EQ("typed content", received[3].content);
  7911. });
  7912. auto port = svr.bind_to_any_port("localhost");
  7913. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7914. auto se = detail::scope_exit([&] {
  7915. svr.stop();
  7916. t.join();
  7917. ASSERT_FALSE(svr.is_running());
  7918. });
  7919. svr.wait_until_ready();
  7920. Client cli("localhost", port);
  7921. UploadFormDataItems items = {
  7922. {"na\"me", "quoted name", "", ""},
  7923. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7924. "application/octet-stream"},
  7925. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7926. {"typed", "typed content", "",
  7927. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7928. };
  7929. auto res = cli.Post("/post", items);
  7930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7931. EXPECT_EQ(StatusCode::OK_200, res->status);
  7932. }
  7933. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7934. const UploadFormDataItems items = {
  7935. {"name1", "Content 1", "", ""},
  7936. {"name2", "Content 2", "file2.txt", "text/plain"},
  7937. };
  7938. Server svr;
  7939. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7940. const ContentReader &content_reader) {
  7941. ASSERT_TRUE(req.is_multipart_form_data());
  7942. std::vector<FormData> received;
  7943. content_reader(
  7944. [&](const FormData &file) {
  7945. received.push_back(file);
  7946. return true;
  7947. },
  7948. [&](const char *data, size_t data_length) {
  7949. received.back().content.append(data, data_length);
  7950. return true;
  7951. });
  7952. ASSERT_EQ(2U, received.size());
  7953. EXPECT_EQ("name1", received[0].name);
  7954. EXPECT_EQ("Content 1", received[0].content);
  7955. EXPECT_EQ("name2", received[1].name);
  7956. EXPECT_EQ("Content 2", received[1].content);
  7957. EXPECT_EQ("file2.txt", received[1].filename);
  7958. EXPECT_EQ("text/plain", received[1].content_type);
  7959. });
  7960. auto port = svr.bind_to_any_port("localhost");
  7961. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7962. auto se = detail::scope_exit([&] {
  7963. svr.stop();
  7964. t.join();
  7965. ASSERT_FALSE(svr.is_running());
  7966. });
  7967. svr.wait_until_ready();
  7968. Client cli("localhost", port);
  7969. // Whole-body serialization with a generated boundary
  7970. {
  7971. MultipartFormDataWriter writer;
  7972. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7973. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7974. writer.content_type());
  7975. auto body = writer.serialize(items);
  7976. EXPECT_EQ(body.size(), writer.content_length(items));
  7977. auto res = cli.Post("/post", body, writer.content_type());
  7978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7979. EXPECT_EQ(StatusCode::OK_200, res->status);
  7980. }
  7981. // Per-part framing with a custom boundary via a content provider
  7982. {
  7983. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7984. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7985. MultipartFormDataWriter writer("custom-boundary_123");
  7986. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7987. std::string body;
  7988. for (const auto &item : items) {
  7989. body += writer.item_begin(item);
  7990. body += item.content;
  7991. body += MultipartFormDataWriter::item_end();
  7992. }
  7993. body += writer.finish();
  7994. EXPECT_EQ(body.size(), writer.content_length(items));
  7995. auto res = cli.Post(
  7996. "/post", body.size(),
  7997. [&](size_t offset, size_t length, DataSink &sink) {
  7998. sink.write(body.data() + offset, length);
  7999. return true;
  8000. },
  8001. writer.content_type());
  8002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8003. EXPECT_EQ(StatusCode::OK_200, res->status);
  8004. }
  8005. }
  8006. TEST_F(ServerTest, PostContentReceiverGzip) {
  8007. cli_.set_compress(true);
  8008. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8010. ASSERT_EQ(StatusCode::OK_200, res->status);
  8011. ASSERT_EQ("content", res->body);
  8012. }
  8013. TEST_F(ServerTest, PutContentReceiver) {
  8014. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8016. ASSERT_EQ(StatusCode::OK_200, res->status);
  8017. ASSERT_EQ("content", res->body);
  8018. }
  8019. TEST_F(ServerTest, PatchContentReceiver) {
  8020. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8022. ASSERT_EQ(StatusCode::OK_200, res->status);
  8023. ASSERT_EQ("content", res->body);
  8024. }
  8025. template <typename ClientType>
  8026. void TestWithHeadersAndContentReceiver(
  8027. ClientType &cli,
  8028. std::function<Result(ClientType &, const std::string &, const Headers &,
  8029. const std::string &, const std::string &,
  8030. ContentReceiver, DownloadProgress)>
  8031. request_func) {
  8032. Headers headers;
  8033. headers.emplace("X-Custom-Header", "test-value");
  8034. std::string received_body;
  8035. auto res = request_func(
  8036. cli, "/content_receiver", headers, "content", "application/json",
  8037. [&](const char *data, size_t data_length) {
  8038. received_body.append(data, data_length);
  8039. return true;
  8040. },
  8041. nullptr);
  8042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8043. EXPECT_EQ(StatusCode::OK_200, res->status);
  8044. EXPECT_EQ("content", received_body);
  8045. }
  8046. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8047. #ifdef CPPHTTPLIB_SSL_ENABLED
  8048. using ClientT = SSLClient;
  8049. #else
  8050. using ClientT = Client;
  8051. #endif
  8052. TestWithHeadersAndContentReceiver<ClientT>(
  8053. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8054. const std::string &body, const std::string &content_type,
  8055. ContentReceiver receiver, DownloadProgress progress) {
  8056. return cli.Post(path, headers, body, content_type, receiver, progress);
  8057. });
  8058. }
  8059. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8060. #ifdef CPPHTTPLIB_SSL_ENABLED
  8061. using ClientT = SSLClient;
  8062. #else
  8063. using ClientT = Client;
  8064. #endif
  8065. TestWithHeadersAndContentReceiver<ClientT>(
  8066. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8067. const std::string &body, const std::string &content_type,
  8068. ContentReceiver receiver, DownloadProgress progress) {
  8069. return cli.Put(path, headers, body, content_type, receiver, progress);
  8070. });
  8071. }
  8072. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8073. #ifdef CPPHTTPLIB_SSL_ENABLED
  8074. using ClientT = SSLClient;
  8075. #else
  8076. using ClientT = Client;
  8077. #endif
  8078. TestWithHeadersAndContentReceiver<ClientT>(
  8079. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8080. const std::string &body, const std::string &content_type,
  8081. ContentReceiver receiver, DownloadProgress progress) {
  8082. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8083. });
  8084. }
  8085. template <typename ClientType>
  8086. void TestWithHeadersAndContentReceiverWithProgress(
  8087. ClientType &cli,
  8088. std::function<Result(ClientType &, const std::string &, const Headers &,
  8089. const std::string &, const std::string &,
  8090. ContentReceiver, DownloadProgress)>
  8091. request_func) {
  8092. Headers headers;
  8093. headers.emplace("X-Test-Header", "progress-test");
  8094. std::string received_body;
  8095. auto progress_called = false;
  8096. auto res = request_func(
  8097. cli, "/content_receiver", headers, "content", "text/plain",
  8098. [&](const char *data, size_t data_length) {
  8099. received_body.append(data, data_length);
  8100. return true;
  8101. },
  8102. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8103. progress_called = true;
  8104. return true;
  8105. });
  8106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8107. EXPECT_EQ(StatusCode::OK_200, res->status);
  8108. EXPECT_EQ("content", received_body);
  8109. EXPECT_TRUE(progress_called);
  8110. }
  8111. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8112. #ifdef CPPHTTPLIB_SSL_ENABLED
  8113. using ClientT = SSLClient;
  8114. #else
  8115. using ClientT = Client;
  8116. #endif
  8117. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8118. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8119. const std::string &body, const std::string &content_type,
  8120. ContentReceiver receiver, DownloadProgress progress) {
  8121. return cli.Post(path, headers, body, content_type, receiver, progress);
  8122. });
  8123. }
  8124. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8125. #ifdef CPPHTTPLIB_SSL_ENABLED
  8126. using ClientT = SSLClient;
  8127. #else
  8128. using ClientT = Client;
  8129. #endif
  8130. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8131. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8132. const std::string &body, const std::string &content_type,
  8133. ContentReceiver receiver, DownloadProgress progress) {
  8134. return cli.Put(path, headers, body, content_type, receiver, progress);
  8135. });
  8136. }
  8137. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8138. #ifdef CPPHTTPLIB_SSL_ENABLED
  8139. using ClientT = SSLClient;
  8140. #else
  8141. using ClientT = Client;
  8142. #endif
  8143. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8144. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8145. const std::string &body, const std::string &content_type,
  8146. ContentReceiver receiver, DownloadProgress progress) {
  8147. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8148. });
  8149. }
  8150. template <typename ClientType>
  8151. void TestWithHeadersAndContentReceiverError(
  8152. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8153. const Headers &, const std::string &,
  8154. const std::string &, ContentReceiver)>
  8155. request_func) {
  8156. Headers headers;
  8157. headers.emplace("X-Error-Test", "true");
  8158. std::string received_body;
  8159. auto receiver_failed = false;
  8160. auto res =
  8161. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8162. [&](const char *data, size_t data_length) {
  8163. received_body.append(data, data_length);
  8164. receiver_failed = true;
  8165. return false;
  8166. });
  8167. ASSERT_FALSE(res);
  8168. EXPECT_TRUE(receiver_failed);
  8169. }
  8170. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8171. #ifdef CPPHTTPLIB_SSL_ENABLED
  8172. using ClientT = SSLClient;
  8173. #else
  8174. using ClientT = Client;
  8175. #endif
  8176. TestWithHeadersAndContentReceiverError<ClientT>(
  8177. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8178. const std::string &body, const std::string &content_type,
  8179. ContentReceiver receiver) {
  8180. return cli.Post(path, headers, body, content_type, receiver);
  8181. });
  8182. }
  8183. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8184. #ifdef CPPHTTPLIB_SSL_ENABLED
  8185. using ClientT = SSLClient;
  8186. #else
  8187. using ClientT = Client;
  8188. #endif
  8189. TestWithHeadersAndContentReceiverError<ClientT>(
  8190. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8191. const std::string &body, const std::string &content_type,
  8192. ContentReceiver receiver) {
  8193. return cli.Put(path, headers, body, content_type, receiver);
  8194. });
  8195. }
  8196. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8197. #ifdef CPPHTTPLIB_SSL_ENABLED
  8198. using ClientT = SSLClient;
  8199. #else
  8200. using ClientT = Client;
  8201. #endif
  8202. TestWithHeadersAndContentReceiverError<ClientT>(
  8203. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8204. const std::string &body, const std::string &content_type,
  8205. ContentReceiver receiver) {
  8206. return cli.Patch(path, headers, body, content_type, receiver);
  8207. });
  8208. }
  8209. TEST_F(ServerTest, PostQueryStringAndBody) {
  8210. auto res =
  8211. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8213. ASSERT_EQ(StatusCode::OK_200, res->status);
  8214. }
  8215. TEST_F(ServerTest, HTTP2Magic) {
  8216. Request req;
  8217. req.method = "PRI";
  8218. req.path = "*";
  8219. req.body = "SM";
  8220. auto res = std::make_shared<Response>();
  8221. auto error = Error::Success;
  8222. auto ret = cli_.send(req, *res, error);
  8223. ASSERT_TRUE(ret);
  8224. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8225. }
  8226. TEST_F(ServerTest, KeepAlive) {
  8227. auto res = cli_.Get("/hi");
  8228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8229. EXPECT_EQ(StatusCode::OK_200, res->status);
  8230. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8231. EXPECT_EQ("Hello World!", res->body);
  8232. res = cli_.Get("/hi");
  8233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8234. EXPECT_EQ(StatusCode::OK_200, res->status);
  8235. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8236. EXPECT_EQ("Hello World!", res->body);
  8237. res = cli_.Get("/hi");
  8238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8239. EXPECT_EQ(StatusCode::OK_200, res->status);
  8240. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8241. EXPECT_EQ("Hello World!", res->body);
  8242. res = cli_.Get("/not-exist");
  8243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8244. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8245. res = cli_.Post("/empty", "", "text/plain");
  8246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8247. EXPECT_EQ(StatusCode::OK_200, res->status);
  8248. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8249. EXPECT_EQ("empty", res->body);
  8250. EXPECT_EQ("close", res->get_header_value("Connection"));
  8251. res = cli_.Post(
  8252. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8253. "text/plain");
  8254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8255. EXPECT_EQ(StatusCode::OK_200, res->status);
  8256. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8257. EXPECT_EQ("empty", res->body);
  8258. cli_.set_keep_alive(false);
  8259. res = cli_.Get("/last-request");
  8260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8261. EXPECT_EQ(StatusCode::OK_200, res->status);
  8262. EXPECT_EQ("close", res->get_header_value("Connection"));
  8263. }
  8264. TEST_F(ServerTest, TooManyRedirect) {
  8265. cli_.set_follow_location(true);
  8266. auto res = cli_.Get("/redirect/0");
  8267. ASSERT_TRUE(!res);
  8268. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8269. }
  8270. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8271. Request req;
  8272. req.method = "FOOBAR";
  8273. req.path = "/hi";
  8274. cli_.set_keep_alive(true);
  8275. auto res = cli_.send(req);
  8276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8277. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8278. EXPECT_EQ("close", res->get_header_value("Connection"));
  8279. EXPECT_FALSE(cli_.is_socket_open());
  8280. }
  8281. TEST_F(ServerTest, CustomRouteReadsBody) {
  8282. const std::string xml =
  8283. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8284. Request req;
  8285. req.method = "PROPFIND";
  8286. req.path = "/dav/dir";
  8287. req.set_header("Depth", "1");
  8288. req.body = xml;
  8289. auto res = cli_.send(req);
  8290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8291. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8292. EXPECT_EQ(xml, res->body);
  8293. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8294. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8295. }
  8296. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8297. Request req;
  8298. req.method = "PROPFIND";
  8299. req.path = "/dav/42";
  8300. auto res = cli_.send(req);
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8303. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8304. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8305. }
  8306. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8307. Request req;
  8308. req.method = "PROPFIND";
  8309. req.path = "/dav-re/123";
  8310. auto res = cli_.send(req);
  8311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8312. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8313. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8314. }
  8315. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8316. Request req;
  8317. req.method = "MKCOL";
  8318. req.path = "/dav-mkcol";
  8319. auto res = cli_.send(req);
  8320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8321. EXPECT_EQ(StatusCode::Created_201, res->status);
  8322. }
  8323. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8324. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8325. Request req;
  8326. req.method = "REPORT";
  8327. req.path = "/dav-report";
  8328. req.body = xml;
  8329. auto res = cli_.send(req);
  8330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8331. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8332. EXPECT_EQ(xml, res->body);
  8333. }
  8334. // A content reader route must fire even when the request carries no body,
  8335. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8336. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8337. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8338. Request req;
  8339. req.method = "REPORT";
  8340. req.path = "/dav-report";
  8341. auto res = cli_.send(req);
  8342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8343. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8344. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8345. }
  8346. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8347. Request req;
  8348. req.method = "PROPFIND";
  8349. req.path = "/not-dav";
  8350. auto res = cli_.send(req);
  8351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8352. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8353. }
  8354. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8355. Request req;
  8356. req.method = "UNLOCK";
  8357. req.path = "/dav/dir";
  8358. cli_.set_keep_alive(true);
  8359. auto res = cli_.send(req);
  8360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8361. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8362. EXPECT_EQ("close", res->get_header_value("Connection"));
  8363. EXPECT_FALSE(cli_.is_socket_open());
  8364. }
  8365. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8366. // The mount point serves this path, but only for GET and HEAD.
  8367. auto get_res = cli_.Get("/dir/index.html");
  8368. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8369. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8370. Request req;
  8371. req.method = "PROPFIND";
  8372. req.path = "/dir/index.html";
  8373. auto res = cli_.send(req);
  8374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8375. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8376. }
  8377. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8378. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8379. cli_.set_keep_alive(true);
  8380. for (auto i = 0; i < 2; i++) {
  8381. Request req;
  8382. req.method = "PROPFIND";
  8383. req.path = "/dav/dir";
  8384. req.body = xml;
  8385. auto res = cli_.send(req);
  8386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8387. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8388. EXPECT_EQ(xml, res->body);
  8389. EXPECT_TRUE(cli_.is_socket_open());
  8390. }
  8391. // A built-in method must still be served on the same connection.
  8392. cli_.set_keep_alive(false);
  8393. auto res = cli_.Get("/hi");
  8394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8395. EXPECT_EQ(StatusCode::OK_200, res->status);
  8396. EXPECT_EQ("close", res->get_header_value("Connection"));
  8397. }
  8398. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8399. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8400. Request req;
  8401. req.method = "PROPFIND";
  8402. req.path = "/dav/dir";
  8403. req.set_header("Expect", "100-continue");
  8404. req.body = xml;
  8405. auto res = cli_.send(req);
  8406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8407. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8408. EXPECT_EQ(xml, res->body);
  8409. }
  8410. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8411. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8412. TEST_F(ServerTest, Gzip) {
  8413. Headers headers;
  8414. headers.emplace("Accept-Encoding", "gzip, deflate");
  8415. auto res = cli_.Get("/compress", headers);
  8416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8417. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8418. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8419. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8420. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8421. "7890123456789012345678901234567890",
  8422. res->body);
  8423. EXPECT_EQ(StatusCode::OK_200, res->status);
  8424. }
  8425. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8426. Headers headers;
  8427. headers.emplace("Accept-Encoding", "gzip, deflate");
  8428. auto res = cli_.Get("/compress-with-charset", headers);
  8429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8430. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8431. EXPECT_EQ("application/json; charset=utf-8",
  8432. res->get_header_value("Content-Type"));
  8433. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8434. "7890123456789012345678901234567890",
  8435. res->body);
  8436. EXPECT_EQ(StatusCode::OK_200, res->status);
  8437. }
  8438. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8439. Headers headers;
  8440. headers.emplace("Accept-Encoding", "");
  8441. auto res = cli_.Get("/compress", headers);
  8442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8443. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8444. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8445. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8446. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8447. "7890123456789012345678901234567890",
  8448. res->body);
  8449. EXPECT_EQ(StatusCode::OK_200, res->status);
  8450. }
  8451. TEST_F(ServerTest, GzipWithContentReceiver) {
  8452. Headers headers;
  8453. headers.emplace("Accept-Encoding", "gzip, deflate");
  8454. std::string body;
  8455. auto res = cli_.Get("/compress", headers,
  8456. [&](const char *data, uint64_t data_length) {
  8457. EXPECT_EQ(100U, data_length);
  8458. body.append(data, data_length);
  8459. return true;
  8460. });
  8461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8462. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8463. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8464. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8465. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8466. "7890123456789012345678901234567890",
  8467. body);
  8468. EXPECT_EQ(StatusCode::OK_200, res->status);
  8469. }
  8470. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8471. Headers headers;
  8472. headers.emplace("Accept-Encoding", "gzip, deflate");
  8473. cli_.set_decompress(false);
  8474. auto res = cli_.Get("/compress", headers);
  8475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8476. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8477. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8478. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8479. EXPECT_EQ(33U, res->body.size());
  8480. EXPECT_EQ(StatusCode::OK_200, res->status);
  8481. }
  8482. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8483. Headers headers;
  8484. headers.emplace("Accept-Encoding", "");
  8485. std::string body;
  8486. auto res = cli_.Get("/compress", headers,
  8487. [&](const char *data, uint64_t data_length) {
  8488. EXPECT_EQ(100U, data_length);
  8489. body.append(data, data_length);
  8490. return true;
  8491. });
  8492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8493. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8494. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8495. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8496. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8497. "7890123456789012345678901234567890",
  8498. body);
  8499. EXPECT_EQ(StatusCode::OK_200, res->status);
  8500. }
  8501. TEST_F(ServerTest, NoGzip) {
  8502. Headers headers;
  8503. headers.emplace("Accept-Encoding", "gzip, deflate");
  8504. auto res = cli_.Get("/nocompress", headers);
  8505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8506. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8507. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8508. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8509. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8510. "7890123456789012345678901234567890",
  8511. res->body);
  8512. EXPECT_EQ(StatusCode::OK_200, res->status);
  8513. }
  8514. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8515. Headers headers;
  8516. headers.emplace("Accept-Encoding", "gzip, deflate");
  8517. std::string body;
  8518. auto res = cli_.Get("/nocompress", headers,
  8519. [&](const char *data, uint64_t data_length) {
  8520. EXPECT_EQ(100U, data_length);
  8521. body.append(data, data_length);
  8522. return true;
  8523. });
  8524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8525. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8526. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8527. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8528. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8529. "7890123456789012345678901234567890",
  8530. body);
  8531. EXPECT_EQ(StatusCode::OK_200, res->status);
  8532. }
  8533. TEST_F(ServerTest, MultipartFormDataGzip) {
  8534. UploadFormDataItems items = {
  8535. {"key1", "test", "", ""},
  8536. {"key2", "--abcdefg123", "", ""},
  8537. };
  8538. cli_.set_compress(true);
  8539. auto res = cli_.Post("/compress-multipart", items);
  8540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8541. EXPECT_EQ(StatusCode::OK_200, res->status);
  8542. }
  8543. #endif
  8544. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8545. // Static file compression is opt-in, so these run their own server rather than
  8546. // flipping it on for the shared ServerTest fixture, which would silently
  8547. // rewrite what every other static file test is asserting.
  8548. class StaticFileCompressionTest : public ::testing::Test {
  8549. protected:
  8550. void TearDown() override {
  8551. if (t_.joinable()) {
  8552. svr_.stop();
  8553. t_.join();
  8554. }
  8555. }
  8556. int start(const std::function<void(Server &)> &configure = nullptr) {
  8557. // Serves the same tree as a directory of build-time compressed assets
  8558. // would be served: the mount point names the coding the files are already
  8559. // stored in. Registered before "/" so it is the one that matches.
  8560. svr_.set_mount_point("/pre-encoded", "./www",
  8561. {{"Content-Encoding", "gzip"}});
  8562. svr_.set_mount_point("/", "./www");
  8563. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8564. res.set_file_content("./www/dir/index.html", "text/html");
  8565. });
  8566. svr_.Get("/pre-encoded-file-content",
  8567. [](const Request & /*req*/, Response &res) {
  8568. res.set_header("Content-Encoding", "gzip");
  8569. res.set_file_content("./www/dir/index.html", "text/html");
  8570. });
  8571. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8572. res.set_content_provider(
  8573. 6, "text/plain",
  8574. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8575. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8576. return true;
  8577. });
  8578. });
  8579. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8580. res.set_content_provider(
  8581. 1000, "text/plain",
  8582. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8583. if (offset < 100) {
  8584. std::string data(100, 'A');
  8585. sink.write(data.data(), data.size());
  8586. return true;
  8587. }
  8588. std::this_thread::sleep_for(std::chrono::seconds(2));
  8589. std::string data(900, 'B');
  8590. sink.write(data.data(), data.size());
  8591. return true;
  8592. });
  8593. });
  8594. if (configure) { configure(svr_); }
  8595. auto port = svr_.bind_to_any_port(HOST);
  8596. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8597. svr_.wait_until_ready();
  8598. return port;
  8599. }
  8600. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8601. // Every file under ./www except 1MB.txt is smaller than the default
  8602. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8603. // it out of the way.
  8604. static void enable_without_floor(Server &svr) {
  8605. svr.set_static_file_compression(true);
  8606. svr.set_static_file_compression_min_length(0);
  8607. }
  8608. Server svr_;
  8609. std::thread t_;
  8610. };
  8611. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8612. auto port = start();
  8613. Client cli(HOST, port);
  8614. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8616. EXPECT_EQ(StatusCode::OK_200, res->status);
  8617. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8618. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8619. EXPECT_EQ(1048576U, res->body.size());
  8620. }
  8621. TEST_F(StaticFileCompressionTest, MountPoint) {
  8622. auto port = start(enable);
  8623. Client cli(HOST, port);
  8624. cli.set_decompress(false);
  8625. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8627. EXPECT_EQ(StatusCode::OK_200, res->status);
  8628. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8629. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8630. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8631. // The response stays self-delimiting: a length, not a chunked body.
  8632. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8633. EXPECT_EQ(std::to_string(res->body.size()),
  8634. res->get_header_value("Content-Length"));
  8635. EXPECT_LT(res->body.size(), 1048576U);
  8636. EXPECT_FALSE(res->body.empty());
  8637. }
  8638. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8639. auto port = start(enable);
  8640. Client cli(HOST, port);
  8641. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8643. EXPECT_EQ(StatusCode::OK_200, res->status);
  8644. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8645. EXPECT_EQ(1048576U, res->body.size());
  8646. }
  8647. TEST_F(StaticFileCompressionTest, FileContent) {
  8648. auto port = start(enable_without_floor);
  8649. Client cli(HOST, port);
  8650. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8652. EXPECT_EQ(StatusCode::OK_200, res->status);
  8653. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8654. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8655. EXPECT_EQ(104U, res->body.size());
  8656. }
  8657. // A handler that serves an already-encoded file names the coding itself. The
  8658. // file-backed path decided its coding from Accept-Encoding and the content
  8659. // type alone, so it compressed the stored bytes a second time and appended a
  8660. // second Content-Encoding field line.
  8661. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8662. auto port = start(enable_without_floor);
  8663. Client cli(HOST, port);
  8664. cli.set_decompress(false);
  8665. auto res = cli.Get("/pre-encoded-file-content",
  8666. Headers{{"Accept-Encoding", "gzip"}});
  8667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8668. EXPECT_EQ(StatusCode::OK_200, res->status);
  8669. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8670. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8671. // Vary belongs to a coding the server chose, and it chose none here.
  8672. EXPECT_FALSE(res->has_header("Vary"));
  8673. // The file travels exactly as it is stored on disk.
  8674. EXPECT_EQ(104U, res->body.size());
  8675. }
  8676. // The 1MB file clears the default floor, so this one runs the configuration a
  8677. // deployment would actually have.
  8678. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8679. auto port = start(enable);
  8680. Client cli(HOST, port);
  8681. cli.set_decompress(false);
  8682. auto res =
  8683. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8685. EXPECT_EQ(StatusCode::OK_200, res->status);
  8686. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8687. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8688. EXPECT_FALSE(res->has_header("Vary"));
  8689. EXPECT_EQ(1048576U, res->body.size());
  8690. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8691. }
  8692. TEST_F(StaticFileCompressionTest, Head) {
  8693. auto port = start(enable);
  8694. Client cli(HOST, port);
  8695. cli.set_decompress(false);
  8696. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8697. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8698. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8700. EXPECT_EQ(StatusCode::OK_200, res->status);
  8701. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8702. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8703. // HEAD still reports the size a GET would return.
  8704. EXPECT_EQ(get->get_header_value("Content-Length"),
  8705. res->get_header_value("Content-Length"));
  8706. EXPECT_TRUE(res->body.empty());
  8707. }
  8708. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8709. auto port = start(enable);
  8710. Client cli(HOST, port);
  8711. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8712. {"Accept-Encoding", "gzip"}});
  8713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8714. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8715. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8716. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8717. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8718. EXPECT_EQ("cd", res->body);
  8719. }
  8720. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8721. auto port = start(enable);
  8722. Client cli(HOST, port);
  8723. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8725. EXPECT_EQ(StatusCode::OK_200, res->status);
  8726. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8727. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8728. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8729. }
  8730. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8731. auto port = start(enable);
  8732. Client cli(HOST, port);
  8733. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8735. EXPECT_EQ(StatusCode::OK_200, res->status);
  8736. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8737. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8738. EXPECT_TRUE(res->body.empty());
  8739. }
  8740. TEST_F(StaticFileCompressionTest, MinLength) {
  8741. auto port = start(enable);
  8742. Client cli(HOST, port);
  8743. // 104 bytes, well under the default floor. Compressing it would add the
  8744. // gzip header and trailer to a body that already fits in one packet.
  8745. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8747. EXPECT_EQ(StatusCode::OK_200, res->status);
  8748. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8749. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8750. }
  8751. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8752. auto port = start([](Server &svr) {
  8753. svr.set_static_file_compression(true);
  8754. svr.set_static_file_compression_min_length(1);
  8755. });
  8756. Client cli(HOST, port);
  8757. cli.set_decompress(false);
  8758. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8760. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8761. // A 9-byte file comes back larger than it went in, because gzip's header and
  8762. // trailer outweigh anything deflate can save. That is the end of the range
  8763. // the floor exists to keep out.
  8764. EXPECT_GT(res->body.size(), 9U);
  8765. }
  8766. TEST_F(StaticFileCompressionTest, MaxLength) {
  8767. auto port = start([](Server &svr) {
  8768. svr.set_static_file_compression(true);
  8769. svr.set_static_file_compression_min_length(0);
  8770. svr.set_static_file_compression_max_length(1024);
  8771. });
  8772. Client cli(HOST, port);
  8773. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8774. // defines `small` as a macro on Windows.
  8775. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8776. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8777. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8778. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8779. // Under it: compressed.
  8780. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8781. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8782. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8783. }
  8784. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8785. auto port = start(enable_without_floor);
  8786. Client cli(HOST, port);
  8787. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8788. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8789. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8790. auto identity_etag = identity->get_header_value("ETag");
  8791. ASSERT_FALSE(identity_etag.empty());
  8792. auto gzipped =
  8793. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8794. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8795. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8796. auto gzip_etag = gzipped->get_header_value("ETag");
  8797. ASSERT_FALSE(gzip_etag.empty());
  8798. // Two representations, two validators.
  8799. EXPECT_NE(identity_etag, gzip_etag);
  8800. // Each one revalidates against the request that would produce it...
  8801. auto fresh =
  8802. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8803. {"If-None-Match", gzip_etag}});
  8804. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8805. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8806. auto fresh_identity =
  8807. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8808. {"If-None-Match", identity_etag}});
  8809. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8810. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8811. // ...and not against the other representation.
  8812. auto crossed =
  8813. cli.Get("/dir/index.html",
  8814. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8815. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8816. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8817. }
  8818. // The opt-in covers responses the server reads off disk itself. A caller's own
  8819. // known-length provider keeps its Content-Length and, more importantly, keeps
  8820. // delivering incrementally: routing it through a compressor would hold every
  8821. // write back until zlib's window filled.
  8822. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8823. auto port = start(enable);
  8824. Client cli(HOST, port);
  8825. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8827. EXPECT_EQ(StatusCode::OK_200, res->status);
  8828. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8829. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8830. EXPECT_EQ("aaabbb", res->body);
  8831. }
  8832. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8833. auto port = start(enable);
  8834. Client cli(HOST, port);
  8835. cli.set_read_timeout(1, 0);
  8836. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8837. Headers{{"Accept-Encoding", "gzip"}});
  8838. ASSERT_TRUE(handle.is_valid());
  8839. // The provider writes 100 bytes and then stalls for longer than the read
  8840. // timeout. Those first bytes have to arrive anyway: run the response through
  8841. // a compressor and zlib holds them until its window fills, so the read would
  8842. // come back empty instead.
  8843. char buf[256];
  8844. auto n = handle.read(buf, sizeof(buf));
  8845. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8846. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8847. }
  8848. #endif
  8849. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8850. TEST_F(ServerTest, Brotli) {
  8851. Headers headers;
  8852. headers.emplace("Accept-Encoding", "br");
  8853. auto res = cli_.Get("/compress", headers);
  8854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8855. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8856. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8857. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8858. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8859. "7890123456789012345678901234567890",
  8860. res->body);
  8861. EXPECT_EQ(StatusCode::OK_200, res->status);
  8862. }
  8863. #endif
  8864. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8865. TEST_F(ServerTest, Zstd) {
  8866. Headers headers;
  8867. headers.emplace("Accept-Encoding", "zstd");
  8868. auto res = cli_.Get("/compress", headers);
  8869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8870. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8871. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8872. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8873. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8874. "7890123456789012345678901234567890",
  8875. res->body);
  8876. EXPECT_EQ(StatusCode::OK_200, res->status);
  8877. }
  8878. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8879. Headers headers;
  8880. headers.emplace("Accept-Encoding", "");
  8881. auto res = cli_.Get("/compress", headers);
  8882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8883. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8884. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8885. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8886. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8887. "7890123456789012345678901234567890",
  8888. res->body);
  8889. EXPECT_EQ(StatusCode::OK_200, res->status);
  8890. }
  8891. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8892. Headers headers;
  8893. headers.emplace("Accept-Encoding", "zstd");
  8894. std::string body;
  8895. auto res = cli_.Get("/compress", headers,
  8896. [&](const char *data, uint64_t data_length) {
  8897. EXPECT_EQ(100U, data_length);
  8898. body.append(data, data_length);
  8899. return true;
  8900. });
  8901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8902. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8903. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8904. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8905. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8906. "7890123456789012345678901234567890",
  8907. body);
  8908. EXPECT_EQ(StatusCode::OK_200, res->status);
  8909. }
  8910. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8911. Headers headers;
  8912. headers.emplace("Accept-Encoding", "zstd");
  8913. cli_.set_decompress(false);
  8914. auto res = cli_.Get("/compress", headers);
  8915. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8916. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8917. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8918. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8920. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8921. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8922. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8923. EXPECT_EQ(StatusCode::OK_200, res->status);
  8924. ASSERT_EQ(26U, res->body.size());
  8925. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8926. 0);
  8927. }
  8928. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8929. Headers headers;
  8930. headers.emplace("Accept-Encoding", "");
  8931. std::string body;
  8932. auto res = cli_.Get("/compress", headers,
  8933. [&](const char *data, uint64_t data_length) {
  8934. EXPECT_EQ(100U, data_length);
  8935. body.append(data, data_length);
  8936. return true;
  8937. });
  8938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8939. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8940. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8941. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8942. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8943. "7890123456789012345678901234567890",
  8944. body);
  8945. EXPECT_EQ(StatusCode::OK_200, res->status);
  8946. }
  8947. TEST_F(ServerTest, NoZstd) {
  8948. Headers headers;
  8949. headers.emplace("Accept-Encoding", "zstd");
  8950. auto res = cli_.Get("/nocompress", headers);
  8951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8952. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8953. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8954. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8955. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8956. "7890123456789012345678901234567890",
  8957. res->body);
  8958. EXPECT_EQ(StatusCode::OK_200, res->status);
  8959. }
  8960. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8961. Headers headers;
  8962. headers.emplace("Accept-Encoding", "zstd");
  8963. std::string body;
  8964. auto res = cli_.Get("/nocompress", headers,
  8965. [&](const char *data, uint64_t data_length) {
  8966. EXPECT_EQ(100U, data_length);
  8967. body.append(data, data_length);
  8968. return true;
  8969. });
  8970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8971. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8972. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8973. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8974. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8975. "7890123456789012345678901234567890",
  8976. body);
  8977. EXPECT_EQ(StatusCode::OK_200, res->status);
  8978. }
  8979. // TODO: How to enable zstd ??
  8980. TEST_F(ServerTest, MultipartFormDataZstd) {
  8981. UploadFormDataItems items = {
  8982. {"key1", "test", "", ""},
  8983. {"key2", "--abcdefg123", "", ""},
  8984. };
  8985. Headers headers;
  8986. headers.emplace("Accept-Encoding", "zstd");
  8987. cli_.set_compress(true);
  8988. auto res = cli_.Post("/compress-multipart", headers, items);
  8989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8990. EXPECT_EQ(StatusCode::OK_200, res->status);
  8991. }
  8992. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8993. Headers headers;
  8994. headers.emplace("Accept-Encoding", "zstd");
  8995. cli_.set_compress(true);
  8996. auto res = cli_.Put(
  8997. "/put", headers, 3,
  8998. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8999. sink.os << "PUT";
  9000. return true;
  9001. },
  9002. "text/plain");
  9003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9004. EXPECT_EQ(StatusCode::OK_200, res->status);
  9005. EXPECT_EQ("PUT", res->body);
  9006. }
  9007. // Pre-compression logging tests
  9008. TEST_F(ServerTest, PreCompressionLogging) {
  9009. // Test data for compression (matches the actual /compress endpoint content)
  9010. const std::string test_content =
  9011. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9012. "3456789012345678901234567890";
  9013. // Variables to capture logging data
  9014. std::string pre_compression_body;
  9015. std::string pre_compression_content_type;
  9016. std::string pre_compression_content_encoding;
  9017. std::string post_compression_body;
  9018. std::string post_compression_content_type;
  9019. std::string post_compression_content_encoding;
  9020. // Set up pre-compression logger
  9021. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9022. const Response &res) {
  9023. pre_compression_body = res.body;
  9024. pre_compression_content_type = res.get_header_value("Content-Type");
  9025. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9026. });
  9027. // Set up post-compression logger
  9028. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9029. post_compression_body = res.body;
  9030. post_compression_content_type = res.get_header_value("Content-Type");
  9031. post_compression_content_encoding =
  9032. res.get_header_value("Content-Encoding");
  9033. });
  9034. // Test with gzip compression
  9035. Headers headers;
  9036. headers.emplace("Accept-Encoding", "gzip");
  9037. auto res = cli_.Get("/compress", headers);
  9038. // Verify response was compressed
  9039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9040. EXPECT_EQ(StatusCode::OK_200, res->status);
  9041. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9042. // Verify pre-compression logger captured uncompressed content
  9043. EXPECT_EQ(test_content, pre_compression_body);
  9044. EXPECT_EQ("text/plain", pre_compression_content_type);
  9045. EXPECT_TRUE(pre_compression_content_encoding
  9046. .empty()); // No encoding header before compression
  9047. // Verify post-compression logger captured compressed content
  9048. EXPECT_NE(test_content,
  9049. post_compression_body); // Should be different after compression
  9050. EXPECT_EQ("text/plain", post_compression_content_type);
  9051. EXPECT_EQ("gzip", post_compression_content_encoding);
  9052. // Verify compressed content is smaller
  9053. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9054. }
  9055. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9056. const std::string test_content =
  9057. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9058. "3456789012345678901234567890";
  9059. std::string pre_compression_body;
  9060. std::string post_compression_body;
  9061. svr_.set_pre_compression_logger(
  9062. [&](const Request & /*req*/, const Response &res) {
  9063. pre_compression_body = res.body;
  9064. });
  9065. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9066. post_compression_body = res.body;
  9067. });
  9068. Headers headers;
  9069. headers.emplace("Accept-Encoding", "br");
  9070. auto res = cli_.Get("/compress", headers);
  9071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9072. EXPECT_EQ(StatusCode::OK_200, res->status);
  9073. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9074. // Verify pre-compression content is uncompressed
  9075. EXPECT_EQ(test_content, pre_compression_body);
  9076. // Verify post-compression content is compressed
  9077. EXPECT_NE(test_content, post_compression_body);
  9078. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9079. }
  9080. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9081. const std::string test_content =
  9082. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9083. "3456789012345678901234567890";
  9084. std::string pre_compression_body;
  9085. std::string post_compression_body;
  9086. svr_.set_pre_compression_logger(
  9087. [&](const Request & /*req*/, const Response &res) {
  9088. pre_compression_body = res.body;
  9089. });
  9090. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9091. post_compression_body = res.body;
  9092. });
  9093. // Request without compression (use /nocompress endpoint)
  9094. Headers headers;
  9095. auto res = cli_.Get("/nocompress", headers);
  9096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9097. EXPECT_EQ(StatusCode::OK_200, res->status);
  9098. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9099. // Pre-compression logger should not be called when no compression is applied
  9100. EXPECT_TRUE(
  9101. pre_compression_body.empty()); // Pre-compression logger not called
  9102. EXPECT_EQ(
  9103. test_content,
  9104. post_compression_body); // Post-compression logger captures final content
  9105. }
  9106. TEST_F(ServerTest, LoggerSeesContentLength) {
  9107. size_t logged_content_length = 0;
  9108. std::string logged_content_length_header;
  9109. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9110. logged_content_length = res.content_length_;
  9111. logged_content_length_header = res.get_header_value("Content-Length");
  9112. });
  9113. auto res = cli_.Get("/nocompress");
  9114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9115. EXPECT_EQ(StatusCode::OK_200, res->status);
  9116. EXPECT_EQ(res->body.size(), logged_content_length);
  9117. EXPECT_EQ(std::to_string(logged_content_length),
  9118. logged_content_length_header);
  9119. }
  9120. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9121. const std::string test_content =
  9122. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9123. "3456789012345678901234567890";
  9124. std::string pre_compression_body;
  9125. bool pre_logger_called = false;
  9126. // Set only pre-compression logger
  9127. svr_.set_pre_compression_logger(
  9128. [&](const Request & /*req*/, const Response &res) {
  9129. pre_compression_body = res.body;
  9130. pre_logger_called = true;
  9131. });
  9132. Headers headers;
  9133. headers.emplace("Accept-Encoding", "gzip");
  9134. auto res = cli_.Get("/compress", headers);
  9135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9136. EXPECT_EQ(StatusCode::OK_200, res->status);
  9137. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9138. // Verify pre-compression logger was called
  9139. EXPECT_TRUE(pre_logger_called);
  9140. EXPECT_EQ(test_content, pre_compression_body);
  9141. }
  9142. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9143. {
  9144. // Test with Expect: 100-continue header - success case
  9145. // Server returns 100 Continue, client sends body, server returns 200 OK
  9146. Request req;
  9147. req.method = "POST";
  9148. req.path = "/post-large";
  9149. req.set_header("Expect", "100-continue");
  9150. req.body = LARGE_DATA;
  9151. Response res;
  9152. auto error = Error::Success;
  9153. cli_.set_keep_alive(true);
  9154. auto ret = cli_.send(req, res, error);
  9155. EXPECT_TRUE(ret);
  9156. EXPECT_EQ(StatusCode::OK_200, res.status);
  9157. EXPECT_EQ(LARGE_DATA, res.body);
  9158. }
  9159. {
  9160. // Test with Expect: 100-continue header - error case
  9161. // Client should not send the body when server returns an error
  9162. Request req;
  9163. req.method = "POST";
  9164. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9165. req.set_header("Expect", "100-continue");
  9166. req.body = LARGE_DATA;
  9167. Response res;
  9168. auto error = Error::Success;
  9169. auto start = std::chrono::high_resolution_clock::now();
  9170. cli_.set_keep_alive(true);
  9171. auto ret = cli_.send(req, res, error);
  9172. auto end = std::chrono::high_resolution_clock::now();
  9173. auto elapsed =
  9174. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9175. .count();
  9176. // With Expect: 100-continue, request completes successfully but with error
  9177. EXPECT_TRUE(ret);
  9178. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9179. EXPECT_EQ("close", res.get_header_value("Connection"));
  9180. EXPECT_FALSE(cli_.is_socket_open());
  9181. EXPECT_LE(elapsed, 2000);
  9182. }
  9183. {
  9184. // Send an extra GET request to ensure error recovery without hanging
  9185. Request req;
  9186. req.method = "GET";
  9187. req.path = "/hi";
  9188. auto start = std::chrono::high_resolution_clock::now();
  9189. auto res = cli_.send(req);
  9190. auto end = std::chrono::high_resolution_clock::now();
  9191. auto elapsed =
  9192. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9193. .count();
  9194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9195. EXPECT_EQ(StatusCode::OK_200, res->status);
  9196. EXPECT_EQ("Hello World!", res->body);
  9197. EXPECT_LE(elapsed, 500);
  9198. }
  9199. }
  9200. TEST(ZstdDecompressor, ChunkedDecompression) {
  9201. std::string data;
  9202. for (size_t i = 0; i < 32 * 1024; ++i) {
  9203. data.push_back(static_cast<char>('a' + i % 26));
  9204. }
  9205. std::string compressed_data;
  9206. {
  9207. httplib::detail::zstd_compressor compressor;
  9208. bool result = compressor.compress(
  9209. data.data(), data.size(),
  9210. /*last=*/true,
  9211. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9212. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9213. compressed_data_size);
  9214. return true;
  9215. });
  9216. ASSERT_TRUE(result);
  9217. }
  9218. std::string decompressed_data;
  9219. {
  9220. httplib::detail::zstd_decompressor decompressor;
  9221. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9222. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9223. size_t chunk_size = 130;
  9224. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9225. chunk_begin += chunk_size) {
  9226. size_t current_chunk_size =
  9227. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9228. bool result = decompressor.decompress(
  9229. compressed_data.data() + chunk_begin, current_chunk_size,
  9230. [&](const char *decompressed_data_chunk,
  9231. size_t decompressed_data_chunk_size) {
  9232. decompressed_data.insert(decompressed_data.size(),
  9233. decompressed_data_chunk,
  9234. decompressed_data_chunk_size);
  9235. return true;
  9236. });
  9237. ASSERT_TRUE(result);
  9238. }
  9239. }
  9240. ASSERT_EQ(data, decompressed_data);
  9241. }
  9242. TEST(ZstdDecompressor, Decompress) {
  9243. std::string original_text = "Compressed with ZSTD";
  9244. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9245. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9246. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9247. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9248. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9249. std::string decompressed_data;
  9250. {
  9251. httplib::detail::zstd_decompressor decompressor;
  9252. bool result = decompressor.decompress(
  9253. compressed_data.data(), compressed_data.size(),
  9254. [&](const char *decompressed_data_chunk,
  9255. size_t decompressed_data_chunk_size) {
  9256. decompressed_data.insert(decompressed_data.size(),
  9257. decompressed_data_chunk,
  9258. decompressed_data_chunk_size);
  9259. return true;
  9260. });
  9261. ASSERT_TRUE(result);
  9262. }
  9263. ASSERT_EQ(original_text, decompressed_data);
  9264. }
  9265. #endif
  9266. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9267. // separate chunks so that the server sees each part in its own read(). Used to
  9268. // place a read boundary at a specific offset of a request body.
  9269. static bool send_request_in_parts(time_t read_timeout_sec,
  9270. const std::vector<std::string> &parts,
  9271. std::string *resp = nullptr,
  9272. int port = PORT) {
  9273. auto error = Error::Success;
  9274. auto client_sock = detail::create_client_socket(
  9275. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9276. /*connection_timeout_sec=*/5, 0,
  9277. /*read_timeout_sec=*/5, 0,
  9278. /*write_timeout_sec=*/5, 0, std::string(), error);
  9279. if (client_sock == INVALID_SOCKET) { return false; }
  9280. auto ret = detail::process_client_socket(
  9281. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9282. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9283. for (size_t i = 0; i < parts.size(); i++) {
  9284. const auto &part = parts[i];
  9285. if (part.size() !=
  9286. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9287. return false;
  9288. }
  9289. if (i + 1 < parts.size()) {
  9290. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9291. }
  9292. }
  9293. char buf[512];
  9294. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9295. while (line_reader.getline()) {
  9296. if (resp) { *resp += line_reader.ptr(); }
  9297. }
  9298. return true;
  9299. });
  9300. detail::close_socket(client_sock);
  9301. return ret;
  9302. }
  9303. // Sends a raw request to a server listening at HOST:PORT.
  9304. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9305. std::string *resp = nullptr, int port = PORT) {
  9306. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9307. }
  9308. #ifdef CPPHTTPLIB_SSL_ENABLED
  9309. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9310. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9311. ASSERT_TRUE(svr.is_valid());
  9312. svr.set_read_timeout(1, 0);
  9313. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9314. auto se = detail::scope_exit([&] {
  9315. svr.stop();
  9316. t.join();
  9317. ASSERT_FALSE(svr.is_running());
  9318. });
  9319. svr.wait_until_ready();
  9320. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9321. // keeps each wait well within the read timeout. The server gives up a
  9322. // second in, so the bytes sent after that fail.
  9323. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9324. parts.resize(26, std::string(1, '\0'));
  9325. EXPECT_FALSE(send_request_in_parts(5, parts));
  9326. }
  9327. #endif
  9328. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9329. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9330. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9331. const std::vector<std::string> &parts,
  9332. std::string *resp = nullptr,
  9333. int port = PORT) {
  9334. auto error = Error::Success;
  9335. auto sock = detail::create_client_socket(
  9336. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9337. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9338. /*write_timeout_sec=*/5, 0, std::string(), error);
  9339. if (sock == INVALID_SOCKET) { return false; }
  9340. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9341. auto ctx = SSL_CTX_new(TLS_client_method());
  9342. auto ssl = SSL_new(ctx);
  9343. auto ssl_se = detail::scope_exit([&] {
  9344. SSL_free(ssl);
  9345. SSL_CTX_free(ctx);
  9346. });
  9347. SSL_set_fd(ssl, static_cast<int>(sock));
  9348. if (SSL_connect(ssl) != 1) { return false; }
  9349. for (size_t i = 0; i < parts.size(); i++) {
  9350. const auto &part = parts[i];
  9351. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9352. static_cast<int>(part.size())) {
  9353. return false;
  9354. }
  9355. if (i + 1 < parts.size()) {
  9356. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9357. }
  9358. }
  9359. char buf[512];
  9360. int n;
  9361. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9362. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9363. }
  9364. return true;
  9365. }
  9366. #endif
  9367. // The request line, then a header value a byte at a time.
  9368. static std::vector<std::string> slow_request_head_parts() {
  9369. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9370. parts.resize(26, "a");
  9371. parts.emplace_back("\r\n\r\n");
  9372. return parts;
  9373. }
  9374. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9375. // within the one-second read timeout. The server gives up a second in, before
  9376. // the head is complete.
  9377. static void
  9378. expect_slow_request_head_dropped(Server &svr,
  9379. const std::function<std::string()> &send) {
  9380. std::atomic<bool> handled(false);
  9381. svr.Get("/", [&](const Request &, Response &res) {
  9382. handled = true;
  9383. res.set_content("ok", "text/plain");
  9384. });
  9385. svr.set_read_timeout(1, 0);
  9386. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9387. auto se = detail::scope_exit([&] {
  9388. svr.stop();
  9389. t.join();
  9390. ASSERT_FALSE(svr.is_running());
  9391. });
  9392. svr.wait_until_ready();
  9393. auto resp = send();
  9394. EXPECT_FALSE(handled);
  9395. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9396. }
  9397. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9398. Server svr;
  9399. expect_slow_request_head_dropped(svr, [] {
  9400. std::string resp;
  9401. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9402. return resp;
  9403. });
  9404. }
  9405. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9406. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9407. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9408. ASSERT_TRUE(svr.is_valid());
  9409. expect_slow_request_head_dropped(svr, [] {
  9410. std::string resp;
  9411. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9412. return resp;
  9413. });
  9414. }
  9415. #endif
  9416. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9417. Server svr;
  9418. std::string header_value;
  9419. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9420. header_value = req.get_header_value("foo");
  9421. res.set_content("ok", "text/plain");
  9422. });
  9423. thread t = thread([&] { svr.listen(HOST, PORT); });
  9424. auto se = detail::scope_exit([&] {
  9425. svr.stop();
  9426. t.join();
  9427. ASSERT_FALSE(svr.is_running());
  9428. });
  9429. svr.wait_until_ready();
  9430. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9431. // like characters are not treated the same - use vertical tab and escape.
  9432. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9433. "foo: \t \v bar \x1B\t \r\n"
  9434. "Connection: close\r\n"
  9435. "\r\n";
  9436. std::string res;
  9437. ASSERT_TRUE(send_request(5, req, &res));
  9438. EXPECT_EQ(header_value, "");
  9439. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9440. }
  9441. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9442. Server svr;
  9443. std::string received;
  9444. svr.Get("/order", [&](const Request &req, Response &res) {
  9445. received = entries_to_string(req.headers);
  9446. res.set_content("ok", "text/plain");
  9447. });
  9448. auto port = svr.bind_to_any_port(HOST);
  9449. thread t = thread([&] { svr.listen_after_bind(); });
  9450. auto se = detail::scope_exit([&] {
  9451. svr.stop();
  9452. t.join();
  9453. ASSERT_FALSE(svr.is_running());
  9454. });
  9455. svr.wait_until_ready();
  9456. const std::string req = "GET /order HTTP/1.1\r\n"
  9457. "Host: localhost\r\n"
  9458. "X-First: 1\r\n"
  9459. "X-Dup: a\r\n"
  9460. "X-Second: 2\r\n"
  9461. "X-Dup: b\r\n"
  9462. "Connection: close\r\n"
  9463. "\r\n";
  9464. std::string res;
  9465. ASSERT_TRUE(send_request(5, req, &res, port));
  9466. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9467. EXPECT_EQ(
  9468. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9469. received);
  9470. }
  9471. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9472. Server svr;
  9473. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9474. res.set_header("Set-Cookie", "first=1");
  9475. res.set_header("X-Between", "y");
  9476. res.set_header("Set-Cookie", "second=2");
  9477. res.set_content("ok", "text/plain");
  9478. });
  9479. auto port = svr.bind_to_any_port(HOST);
  9480. thread t = thread([&] { svr.listen_after_bind(); });
  9481. auto se = detail::scope_exit([&] {
  9482. svr.stop();
  9483. t.join();
  9484. ASSERT_FALSE(svr.is_running());
  9485. });
  9486. svr.wait_until_ready();
  9487. Client cli(HOST, port);
  9488. auto res = cli.Get("/cookies");
  9489. ASSERT_TRUE(res);
  9490. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9491. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9492. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9493. }
  9494. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9495. Server svr;
  9496. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9497. auto i = new int(0);
  9498. res.set_header("Trailer", "X-Safe, X-Reflected");
  9499. res.set_chunked_content_provider(
  9500. "text/plain",
  9501. [i](size_t /*offset*/, DataSink &sink) {
  9502. if (*i == 0) {
  9503. sink.os << "body";
  9504. } else {
  9505. Headers trailer;
  9506. // A valid trailer that must survive.
  9507. trailer.emplace("X-Safe", "safe");
  9508. // Attacker-controlled value carrying CR/LF (response splitting).
  9509. trailer.emplace("X-Reflected",
  9510. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9511. // Attacker-controlled name carrying CR/LF.
  9512. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9513. sink.done_with_trailer(trailer);
  9514. }
  9515. (*i)++;
  9516. return true;
  9517. },
  9518. [i](bool /*success*/) { delete i; });
  9519. });
  9520. thread t = thread([&] { svr.listen(HOST, PORT); });
  9521. auto se = detail::scope_exit([&] {
  9522. svr.stop();
  9523. t.join();
  9524. ASSERT_FALSE(svr.is_running());
  9525. });
  9526. svr.wait_until_ready();
  9527. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9528. "Host: " + HOST +
  9529. "\r\n"
  9530. "Connection: close\r\n"
  9531. "\r\n";
  9532. std::string res;
  9533. ASSERT_TRUE(send_request(5, req, &res));
  9534. // The injected fields must not appear anywhere in the raw response.
  9535. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9536. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9537. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9538. // Invalid trailers are dropped entirely, matching set_header().
  9539. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9540. // The valid trailer still passes through.
  9541. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9542. }
  9543. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9544. Server svr;
  9545. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9546. // res.headers is a public field an application can populate directly,
  9547. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9548. // A valid header that must survive.
  9549. res.headers.emplace("X-Safe", "safe");
  9550. // Attacker-controlled value carrying CR/LF (response splitting).
  9551. res.headers.emplace("X-Reflected",
  9552. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9553. // Attacker-controlled name carrying CR/LF.
  9554. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9555. res.set_content("body", "text/plain");
  9556. });
  9557. thread t = thread([&] { svr.listen(HOST, PORT); });
  9558. auto se = detail::scope_exit([&] {
  9559. svr.stop();
  9560. t.join();
  9561. ASSERT_FALSE(svr.is_running());
  9562. });
  9563. svr.wait_until_ready();
  9564. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9565. "Host: " + HOST +
  9566. "\r\n"
  9567. "Connection: close\r\n"
  9568. "\r\n";
  9569. std::string res;
  9570. ASSERT_TRUE(send_request(5, req, &res));
  9571. // The injected fields must not appear anywhere in the raw response.
  9572. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9573. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9574. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9575. // Invalid headers are dropped entirely, matching set_header().
  9576. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9577. // The valid header still passes through.
  9578. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9579. }
  9580. // Forward declaration: in split builds split.py strips `inline` and moves the
  9581. // definition into httplib.cc, so detail::write_request_line is not visible from
  9582. // the public httplib.h. Re-declaring it here lets the tests link against the
  9583. // symbol in both header-only and split builds.
  9584. namespace httplib {
  9585. namespace detail {
  9586. ssize_t write_request_line(Stream &strm, const std::string &method,
  9587. const std::string &path);
  9588. } // namespace detail
  9589. } // namespace httplib
  9590. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9591. // A well-formed target is written verbatim.
  9592. {
  9593. detail::BufferStream strm;
  9594. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9595. EXPECT_GT(n, 0);
  9596. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9597. }
  9598. // A target carrying CR/LF, SP or other control octets must be rejected
  9599. // before anything reaches the wire, otherwise it splits the request line and
  9600. // injects a header or a whole request.
  9601. const std::string evil_targets[] = {
  9602. "/a\r\nInjected: pwned",
  9603. "/a\rInjected",
  9604. "/a\nInjected",
  9605. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9606. "/a b",
  9607. "/a\tb",
  9608. "/a\x7f",
  9609. };
  9610. for (const auto &evil : evil_targets) {
  9611. detail::BufferStream strm;
  9612. auto n = detail::write_request_line(strm, "GET", evil);
  9613. EXPECT_LT(n, 0);
  9614. EXPECT_TRUE(strm.get_buffer().empty());
  9615. }
  9616. }
  9617. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9618. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9619. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9620. // target reaches write_request. The client must fail cleanly with
  9621. // Error::Write instead of putting a request-line-less, header-injecting
  9622. // request on the wire.
  9623. Server svr;
  9624. svr.Get("/a", [](const Request &, Response &res) {
  9625. res.set_content("ok", "text/plain");
  9626. });
  9627. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9628. auto se = detail::scope_exit([&] {
  9629. svr.stop();
  9630. thread.join();
  9631. ASSERT_FALSE(svr.is_running());
  9632. });
  9633. svr.wait_until_ready();
  9634. {
  9635. Client cli(HOST, PORT);
  9636. cli.set_path_encode(false);
  9637. // The request is rejected before anything is written, so the connection
  9638. // stays silent and the subsequent response read would otherwise block for
  9639. // the full default read timeout. Shorten it -- the assertion is on the
  9640. // error, not the timeout.
  9641. cli.set_read_timeout(1, 0);
  9642. auto res = cli.Get("/a\r\nInjected: pwned");
  9643. EXPECT_FALSE(res);
  9644. EXPECT_EQ(Error::Write, res.error());
  9645. }
  9646. }
  9647. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9648. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9649. // including extension methods.
  9650. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9651. for (const auto &method : good_methods) {
  9652. detail::BufferStream strm;
  9653. auto n = detail::write_request_line(strm, method, "/");
  9654. EXPECT_GT(n, 0);
  9655. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9656. }
  9657. // A method carrying CR/LF would split the request line and smuggle a whole
  9658. // request ahead of the real one. A space or an empty method corrupts the
  9659. // request line. All must be rejected before anything reaches the wire.
  9660. const std::string evil_methods[] = {
  9661. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9662. "GET\r\nInjected: pwned",
  9663. "GET\r",
  9664. "GET\n",
  9665. "GE T",
  9666. "",
  9667. };
  9668. for (const auto &evil : evil_methods) {
  9669. detail::BufferStream strm;
  9670. auto n = detail::write_request_line(strm, evil, "/");
  9671. EXPECT_LT(n, 0);
  9672. EXPECT_TRUE(strm.get_buffer().empty());
  9673. }
  9674. }
  9675. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9676. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9677. // through Client::send must fail with Error::Write and no request, neither
  9678. // the smuggled one nor the real one, may reach the server.
  9679. Server svr;
  9680. std::atomic<int> request_count(0);
  9681. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9682. request_count++;
  9683. res.status = StatusCode::OK_200;
  9684. return Server::HandlerResponse::Handled;
  9685. });
  9686. auto port = svr.bind_to_any_port(HOST);
  9687. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9688. auto se = detail::scope_exit([&] {
  9689. svr.stop();
  9690. thread.join();
  9691. ASSERT_FALSE(svr.is_running());
  9692. });
  9693. svr.wait_until_ready();
  9694. {
  9695. Client cli(HOST, port);
  9696. const std::string evil_methods[] = {
  9697. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9698. "GE T",
  9699. "",
  9700. };
  9701. for (const auto &evil : evil_methods) {
  9702. Request req;
  9703. req.method = evil;
  9704. req.path = "/";
  9705. auto res = cli.send(req);
  9706. EXPECT_FALSE(res);
  9707. EXPECT_EQ(Error::Write, res.error());
  9708. }
  9709. auto handle =
  9710. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9711. EXPECT_FALSE(handle.is_valid());
  9712. EXPECT_EQ(Error::Write, handle.error);
  9713. // A valid request on the same client still goes through.
  9714. auto res = cli.Get("/");
  9715. ASSERT_TRUE(res);
  9716. EXPECT_EQ(StatusCode::OK_200, res->status);
  9717. }
  9718. EXPECT_EQ(1, request_count.load());
  9719. }
  9720. // Sends a raw request and verifies that there isn't a crash or exception.
  9721. static void test_raw_request(const std::string &req,
  9722. std::string *out = nullptr) {
  9723. Server svr;
  9724. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9725. res.set_content("ok", "text/plain");
  9726. });
  9727. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9728. res.set_content("ok", "text/plain");
  9729. });
  9730. svr.Get("/header_field_value_check",
  9731. [&](const Request & /*req*/, Response &res) {
  9732. res.set_content("ok", "text/plain");
  9733. });
  9734. svr.CustomRoute("PROPFIND", "/dav",
  9735. [&](const Request & /*req*/, Response &res) {
  9736. res.status = StatusCode::MultiStatus_207;
  9737. });
  9738. // Server read timeout must be longer than the client read timeout for the
  9739. // bug to reproduce, probably to force the server to process a request
  9740. // without a trailing blank line.
  9741. const time_t client_read_timeout_sec = 1;
  9742. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9743. bool listen_thread_ok = false;
  9744. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9745. auto se = detail::scope_exit([&] {
  9746. svr.stop();
  9747. t.join();
  9748. ASSERT_FALSE(svr.is_running());
  9749. EXPECT_TRUE(listen_thread_ok);
  9750. });
  9751. svr.wait_until_ready();
  9752. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9753. }
  9754. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9755. // A certain header line causes an exception if the header property is parsed
  9756. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9757. test_raw_request(
  9758. "GET /hi HTTP/1.1\r\n"
  9759. " : "
  9760. " "
  9761. " ");
  9762. }
  9763. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9764. // A certain header line causes an exception if the header property *name* is
  9765. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9766. // greedy matcher and requires backtracking when there are a lot of ":"
  9767. // characters.
  9768. // This occurs with libc++ but not libstdc++.
  9769. test_raw_request(
  9770. "GET /hi HTTP/1.1\r\n"
  9771. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9772. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9773. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9774. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9775. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9776. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9777. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9778. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9779. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9780. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9781. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9782. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9783. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9784. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9785. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9786. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9787. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9788. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9789. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9790. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9791. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9792. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9793. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9794. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9795. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9796. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9797. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9798. "&&&%%%");
  9799. }
  9800. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9801. // Make sure this doesn't crash the server.
  9802. // In a previous version of the header line regex, the "\r" rendered the line
  9803. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9804. // a new position where the leading white space ended and the field value
  9805. // began.
  9806. // The crash occurs with libc++ but not libstdc++.
  9807. test_raw_request("GET /hi HTTP/1.1\r\n"
  9808. "a:" +
  9809. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9810. "\r\n"
  9811. "\r\n");
  9812. }
  9813. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9814. const char *rejected[] = {
  9815. // RFC 9112 §3: one SP between the parts, and nothing else
  9816. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9817. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9818. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9819. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9820. // A request-target has no fragment
  9821. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9822. // An HTTP/1.1 request needs a Host
  9823. "GET /hi HTTP/1.1\r\n\r\n",
  9824. };
  9825. for (auto request : rejected) {
  9826. std::string out;
  9827. test_raw_request(request, &out);
  9828. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9829. }
  9830. std::string out;
  9831. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9832. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9833. }
  9834. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9835. // RFC 9112 §6.1
  9836. const char *requests[] = {
  9837. "PUT /put_hi HTTP/1.1\r\n"
  9838. "Host: localhost\r\n"
  9839. "Content-Length: 0\r\n"
  9840. "Transfer-Encoding: chunked\r\n"
  9841. "\r\n"
  9842. "0\r\n\r\n",
  9843. "PUT /put_hi HTTP/1.0\r\n"
  9844. "Connection: keep-alive\r\n"
  9845. "Transfer-Encoding: chunked\r\n"
  9846. "\r\n"
  9847. "0\r\n\r\n",
  9848. };
  9849. for (auto request : requests) {
  9850. std::string out;
  9851. test_raw_request(request, &out);
  9852. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9853. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9854. }
  9855. }
  9856. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9857. std::string out;
  9858. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9859. "Content-Type: text/plain\r\n"
  9860. "Transfer-Encoding: chunked\r\n"
  9861. "\r\n"
  9862. "nothex\r\n",
  9863. &out);
  9864. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9865. }
  9866. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9867. std::string out;
  9868. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9869. "Content-Type: text/plain\r\n"
  9870. "Transfer-Encoding: chunked\r\n"
  9871. "\r\n"
  9872. "3\r\n"
  9873. "xyz\r\n"
  9874. "NaN\r\n",
  9875. &out);
  9876. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9877. }
  9878. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9879. std::string out;
  9880. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9881. "Content-Type: text/plain\r\n"
  9882. "Transfer-Encoding: chunked\r\n"
  9883. "\r\n"
  9884. // Length is too large for 64 bits.
  9885. "1ffffffffffffffff\r\n"
  9886. "xyz\r\n",
  9887. &out);
  9888. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9889. }
  9890. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9891. test_raw_request("GET /hi HTTP/1.1\r\n"
  9892. "Content-Type: text/plain\r\n\r");
  9893. }
  9894. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9895. std::string out;
  9896. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9897. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9898. }
  9899. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9900. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9901. std::string out;
  9902. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9903. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9904. }
  9905. }
  9906. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9907. std::string out;
  9908. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9909. "Host: localhost\r\n"
  9910. "Connection: close\r\n\r\n",
  9911. &out);
  9912. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9913. }
  9914. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9915. Server svr;
  9916. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9917. EXPECT_TRUE(!req.remote_addr.empty());
  9918. });
  9919. thread t = thread([&] { svr.listen(HOST, PORT); });
  9920. auto se = detail::scope_exit([&] {
  9921. svr.stop();
  9922. t.join();
  9923. ASSERT_FALSE(svr.is_running());
  9924. });
  9925. svr.wait_until_ready();
  9926. // Send an invalid request line to trigger Bad Request
  9927. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9928. std::string out;
  9929. ASSERT_TRUE(send_request(5, bad_req, &out));
  9930. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9931. }
  9932. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9933. // answered right away rather than blocking on a read that waits for EOF.
  9934. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9935. std::string out;
  9936. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9937. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9938. }
  9939. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9940. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9941. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9942. for (const auto *method : methods) {
  9943. Server svr;
  9944. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9945. EXPECT_FALSE(svr.is_valid()) << method;
  9946. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9947. }
  9948. }
  9949. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9950. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9951. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9952. for (const auto *method : methods) {
  9953. Server svr;
  9954. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9955. EXPECT_FALSE(svr.is_valid()) << method;
  9956. }
  9957. }
  9958. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9959. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9960. "COPY", "MOVE", "LOCK",
  9961. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9962. Server svr;
  9963. for (const auto *method : methods) {
  9964. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9965. }
  9966. EXPECT_TRUE(svr.is_valid());
  9967. }
  9968. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9969. Server svr;
  9970. svr.CustomRoute("POST", "/x",
  9971. [](const Request &, Response &, const ContentReader &) {});
  9972. EXPECT_FALSE(svr.is_valid());
  9973. }
  9974. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9975. Server svr;
  9976. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9977. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9978. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9979. EXPECT_FALSE(svr.is_valid());
  9980. }
  9981. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9982. Server svr;
  9983. auto captured = Error::Success;
  9984. svr.set_error_logger(
  9985. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9986. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9987. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9988. }
  9989. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9990. std::string out;
  9991. std::string request(
  9992. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9993. test_raw_request(request, &out);
  9994. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9995. }
  9996. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9997. std::string out;
  9998. std::string request(
  9999. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10000. test_raw_request(request, &out);
  10001. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10002. }
  10003. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10004. std::string out;
  10005. std::string request(
  10006. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10007. test_raw_request(request, &out);
  10008. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10009. }
  10010. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10011. std::string out;
  10012. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10013. "Host: localhost\r\n"
  10014. "Test: \r\n\r\n",
  10015. &out);
  10016. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10017. }
  10018. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10019. Server svr;
  10020. std::string x_custom;
  10021. std::string cookie;
  10022. std::string xff;
  10023. std::string x_unicode;
  10024. std::string x_iis;
  10025. svr.Get("/check", [&](const Request &req, Response &res) {
  10026. x_custom = req.get_header_value("X-Custom");
  10027. cookie = req.get_header_value("Cookie");
  10028. xff = req.get_header_value("X-Forwarded-For");
  10029. x_unicode = req.get_header_value("X-Unicode");
  10030. x_iis = req.get_header_value("X-IIS");
  10031. res.set_content("ok", "text/plain");
  10032. });
  10033. thread t = thread([&] { svr.listen(HOST, PORT); });
  10034. auto se = detail::scope_exit([&] {
  10035. svr.stop();
  10036. t.join();
  10037. ASSERT_FALSE(svr.is_running());
  10038. });
  10039. svr.wait_until_ready();
  10040. const std::string req = "GET /check HTTP/1.1\r\n"
  10041. "Host: localhost\r\n"
  10042. "X-Custom: a%0D%0AInjected: b\r\n"
  10043. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10044. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10045. "X-Unicode: %E3%81%82\r\n"
  10046. "X-IIS: %u00E9\r\n"
  10047. "Connection: close\r\n"
  10048. "\r\n";
  10049. std::string res;
  10050. ASSERT_TRUE(send_request(5, req, &res));
  10051. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10052. // Every value must be returned verbatim (wire form), with no decoding.
  10053. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10054. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10055. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10056. EXPECT_EQ("%E3%81%82", x_unicode);
  10057. EXPECT_EQ("%u00E9", x_iis);
  10058. }
  10059. // Applications that previously relied on automatic percent-decoding can
  10060. // reproduce the old behavior by explicitly calling decode_path_component()
  10061. // or, for RFC 3986 conformance, decode_uri_component().
  10062. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10063. Server svr;
  10064. std::string decoded;
  10065. svr.Get("/check", [&](const Request &req, Response &res) {
  10066. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10067. res.set_content("ok", "text/plain");
  10068. });
  10069. thread t = thread([&] { svr.listen(HOST, PORT); });
  10070. auto se = detail::scope_exit([&] {
  10071. svr.stop();
  10072. t.join();
  10073. ASSERT_FALSE(svr.is_running());
  10074. });
  10075. svr.wait_until_ready();
  10076. const std::string req = "GET /check HTTP/1.1\r\n"
  10077. "Host: localhost\r\n"
  10078. "X-Custom: hello%20world\r\n"
  10079. "Connection: close\r\n"
  10080. "\r\n";
  10081. std::string res;
  10082. ASSERT_TRUE(send_request(5, req, &res));
  10083. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10084. EXPECT_EQ("hello world", decoded);
  10085. }
  10086. // Regression test for #2033. Browsers send Referer values that include
  10087. // percent-encoded characters such as %0A inside the URL. Decoding the
  10088. // header value would either trip the post-decode CR/LF/NUL guard (the
  10089. // original bug, returning 400) or, after that guard was relaxed, silently
  10090. // store a literal LF — both unacceptable. The wire form must round-trip.
  10091. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10092. Server svr;
  10093. std::string referer;
  10094. svr.Get("/check", [&](const Request &req, Response &res) {
  10095. referer = req.get_header_value("Referer");
  10096. res.set_content("ok", "text/plain");
  10097. });
  10098. thread t = thread([&] { svr.listen(HOST, PORT); });
  10099. auto se = detail::scope_exit([&] {
  10100. svr.stop();
  10101. t.join();
  10102. ASSERT_FALSE(svr.is_running());
  10103. });
  10104. svr.wait_until_ready();
  10105. const std::string req = "GET /check HTTP/1.1\r\n"
  10106. "Host: localhost\r\n"
  10107. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10108. "Connection: close\r\n"
  10109. "\r\n";
  10110. std::string res;
  10111. ASSERT_TRUE(send_request(5, req, &res));
  10112. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10113. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10114. }
  10115. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10116. Server svr;
  10117. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10118. res.set_header("Cache-Control", "no-cache");
  10119. res.set_chunked_content_provider(
  10120. "text/event-stream", [](size_t offset, DataSink &sink) {
  10121. std::string s = "data:";
  10122. s += std::to_string(offset);
  10123. s += "\n\n";
  10124. auto ret = sink.write(s.data(), s.size());
  10125. EXPECT_TRUE(ret);
  10126. std::this_thread::sleep_for(std::chrono::seconds(1));
  10127. return true;
  10128. });
  10129. });
  10130. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10131. svr.wait_until_ready();
  10132. Client client(HOST, PORT);
  10133. const Headers headers = {{"Accept", "text/event-stream"}};
  10134. auto get_thread = std::thread([&client, &headers]() {
  10135. auto res = client.Get(
  10136. "/events", headers,
  10137. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10138. });
  10139. auto se = detail::scope_exit([&] {
  10140. svr.stop();
  10141. get_thread.join();
  10142. listen_thread.join();
  10143. ASSERT_FALSE(svr.is_running());
  10144. });
  10145. // Give GET time to get a few messages.
  10146. std::this_thread::sleep_for(std::chrono::seconds(2));
  10147. }
  10148. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10149. httplib::Server svr;
  10150. svr.Post("/hi",
  10151. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10152. res.status = StatusCode::OK_200;
  10153. });
  10154. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10155. svr.wait_until_ready();
  10156. Client cli(HOST, PORT);
  10157. auto res = cli.Post("/hi", "data", "text/plain");
  10158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10159. EXPECT_EQ(StatusCode::OK_200, res->status);
  10160. svr.stop();
  10161. thread.join();
  10162. ASSERT_FALSE(svr.is_running());
  10163. res = cli.Post("/hi", "data", "text/plain");
  10164. ASSERT_FALSE(res);
  10165. }
  10166. TEST(ServerStopTest, ListenFailure) {
  10167. Server svr;
  10168. auto t = thread([&]() {
  10169. auto ret = svr.listen("????", PORT);
  10170. EXPECT_FALSE(ret);
  10171. });
  10172. svr.wait_until_ready();
  10173. svr.stop();
  10174. t.join();
  10175. }
  10176. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10177. TEST(ServerStopTest, Decommision) {
  10178. Server svr;
  10179. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10180. for (int i = 0; i < 4; i++) {
  10181. auto is_even = !(i % 2);
  10182. std::thread t{[&] {
  10183. try {
  10184. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10185. if (is_even) {
  10186. throw std::runtime_error("Some thing that happens to go wrong.");
  10187. }
  10188. svr.listen(HOST, PORT);
  10189. } catch (...) { svr.decommission(); }
  10190. }};
  10191. svr.wait_until_ready();
  10192. // Server is up
  10193. {
  10194. Client cli(HOST, PORT);
  10195. auto res = cli.Get("/hi");
  10196. if (is_even) {
  10197. EXPECT_FALSE(res);
  10198. } else {
  10199. EXPECT_TRUE(res);
  10200. EXPECT_EQ("hi...", res->body);
  10201. }
  10202. }
  10203. svr.stop();
  10204. t.join();
  10205. // Server is down...
  10206. {
  10207. Client cli(HOST, PORT);
  10208. auto res = cli.Get("/hi");
  10209. EXPECT_FALSE(res);
  10210. }
  10211. }
  10212. }
  10213. #endif
  10214. // Helper function for string body upload progress tests
  10215. template <typename SetupHandler, typename ClientCall>
  10216. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10217. ClientCall &&client_call,
  10218. const string &body) {
  10219. Server svr;
  10220. setup_handler(svr);
  10221. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10222. auto se = detail::scope_exit([&] {
  10223. svr.stop();
  10224. t.join();
  10225. });
  10226. svr.wait_until_ready();
  10227. Client cli(HOST, PORT);
  10228. vector<uint64_t> progress_values;
  10229. bool progress_called = false;
  10230. auto res =
  10231. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10232. progress_values.push_back(current);
  10233. progress_called = true;
  10234. return true;
  10235. });
  10236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10237. EXPECT_EQ(200, res->status);
  10238. EXPECT_TRUE(progress_called);
  10239. }
  10240. TEST(UploadProgressTest, PostStringBodyBasic) {
  10241. TestStringBodyUploadProgress(
  10242. [](Server &svr) {
  10243. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10244. res.set_content("received", "text/plain");
  10245. });
  10246. },
  10247. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10248. return cli.Post("/test", body, "text/plain", progress_callback);
  10249. },
  10250. "test data for upload progress");
  10251. }
  10252. TEST(UploadProgressTest, PutStringBodyBasic) {
  10253. TestStringBodyUploadProgress(
  10254. [](Server &svr) {
  10255. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10256. res.set_content("put received", "text/plain");
  10257. });
  10258. },
  10259. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10260. return cli.Put("/test", body, "text/plain", progress_callback);
  10261. },
  10262. "put test data for upload progress");
  10263. }
  10264. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10265. TestStringBodyUploadProgress(
  10266. [](Server &svr) {
  10267. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10268. res.set_content("patch received", "text/plain");
  10269. });
  10270. },
  10271. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10272. return cli.Patch("/test", body, "text/plain", progress_callback);
  10273. },
  10274. "patch test data for upload progress");
  10275. }
  10276. // Helper function for content provider upload progress tests
  10277. template <typename SetupHandler, typename ClientCall>
  10278. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10279. ClientCall &&client_call) {
  10280. Server svr;
  10281. setup_handler(svr);
  10282. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10283. auto se = detail::scope_exit([&] {
  10284. svr.stop();
  10285. t.join();
  10286. });
  10287. svr.wait_until_ready();
  10288. Client cli(HOST, PORT);
  10289. vector<uint64_t> progress_values;
  10290. auto res =
  10291. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10292. progress_values.push_back(current);
  10293. return true;
  10294. });
  10295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10296. EXPECT_EQ(200, res->status);
  10297. EXPECT_FALSE(progress_values.empty());
  10298. }
  10299. TEST(UploadProgressTest, PostContentProviderProgress) {
  10300. TestContentProviderUploadProgress(
  10301. [](Server &svr) {
  10302. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10303. res.set_content("provider received", "text/plain");
  10304. });
  10305. },
  10306. [](Client &cli, UploadProgress progress_callback) {
  10307. return cli.Post(
  10308. "/test", 9,
  10309. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10310. sink.os << "test data";
  10311. return true;
  10312. },
  10313. "text/plain", progress_callback);
  10314. });
  10315. }
  10316. // Helper function for multipart upload progress tests
  10317. template <typename SetupHandler, typename ClientCall>
  10318. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10319. ClientCall &&client_call,
  10320. const string &endpoint) {
  10321. Server svr;
  10322. setup_handler(svr);
  10323. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10324. auto se = detail::scope_exit([&] {
  10325. svr.stop();
  10326. t.join();
  10327. });
  10328. svr.wait_until_ready();
  10329. Client cli(HOST, PORT);
  10330. vector<uint64_t> progress_values;
  10331. UploadFormDataItems items = {
  10332. {"field1", "value1", "", ""},
  10333. {"field2", "longer value for progress tracking test", "", ""},
  10334. {"file1", "file content data for upload progress", "test.txt",
  10335. "text/plain"}};
  10336. auto res = client_call(cli, endpoint, items,
  10337. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10338. progress_values.push_back(current);
  10339. return true;
  10340. });
  10341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10342. EXPECT_EQ(200, res->status);
  10343. EXPECT_FALSE(progress_values.empty());
  10344. }
  10345. TEST(UploadProgressTest, PostMultipartProgress) {
  10346. TestMultipartUploadProgress(
  10347. [](Server &svr) {
  10348. svr.Post("/multipart", [](const Request &req, Response &res) {
  10349. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10350. res.set_content("multipart received", "text/plain");
  10351. });
  10352. },
  10353. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10354. UploadProgress progress_callback) {
  10355. return cli.Post(endpoint, items, progress_callback);
  10356. },
  10357. "/multipart");
  10358. }
  10359. // Helper function for basic download progress tests
  10360. template <typename SetupHandler, typename ClientCall>
  10361. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10362. ClientCall &&client_call, const string &endpoint,
  10363. size_t expected_content_size) {
  10364. Server svr;
  10365. setup_handler(svr);
  10366. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10367. auto se = detail::scope_exit([&] {
  10368. svr.stop();
  10369. t.join();
  10370. });
  10371. svr.wait_until_ready();
  10372. Client cli(HOST, PORT);
  10373. vector<uint64_t> progress_values;
  10374. auto res = client_call(cli, endpoint,
  10375. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10376. progress_values.push_back(current);
  10377. return true;
  10378. });
  10379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10380. EXPECT_EQ(200, res->status);
  10381. EXPECT_FALSE(progress_values.empty());
  10382. EXPECT_EQ(expected_content_size, res->body.size());
  10383. }
  10384. TEST(DownloadProgressTest, GetBasic) {
  10385. TestBasicDownloadProgress(
  10386. [](Server &svr) {
  10387. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10388. string content(1000, 'D');
  10389. res.set_content(content, "text/plain");
  10390. });
  10391. },
  10392. [](Client &cli, const string &endpoint,
  10393. DownloadProgress progress_callback) {
  10394. return cli.Get(endpoint, progress_callback);
  10395. },
  10396. "/download", 1000u);
  10397. }
  10398. // Helper function for content receiver download progress tests
  10399. template <typename SetupHandler, typename ClientCall>
  10400. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10401. ClientCall &&client_call,
  10402. const string &endpoint,
  10403. size_t expected_content_size) {
  10404. Server svr;
  10405. setup_handler(svr);
  10406. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10407. auto se = detail::scope_exit([&] {
  10408. svr.stop();
  10409. t.join();
  10410. });
  10411. svr.wait_until_ready();
  10412. Client cli(HOST, PORT);
  10413. vector<uint64_t> progress_values;
  10414. string received_body;
  10415. auto res = client_call(
  10416. cli, endpoint,
  10417. [&](const char *data, size_t data_length) -> bool {
  10418. received_body.append(data, data_length);
  10419. return true;
  10420. },
  10421. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10422. progress_values.push_back(current);
  10423. return true;
  10424. });
  10425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10426. EXPECT_EQ(200, res->status);
  10427. EXPECT_FALSE(progress_values.empty());
  10428. EXPECT_EQ(expected_content_size, received_body.size());
  10429. EXPECT_TRUE(res->body.empty());
  10430. }
  10431. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10432. TestContentReceiverDownloadProgress(
  10433. [](Server &svr) {
  10434. svr.Get("/download-receiver",
  10435. [](const Request & /*req*/, Response &res) {
  10436. string content(2000, 'R');
  10437. res.set_content(content, "text/plain");
  10438. });
  10439. },
  10440. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10441. DownloadProgress progress_callback) {
  10442. return cli.Get(endpoint, content_receiver, progress_callback);
  10443. },
  10444. "/download-receiver", 2000u);
  10445. }
  10446. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10447. // A provider reaching a pass with nothing to hand over - an empty buffer
  10448. // popped off a queue, say - must not be taken to mean the body is finished.
  10449. // It used to end the loop with the terminating chunk unwritten while the
  10450. // server still considered the response complete, so the peer waited for an
  10451. // end that never arrived.
  10452. Server svr;
  10453. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10454. auto step = std::make_shared<int>(0);
  10455. res.set_chunked_content_provider("text/plain",
  10456. [step](size_t /*offset*/, DataSink &sink) {
  10457. switch ((*step)++) {
  10458. case 0: sink.write("", 0); break;
  10459. case 1: sink.write("hello", 5); break;
  10460. default: sink.done(); break;
  10461. }
  10462. return true;
  10463. });
  10464. });
  10465. auto port = svr.bind_to_any_port(HOST);
  10466. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10467. auto listen_se = detail::scope_exit([&] {
  10468. svr.stop();
  10469. listen_thread.join();
  10470. ASSERT_FALSE(svr.is_running());
  10471. });
  10472. svr.wait_until_ready();
  10473. Client cli(HOST, port);
  10474. // Without the fix the body is never terminated, so bound the wait rather
  10475. // than letting the test hang on the default read timeout.
  10476. cli.set_read_timeout(5, 0);
  10477. auto res = cli.Get("/stream");
  10478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10479. EXPECT_EQ(StatusCode::OK_200, res->status);
  10480. EXPECT_EQ("hello", res->body);
  10481. }
  10482. TEST(StreamingTest, NoContentLengthStreaming) {
  10483. Server svr;
  10484. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10485. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10486. if (offset < 6) {
  10487. sink.os << (offset < 3 ? "a" : "b");
  10488. } else {
  10489. sink.done();
  10490. }
  10491. return true;
  10492. });
  10493. });
  10494. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10495. auto listen_se = detail::scope_exit([&] {
  10496. svr.stop();
  10497. listen_thread.join();
  10498. ASSERT_FALSE(svr.is_running());
  10499. });
  10500. svr.wait_until_ready();
  10501. Client client(HOST, PORT);
  10502. auto get_thread = std::thread([&client]() {
  10503. std::string s;
  10504. auto res =
  10505. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10506. s += std::string(data, len);
  10507. return true;
  10508. });
  10509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10510. EXPECT_EQ(StatusCode::OK_200, res->status);
  10511. EXPECT_EQ("aaabbb", s);
  10512. });
  10513. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10514. // Give GET time to get a few messages.
  10515. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10516. }
  10517. TEST(MountTest, Unmount) {
  10518. Server svr;
  10519. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10520. auto se = detail::scope_exit([&] {
  10521. svr.stop();
  10522. listen_thread.join();
  10523. ASSERT_FALSE(svr.is_running());
  10524. });
  10525. svr.wait_until_ready();
  10526. Client cli("localhost", PORT);
  10527. svr.set_mount_point("/mount2", "./www2");
  10528. auto res = cli.Get("/");
  10529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10530. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10531. res = cli.Get("/mount2/dir/test.html");
  10532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10533. EXPECT_EQ(StatusCode::OK_200, res->status);
  10534. svr.set_mount_point("/", "./www");
  10535. res = cli.Get("/dir/");
  10536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10537. EXPECT_EQ(StatusCode::OK_200, res->status);
  10538. svr.remove_mount_point("/");
  10539. res = cli.Get("/dir/");
  10540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10541. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10542. svr.remove_mount_point("/mount2");
  10543. res = cli.Get("/mount2/dir/test.html");
  10544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10545. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10546. }
  10547. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10548. Server svr;
  10549. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10550. svr.Get("/api/hello", [](const Request &, Response &res) {
  10551. res.set_content("api", "text/plain");
  10552. });
  10553. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10554. auto se = detail::scope_exit([&] {
  10555. svr.stop();
  10556. listen_thread.join();
  10557. ASSERT_FALSE(svr.is_running());
  10558. });
  10559. svr.wait_until_ready();
  10560. Client cli(HOST, PORT);
  10561. auto res = cli.Get("/dir/test.html");
  10562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10563. EXPECT_EQ(StatusCode::OK_200, res->status);
  10564. res = cli.Get("/api/hello");
  10565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10566. EXPECT_EQ(StatusCode::OK_200, res->status);
  10567. EXPECT_EQ("api", res->body);
  10568. }
  10569. TEST(MountTest, PathSegmentBoundary) {
  10570. Server svr;
  10571. svr.set_mount_point("/mount2", "./www2");
  10572. svr.set_mount_point("/", "./www");
  10573. auto port = svr.bind_to_any_port(HOST);
  10574. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10575. auto se = detail::scope_exit([&] {
  10576. svr.stop();
  10577. listen_thread.join();
  10578. ASSERT_FALSE(svr.is_running());
  10579. });
  10580. svr.wait_until_ready();
  10581. Client cli(HOST, port);
  10582. auto res = cli.Get("/mount2/dir/test.html");
  10583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10584. EXPECT_EQ(StatusCode::OK_200, res->status);
  10585. // "/mount2" must not match part-way through a path segment.
  10586. res = cli.Get("/mount2dir/test.html");
  10587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10588. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10589. // A mount point ending in '/' keeps matching every path below it.
  10590. res = cli.Get("/dir/test.html");
  10591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10592. EXPECT_EQ(StatusCode::OK_200, res->status);
  10593. }
  10594. TEST(MountTest, Redicect) {
  10595. Server svr;
  10596. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10597. auto se = detail::scope_exit([&] {
  10598. svr.stop();
  10599. listen_thread.join();
  10600. ASSERT_FALSE(svr.is_running());
  10601. });
  10602. svr.set_mount_point("/", "./www");
  10603. svr.wait_until_ready();
  10604. Client cli("localhost", PORT);
  10605. auto res = cli.Get("/dir/");
  10606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10607. EXPECT_EQ(StatusCode::OK_200, res->status);
  10608. res = cli.Get("/dir");
  10609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10610. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10611. res = cli.Get("/file");
  10612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10613. EXPECT_EQ(StatusCode::OK_200, res->status);
  10614. res = cli.Get("/file/");
  10615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10616. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10617. cli.set_follow_location(true);
  10618. res = cli.Get("/dir");
  10619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10620. EXPECT_EQ(StatusCode::OK_200, res->status);
  10621. }
  10622. TEST(MountTest, MultibytesPathName) {
  10623. Server svr;
  10624. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10625. auto se = detail::scope_exit([&] {
  10626. svr.stop();
  10627. listen_thread.join();
  10628. ASSERT_FALSE(svr.is_running());
  10629. });
  10630. svr.set_mount_point("/", "./www");
  10631. svr.wait_until_ready();
  10632. Client cli("localhost", PORT);
  10633. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10635. EXPECT_EQ(StatusCode::OK_200, res->status);
  10636. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10637. }
  10638. #ifdef _WIN32
  10639. // Issue #2435: mmap::open() must succeed even when another handle holds
  10640. // the file open for writing (e.g. an active log file).
  10641. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10642. const char *path = "mmap_concurrent_writer_test.txt";
  10643. const char *content = "hello";
  10644. {
  10645. std::ofstream f(path, std::ios::binary);
  10646. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10647. }
  10648. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10649. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10650. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10651. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10652. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10653. detail::mmap m(path);
  10654. ASSERT_TRUE(m.is_open());
  10655. EXPECT_EQ(strlen(content), m.size());
  10656. char buf[8];
  10657. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10658. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10659. }
  10660. #endif
  10661. #ifndef _WIN32
  10662. // A directory or a device has no size to serve.
  10663. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10664. const char *path = "./mmap_not_regular_test_dir";
  10665. ASSERT_EQ(0, ::mkdir(path, 0755));
  10666. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10667. for (auto p : {path, "/dev/null"}) {
  10668. detail::mmap m(p);
  10669. EXPECT_FALSE(m.is_open()) << p;
  10670. EXPECT_EQ(0U, m.size()) << p;
  10671. }
  10672. Server svr;
  10673. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10674. res.set_file_content("/dev/null");
  10675. });
  10676. auto port = svr.bind_to_any_port(HOST);
  10677. thread t = thread([&] { svr.listen_after_bind(); });
  10678. auto se = detail::scope_exit([&] {
  10679. svr.stop();
  10680. t.join();
  10681. });
  10682. svr.wait_until_ready();
  10683. auto res = Client(HOST, port).Get("/null");
  10684. ASSERT_TRUE(res);
  10685. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10686. }
  10687. #endif
  10688. #ifdef __linux__
  10689. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10690. TEST(MmapTest, FileIsNotMapped) {
  10691. const char *path = "mmap_not_mapped_test.txt";
  10692. {
  10693. std::ofstream f(path, std::ios::binary);
  10694. f << "hello";
  10695. }
  10696. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10697. detail::mmap m(path);
  10698. ASSERT_TRUE(m.is_open());
  10699. std::ifstream maps("/proc/self/maps");
  10700. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10701. std::istreambuf_iterator<char>());
  10702. EXPECT_EQ(std::string::npos, mappings.find(path));
  10703. }
  10704. #endif
  10705. TEST(KeepAliveTest, ReadTimeout) {
  10706. Server svr;
  10707. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10708. std::this_thread::sleep_for(std::chrono::seconds(2));
  10709. res.set_content("a", "text/plain");
  10710. });
  10711. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10712. res.set_content("b", "text/plain");
  10713. });
  10714. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10715. auto se = detail::scope_exit([&] {
  10716. svr.stop();
  10717. listen_thread.join();
  10718. ASSERT_FALSE(svr.is_running());
  10719. });
  10720. svr.wait_until_ready();
  10721. Client cli("localhost", PORT);
  10722. cli.set_keep_alive(true);
  10723. cli.set_read_timeout(std::chrono::seconds(1));
  10724. auto resa = cli.Get("/a");
  10725. ASSERT_FALSE(resa);
  10726. EXPECT_EQ(Error::Read, resa.error());
  10727. auto resb = cli.Get("/b");
  10728. ASSERT_TRUE(resb);
  10729. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10730. EXPECT_EQ("b", resb->body);
  10731. }
  10732. TEST(KeepAliveTest, MaxCount) {
  10733. size_t keep_alive_max_count = 3;
  10734. Server svr;
  10735. svr.set_keep_alive_max_count(keep_alive_max_count);
  10736. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10737. res.set_content("Hello World!", "text/plain");
  10738. });
  10739. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10740. auto se = detail::scope_exit([&] {
  10741. svr.stop();
  10742. listen_thread.join();
  10743. ASSERT_FALSE(svr.is_running());
  10744. });
  10745. svr.wait_until_ready();
  10746. Client cli(HOST, PORT);
  10747. cli.set_keep_alive(true);
  10748. for (size_t i = 0; i < 5; i++) {
  10749. auto result = cli.Get("/hi");
  10750. ASSERT_TRUE(result);
  10751. EXPECT_EQ(StatusCode::OK_200, result->status);
  10752. if (i == keep_alive_max_count - 1) {
  10753. EXPECT_EQ("close", result->get_header_value("Connection"));
  10754. } else {
  10755. EXPECT_FALSE(result->has_header("Connection"));
  10756. }
  10757. }
  10758. }
  10759. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10760. // can pull the next one into the server's buffer. The server must serve it
  10761. // without waiting for the socket to become readable again. The keep-alive
  10762. // timeout outlasts the client's read timeout, so a request left waiting for it
  10763. // shows up as a missing response.
  10764. static void serve_pipelining_routes(Server &svr,
  10765. const std::function<void(int)> &client) {
  10766. svr.set_keep_alive_timeout(5);
  10767. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10768. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10769. });
  10770. svr.Post("/echo", [](const Request &req, Response &res) {
  10771. res.set_content("echo " + req.body, "text/plain");
  10772. });
  10773. auto port = svr.bind_to_any_port(HOST);
  10774. thread t = thread([&] { svr.listen_after_bind(); });
  10775. auto se = detail::scope_exit([&] {
  10776. svr.stop();
  10777. t.join();
  10778. });
  10779. svr.wait_until_ready();
  10780. client(port);
  10781. }
  10782. static std::string
  10783. send_pipelined_requests(const std::vector<std::string> &parts) {
  10784. Server svr;
  10785. std::string res;
  10786. serve_pipelining_routes(svr, [&](int port) {
  10787. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10788. });
  10789. return res;
  10790. }
  10791. static void expect_in_order(const std::string &res,
  10792. const std::vector<std::string> &bodies) {
  10793. size_t pos = 0;
  10794. for (const auto &body : bodies) {
  10795. pos = res.find(body, pos);
  10796. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10797. pos += body.size();
  10798. }
  10799. }
  10800. TEST(KeepAliveTest, PipelinedRequests) {
  10801. auto res = send_pipelined_requests(
  10802. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10803. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10804. "Content-Length: 4\r\n\r\nbody"
  10805. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10806. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10807. }
  10808. // The second request starts in the server's buffer and ends on the socket.
  10809. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10810. auto res =
  10811. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10812. "GET /hi/2 HTTP/1.1\r\nHo",
  10813. "st: localhost\r\nConnection: close\r\n\r\n"});
  10814. expect_in_order(res, {"hi 1", "hi 2"});
  10815. }
  10816. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10817. // CRLF after a body does not turn into a 400 for the next request.
  10818. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10819. auto res = send_pipelined_requests(
  10820. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10821. "Content-Length: 4\r\n\r\nbody\r\n"
  10822. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10823. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10824. expect_in_order(res, {"echo body", "hi 2"});
  10825. }
  10826. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10827. // must not be served as the next request.
  10828. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10829. auto res = send_pipelined_requests(
  10830. {"INVALID REQUEST LINE\r\n\r\n"
  10831. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10832. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10833. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10834. }
  10835. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10836. // Over TLS, the next request is held by the TLS library as already decrypted
  10837. // data rather than on the socket.
  10838. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10840. std::string res;
  10841. serve_pipelining_routes(svr, [&](int port) {
  10842. // One part, so all three requests arrive in one TLS record
  10843. EXPECT_TRUE(send_ssl_request_in_parts(
  10844. 2,
  10845. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10846. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10847. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10848. &res, port));
  10849. });
  10850. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10851. }
  10852. #endif
  10853. TEST(KeepAliveTest, Issue1041) {
  10854. Server svr;
  10855. svr.set_keep_alive_timeout(3);
  10856. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10857. res.set_content("Hello World!", "text/plain");
  10858. });
  10859. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10860. auto se = detail::scope_exit([&] {
  10861. svr.stop();
  10862. listen_thread.join();
  10863. ASSERT_FALSE(svr.is_running());
  10864. });
  10865. svr.wait_until_ready();
  10866. Client cli(HOST, PORT);
  10867. cli.set_keep_alive(true);
  10868. auto result = cli.Get("/hi");
  10869. ASSERT_TRUE(result);
  10870. EXPECT_EQ(StatusCode::OK_200, result->status);
  10871. std::this_thread::sleep_for(std::chrono::seconds(5));
  10872. result = cli.Get("/hi");
  10873. ASSERT_TRUE(result);
  10874. EXPECT_EQ(StatusCode::OK_200, result->status);
  10875. }
  10876. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10877. Server svr;
  10878. svr.set_keep_alive_max_count(0);
  10879. std::set<int> remote_ports;
  10880. svr.Get("/hi", [&](const Request &req, Response &res) {
  10881. remote_ports.insert(req.remote_port);
  10882. res.set_content("hi", "text/plain");
  10883. });
  10884. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10885. auto se = detail::scope_exit([&] {
  10886. svr.stop();
  10887. listen_thread.join();
  10888. ASSERT_FALSE(svr.is_running());
  10889. });
  10890. svr.wait_until_ready();
  10891. Client cli(HOST, PORT);
  10892. cli.set_keep_alive(true);
  10893. for (int i = 0; i < 3; i++) {
  10894. auto res = cli.Get("/hi");
  10895. ASSERT_TRUE(res);
  10896. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10897. }
  10898. // All three over one connection
  10899. EXPECT_EQ(1u, remote_ports.size());
  10900. }
  10901. TEST(KeepAliveTest, Issue1959) {
  10902. Server svr;
  10903. svr.set_keep_alive_timeout(5);
  10904. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10905. res.set_content("a", "text/plain");
  10906. });
  10907. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10908. auto se = detail::scope_exit([&] {
  10909. if (!svr.is_running()) return;
  10910. svr.stop();
  10911. listen_thread.join();
  10912. ASSERT_FALSE(svr.is_running());
  10913. });
  10914. svr.wait_until_ready();
  10915. Client cli("localhost", PORT);
  10916. cli.set_keep_alive(true);
  10917. using namespace std::chrono;
  10918. auto start = steady_clock::now();
  10919. cli.Get("/a");
  10920. svr.stop();
  10921. listen_thread.join();
  10922. auto end = steady_clock::now();
  10923. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10924. EXPECT_LT(elapsed, 5000);
  10925. }
  10926. #ifdef CPPHTTPLIB_SSL_ENABLED
  10927. TEST(KeepAliveTest, SSLClientReconnection) {
  10928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10929. ASSERT_TRUE(svr.is_valid());
  10930. svr.set_keep_alive_timeout(1);
  10931. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10932. res.set_content("Hello World!", "text/plain");
  10933. });
  10934. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10935. auto se = detail::scope_exit([&] {
  10936. svr.stop();
  10937. listen_thread.join();
  10938. ASSERT_FALSE(svr.is_running());
  10939. });
  10940. svr.wait_until_ready();
  10941. SSLClient cli(HOST, PORT);
  10942. cli.enable_server_certificate_verification(false);
  10943. cli.set_keep_alive(true);
  10944. auto result = cli.Get("/hi");
  10945. ASSERT_TRUE(result);
  10946. EXPECT_EQ(StatusCode::OK_200, result->status);
  10947. result = cli.Get("/hi");
  10948. ASSERT_TRUE(result);
  10949. EXPECT_EQ(StatusCode::OK_200, result->status);
  10950. std::this_thread::sleep_for(std::chrono::seconds(2));
  10951. // Recoonect
  10952. result = cli.Get("/hi");
  10953. ASSERT_TRUE(result);
  10954. EXPECT_EQ(StatusCode::OK_200, result->status);
  10955. result = cli.Get("/hi");
  10956. ASSERT_TRUE(result);
  10957. EXPECT_EQ(StatusCode::OK_200, result->status);
  10958. }
  10959. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10960. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10961. ASSERT_TRUE(svr.is_valid());
  10962. svr.set_keep_alive_timeout(1);
  10963. std::string content = "reconnect";
  10964. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10965. res.set_content("Hello World!", "text/plain");
  10966. });
  10967. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10968. auto se = detail::scope_exit([&] {
  10969. svr.stop();
  10970. listen_thread.join();
  10971. ASSERT_FALSE(svr.is_running());
  10972. });
  10973. svr.wait_until_ready();
  10974. SSLClient cli(HOST, PORT);
  10975. cli.enable_server_certificate_verification(false);
  10976. cli.set_keep_alive(true);
  10977. auto result = cli.Post(
  10978. "/hi", content.size(),
  10979. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10980. sink.write(content.c_str(), content.size());
  10981. return true;
  10982. },
  10983. "text/plain");
  10984. ASSERT_TRUE(result);
  10985. EXPECT_EQ(200, result->status);
  10986. std::this_thread::sleep_for(std::chrono::seconds(2));
  10987. // Recoonect
  10988. result = cli.Post(
  10989. "/hi", content.size(),
  10990. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10991. sink.write(content.c_str(), content.size());
  10992. return true;
  10993. },
  10994. "text/plain");
  10995. ASSERT_TRUE(result);
  10996. EXPECT_EQ(200, result->status);
  10997. result = cli.Post(
  10998. "/hi", content.size(),
  10999. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11000. sink.write(content.c_str(), content.size());
  11001. return true;
  11002. },
  11003. "text/plain");
  11004. ASSERT_TRUE(result);
  11005. EXPECT_EQ(200, result->status);
  11006. }
  11007. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11008. using namespace httplib::tls;
  11009. {
  11010. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11011. ASSERT_TRUE(svr.is_valid());
  11012. svr.Get("/sni", [&](const Request &req, Response &res) {
  11013. std::string expected = req.sni();
  11014. EXPECT_EQ(expected, req.get_param_value("expected"));
  11015. res.set_content("ok", "text/plain");
  11016. });
  11017. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11018. auto se = detail::scope_exit([&] {
  11019. svr.stop();
  11020. listen_thread.join();
  11021. ASSERT_FALSE(svr.is_running());
  11022. });
  11023. svr.wait_until_ready();
  11024. {
  11025. SSLClient cli("localhost", PORT);
  11026. cli.enable_server_certificate_verification(false);
  11027. auto res = cli.Get("/sni?expected=localhost");
  11028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11029. }
  11030. {
  11031. SSLClient cli("::1", PORT);
  11032. cli.enable_server_certificate_verification(false);
  11033. auto res = cli.Get("/sni?expected=");
  11034. // NOTE: This may fail if the server is listening on IPv4 only
  11035. // (e.g., when localhost resolves to 127.0.0.1 only)
  11036. if (res) {
  11037. EXPECT_EQ(StatusCode::OK_200, res->status);
  11038. } else {
  11039. EXPECT_EQ(Error::Connection, res.error());
  11040. }
  11041. }
  11042. }
  11043. }
  11044. #endif
  11045. TEST(ClientProblemDetectionTest, ContentProvider) {
  11046. Server svr;
  11047. size_t content_length = 1024 * 1024;
  11048. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11049. res.set_content_provider(
  11050. content_length, "text/plain",
  11051. [&](size_t offset, size_t length, DataSink &sink) {
  11052. auto out_len = std::min(length, static_cast<size_t>(1024));
  11053. std::string out(out_len, '@');
  11054. sink.write(out.data(), out_len);
  11055. return offset < 4096;
  11056. },
  11057. [](bool success) { ASSERT_FALSE(success); });
  11058. });
  11059. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11060. res.set_content_provider(
  11061. 0, "text/plain",
  11062. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11063. EXPECT_TRUE(false);
  11064. return true;
  11065. },
  11066. [](bool success) { ASSERT_FALSE(success); });
  11067. });
  11068. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11069. auto se = detail::scope_exit([&] {
  11070. svr.stop();
  11071. listen_thread.join();
  11072. ASSERT_FALSE(svr.is_running());
  11073. });
  11074. svr.wait_until_ready();
  11075. Client cli("localhost", PORT);
  11076. {
  11077. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11078. size_t /*data_length*/) { return false; });
  11079. ASSERT_FALSE(res);
  11080. }
  11081. {
  11082. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11083. size_t /*data_length*/) { return false; });
  11084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11085. }
  11086. }
  11087. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11088. // A provider that reports success without writing anything and without
  11089. // calling done() used to be handed the same offset and length again on every
  11090. // pass, so it spun for as long as the peer stayed connected.
  11091. Server svr;
  11092. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11093. res.set_content("ok", "text/plain");
  11094. });
  11095. auto port = svr.bind_to_any_port(HOST);
  11096. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11097. auto se = detail::scope_exit([&] {
  11098. svr.stop();
  11099. listen_thread.join();
  11100. ASSERT_FALSE(svr.is_running());
  11101. });
  11102. svr.wait_until_ready();
  11103. std::atomic<int> call_count{0};
  11104. Client cli(HOST, port);
  11105. auto res = cli.Post(
  11106. "/", 1024,
  11107. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11108. // Give up after enough passes to show the spin, so that losing the
  11109. // check below fails this test instead of hanging it.
  11110. return ++call_count < 100;
  11111. },
  11112. "text/plain");
  11113. ASSERT_FALSE(res);
  11114. EXPECT_EQ(Error::Write, res.error());
  11115. EXPECT_EQ(1, call_count.load());
  11116. }
  11117. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11118. // A writer only has to assign `write`. The other three used to be left as
  11119. // empty std::functions, so a provider calling one threw
  11120. // std::bad_function_call out of the thread running it and took the whole
  11121. // process down.
  11122. DataSink sink;
  11123. std::string written;
  11124. sink.write = [&](const char *data, size_t data_len) {
  11125. written.append(data, data_len);
  11126. return true;
  11127. };
  11128. EXPECT_TRUE(sink.is_writable());
  11129. sink.done();
  11130. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11131. EXPECT_TRUE(written.empty());
  11132. }
  11133. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11134. // A sink that cannot carry trailers still has to finish.
  11135. DataSink sink;
  11136. auto done_count = 0;
  11137. sink.done = [&]() { done_count++; };
  11138. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11139. EXPECT_EQ(1, done_count);
  11140. }
  11141. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11142. Server svr;
  11143. const std::string body(4096, 'x');
  11144. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11145. res.set_content_provider(body.size(), "text/plain",
  11146. [&](size_t offset, size_t length, DataSink &sink) {
  11147. sink.write(body.data() + offset, length);
  11148. sink.done();
  11149. return true;
  11150. });
  11151. });
  11152. auto port = svr.bind_to_any_port(HOST);
  11153. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11154. auto se = detail::scope_exit([&] {
  11155. svr.stop();
  11156. listen_thread.join();
  11157. ASSERT_FALSE(svr.is_running());
  11158. });
  11159. svr.wait_until_ready();
  11160. Client cli(HOST, port);
  11161. auto res = cli.Get("/");
  11162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11163. EXPECT_EQ(StatusCode::OK_200, res->status);
  11164. EXPECT_EQ(body, res->body);
  11165. }
  11166. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11167. Server svr;
  11168. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11169. res.set_content_provider(
  11170. 1024, "text/plain",
  11171. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11172. sink.write("hello", 5);
  11173. sink.done(); // short of the 1024 bytes the response promised
  11174. return true;
  11175. });
  11176. });
  11177. auto port = svr.bind_to_any_port(HOST);
  11178. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11179. auto se = detail::scope_exit([&] {
  11180. svr.stop();
  11181. listen_thread.join();
  11182. ASSERT_FALSE(svr.is_running());
  11183. });
  11184. svr.wait_until_ready();
  11185. Client cli(HOST, port);
  11186. cli.set_read_timeout(5, 0);
  11187. // The response is short of its Content-Length, so the client cannot read a
  11188. // complete body. What matters is that this returns at all: a no-op done()
  11189. // would leave the writer looping over a provider that never makes progress.
  11190. auto res = cli.Get("/");
  11191. EXPECT_FALSE(res);
  11192. }
  11193. // Read as the next response by a peer that sees it after a framed body.
  11194. static const std::string smuggled_response =
  11195. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11196. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11197. Server svr;
  11198. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11199. res.set_content_provider(
  11200. 5, "text/plain",
  11201. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11202. auto data = "AAAAA" + smuggled_response;
  11203. sink.write(data.data(), data.size());
  11204. return true;
  11205. });
  11206. });
  11207. thread t = thread([&] { svr.listen(HOST, PORT); });
  11208. auto se = detail::scope_exit([&] {
  11209. svr.stop();
  11210. t.join();
  11211. ASSERT_FALSE(svr.is_running());
  11212. });
  11213. svr.wait_until_ready();
  11214. std::string resp;
  11215. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11216. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11217. resp.clear();
  11218. ASSERT_TRUE(send_request(
  11219. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11220. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11221. }
  11222. TEST(NoContentTest, BodyIsNotSent) {
  11223. Server svr;
  11224. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11225. res.status = StatusCode::NoContent_204;
  11226. res.set_content(smuggled_response, "text/plain");
  11227. });
  11228. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11229. res.status = StatusCode::NotModified_304;
  11230. res.set_chunked_content_provider(
  11231. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11232. sink.write(smuggled_response.data(), smuggled_response.size());
  11233. sink.done();
  11234. return true;
  11235. });
  11236. });
  11237. thread t = thread([&] { svr.listen(HOST, PORT); });
  11238. auto se = detail::scope_exit([&] {
  11239. svr.stop();
  11240. t.join();
  11241. ASSERT_FALSE(svr.is_running());
  11242. });
  11243. svr.wait_until_ready();
  11244. for (auto path : {"/204", "/304"}) {
  11245. std::string resp;
  11246. ASSERT_TRUE(send_request(
  11247. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11248. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11249. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11250. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11251. }
  11252. }
  11253. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11254. Server svr;
  11255. std::atomic<bool> smuggled(false);
  11256. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11257. res.set_content("ok", "text/plain");
  11258. });
  11259. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11260. smuggled = true;
  11261. });
  11262. auto port = svr.bind_to_any_port(HOST);
  11263. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11264. auto se = detail::scope_exit([&] {
  11265. svr.stop();
  11266. listen_thread.join();
  11267. ASSERT_FALSE(svr.is_running());
  11268. });
  11269. svr.wait_until_ready();
  11270. // What follows the body would be read as the next request.
  11271. Client cli(HOST, port);
  11272. auto res = cli.Post(
  11273. "/", 5,
  11274. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11275. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11276. sink.write(data.data(), data.size());
  11277. return true;
  11278. },
  11279. "text/plain");
  11280. ASSERT_FALSE(res);
  11281. EXPECT_EQ(Error::Write, res.error());
  11282. EXPECT_FALSE(smuggled);
  11283. }
  11284. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11285. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11286. // The compressed path builds the whole body before connecting, so this
  11287. // fails client-side and never reaches a server.
  11288. Client cli(HOST, PORT);
  11289. cli.set_compress(true);
  11290. auto res = cli.Post(
  11291. "/", 1024,
  11292. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11293. sink.write("hello", 5);
  11294. sink.done(); // short of the 1024 bytes the request announced
  11295. return true;
  11296. },
  11297. "text/plain");
  11298. ASSERT_FALSE(res);
  11299. EXPECT_EQ(Error::Write, res.error());
  11300. }
  11301. #endif
  11302. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11303. Server svr;
  11304. svr.set_error_handler([](Request const &, Response &res) -> void {
  11305. res.set_chunked_content_provider(
  11306. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11307. sink.os << "hello";
  11308. sink.os << "world";
  11309. sink.done();
  11310. return true;
  11311. });
  11312. });
  11313. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11314. auto se = detail::scope_exit([&] {
  11315. svr.stop();
  11316. listen_thread.join();
  11317. ASSERT_FALSE(svr.is_running());
  11318. });
  11319. svr.wait_until_ready();
  11320. Client cli("localhost", PORT);
  11321. auto res = cli.Get("/");
  11322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11323. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11324. EXPECT_EQ("helloworld", res->body);
  11325. }
  11326. // A body set after a content provider must replace it, not be sent through it.
  11327. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11328. Server svr;
  11329. svr.set_mount_point("/", "./www");
  11330. svr.set_file_request_handler([](const Request &req, Response &res) {
  11331. if (req.path == "/dir/test.html") {
  11332. res.status = StatusCode::Forbidden_403;
  11333. res.set_content(std::string(5000, 'D'), "text/plain");
  11334. } else if (req.path == "/file") {
  11335. res.status = StatusCode::Forbidden_403;
  11336. res.body = "Denied";
  11337. }
  11338. });
  11339. auto port = svr.bind_to_any_port(HOST);
  11340. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11341. auto se = detail::scope_exit([&] {
  11342. svr.stop();
  11343. t.join();
  11344. ASSERT_FALSE(svr.is_running());
  11345. });
  11346. svr.wait_until_ready();
  11347. Client cli(HOST, port);
  11348. {
  11349. auto res = cli.Get("/dir/test.html");
  11350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11351. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11352. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11353. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11354. }
  11355. {
  11356. auto res = cli.Get("/file");
  11357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11358. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11359. EXPECT_EQ("Denied", res->body);
  11360. }
  11361. {
  11362. auto res = cli.Get("/dir/index.html");
  11363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11364. EXPECT_EQ(StatusCode::OK_200, res->status);
  11365. EXPECT_EQ(0U, res->body.find("<html>"));
  11366. }
  11367. }
  11368. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11369. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11370. Server svr;
  11371. std::vector<bool> released;
  11372. std::mutex released_mutex;
  11373. auto releaser = [&](bool success) {
  11374. std::lock_guard<std::mutex> guard(released_mutex);
  11375. released.push_back(success);
  11376. };
  11377. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11378. return sink.write(&"hello"[offset], length);
  11379. };
  11380. svr.Get("/sized", [&](const Request &, Response &res) {
  11381. res.status = StatusCode::NotFound_404;
  11382. res.set_content_provider(5, "text/plain", provider, releaser);
  11383. });
  11384. svr.Get("/chunked", [&](const Request &, Response &res) {
  11385. res.status = StatusCode::ServiceUnavailable_503;
  11386. res.set_chunked_content_provider(
  11387. "text/plain",
  11388. [](size_t, DataSink &sink) {
  11389. sink.os << "chunk";
  11390. sink.done();
  11391. return true;
  11392. },
  11393. releaser);
  11394. });
  11395. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11396. res.set_content_provider(5, "text/plain", provider, releaser);
  11397. throw std::runtime_error("after the provider");
  11398. });
  11399. svr.set_error_handler([](const Request &req, Response &res) {
  11400. // Leave the exception handler's content to it.
  11401. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11402. res.set_content(std::string(1000, 'E'), "text/html");
  11403. return Server::HandlerResponse::Handled;
  11404. });
  11405. svr.set_exception_handler(
  11406. [](const Request &, Response &res, std::exception_ptr) {
  11407. res.status = StatusCode::InternalServerError_500;
  11408. res.set_content(std::string(1000, 'X'), "text/html");
  11409. });
  11410. auto port = svr.bind_to_any_port(HOST);
  11411. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11412. auto se = detail::scope_exit([&] {
  11413. svr.stop();
  11414. t.join();
  11415. ASSERT_FALSE(svr.is_running());
  11416. });
  11417. svr.wait_until_ready();
  11418. Client cli(HOST, port);
  11419. {
  11420. auto res = cli.Get("/sized");
  11421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11422. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11423. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11424. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11425. }
  11426. {
  11427. auto res = cli.Get("/chunked");
  11428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11429. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11430. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11431. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11432. }
  11433. {
  11434. auto res = cli.Get("/throw");
  11435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11436. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11437. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11438. }
  11439. std::lock_guard<std::mutex> guard(released_mutex);
  11440. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11441. }
  11442. #endif
  11443. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11444. Server svr;
  11445. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11446. return sink.write(&"abc"[offset], length);
  11447. };
  11448. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11449. res.set_file_content("./www/dir/test.html");
  11450. res.set_content("body", "text/plain");
  11451. });
  11452. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11453. res.set_content(std::string(100, 'B'), "text/plain");
  11454. res.set_file_content("./www/dir/test.html");
  11455. });
  11456. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11457. res.set_content(std::string(100, 'B'), "text/plain");
  11458. res.set_content_provider(3, "text/x-provider", abc);
  11459. });
  11460. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11461. res.set_content_provider(3, "text/x-provider", abc);
  11462. res.set_content(std::string(100, 'B'), "text/plain");
  11463. });
  11464. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11465. res.set_content_provider(3, "text/x-provider", abc);
  11466. res.set_file_content("./www/dir/test.html", "text/x-file");
  11467. });
  11468. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11469. res.set_file_content("./www/dir/test.html");
  11470. res.set_header("Content-Type", "text/x-handler");
  11471. });
  11472. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11473. res.set_content_provider(3, "text/plain", abc);
  11474. res.body = "direct";
  11475. });
  11476. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11477. res.set_file_content("./www/dir/test.html");
  11478. res.body = "direct";
  11479. });
  11480. auto port = svr.bind_to_any_port(HOST);
  11481. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11482. auto se = detail::scope_exit([&] {
  11483. svr.stop();
  11484. t.join();
  11485. ASSERT_FALSE(svr.is_running());
  11486. });
  11487. svr.wait_until_ready();
  11488. Client cli(HOST, port);
  11489. auto expect_body = [&](const char *path, const std::string &body,
  11490. const std::string &type) {
  11491. // Uncompressed, so Content-Length can be compared with the body.
  11492. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11493. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11494. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11495. EXPECT_EQ(body, res->body) << path;
  11496. EXPECT_EQ(std::to_string(body.size()),
  11497. res->get_header_value("Content-Length"))
  11498. << path;
  11499. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11500. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11501. };
  11502. expect_body("/file-then-body", "body", "text/plain");
  11503. expect_body("/body-then-file", "test.html", "text/html");
  11504. expect_body("/body-then-provider", "abc", "text/x-provider");
  11505. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11506. expect_body("/provider-then-file", "test.html", "text/x-file");
  11507. expect_body("/file-then-header", "test.html", "text/x-handler");
  11508. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11509. expect_body("/file-then-direct-body", "direct", "text/plain");
  11510. // Ranges are checked against the body, not the dropped provider.
  11511. {
  11512. auto res = cli.Get("/provider-then-direct-body",
  11513. Headers{{make_range_header({{1, 2}})}});
  11514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11515. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11516. EXPECT_EQ("ir", res->body);
  11517. }
  11518. {
  11519. auto res = cli.Get("/file-then-direct-body",
  11520. Headers{{make_range_header({{7, 8}})}});
  11521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11522. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11523. }
  11524. }
  11525. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11526. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11527. const char *path = "./truncated_while_served.txt";
  11528. const size_t size = 32 * 1024 * 1024;
  11529. {
  11530. std::ofstream f(path, std::ios::binary);
  11531. f << std::string(size, 'x');
  11532. }
  11533. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11534. // Over TLS, where the bytes are encrypted in this process rather than
  11535. // copied by send().
  11536. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11537. svr.Get("/file", [&](const Request &, Response &res) {
  11538. res.set_file_content(path, "text/plain");
  11539. });
  11540. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11541. auto se = detail::scope_exit([&] {
  11542. svr.stop();
  11543. thread.join();
  11544. ASSERT_FALSE(svr.is_running());
  11545. });
  11546. svr.wait_until_ready();
  11547. // The file shrinks once the first bytes are in, as a rewrite in place
  11548. // would, and reading the mapping past its new end used to raise SIGBUS.
  11549. SSLClient cli(HOST, PORT);
  11550. cli.enable_server_certificate_verification(false);
  11551. size_t received = 0;
  11552. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11553. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11554. received += len;
  11555. return true;
  11556. });
  11557. EXPECT_FALSE(res);
  11558. EXPECT_LT(received, size);
  11559. }
  11560. #endif
  11561. // Forward declaration (see the base64_encode note).
  11562. namespace httplib {
  11563. namespace detail {
  11564. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11565. const std::string &content_type,
  11566. EncodingType encoding);
  11567. } // namespace detail
  11568. } // namespace httplib
  11569. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11570. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11571. ASSERT_TRUE(mm->is_open());
  11572. Response res;
  11573. detail::set_file_content_provider(res, mm, "text/html",
  11574. detail::EncodingType::None);
  11575. std::string out;
  11576. DataSink sink;
  11577. sink.write = [&](const char *d, size_t l) {
  11578. out.append(d, l);
  11579. return true;
  11580. };
  11581. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11582. EXPECT_EQ("test.html", out);
  11583. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11584. EXPECT_EQ("test.html", out);
  11585. }
  11586. TEST(LongPollingTest, ClientCloseDetection) {
  11587. Server svr;
  11588. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11589. res.set_chunked_content_provider(
  11590. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11591. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11592. sink.os << "hello";
  11593. auto count = 10;
  11594. while (count > 0 && sink.is_writable()) {
  11595. this_thread::sleep_for(chrono::milliseconds(10));
  11596. count--;
  11597. }
  11598. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11599. return true;
  11600. });
  11601. });
  11602. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11603. auto se = detail::scope_exit([&] {
  11604. svr.stop();
  11605. listen_thread.join();
  11606. ASSERT_FALSE(svr.is_running());
  11607. });
  11608. svr.wait_until_ready();
  11609. Client cli("localhost", PORT);
  11610. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11611. EXPECT_EQ("hello", string(data, data_length));
  11612. return false; // close the socket immediately.
  11613. });
  11614. ASSERT_FALSE(res);
  11615. }
  11616. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11617. Server svr;
  11618. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11619. res.set_chunked_content_provider(
  11620. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11621. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11622. sink.os << "hello";
  11623. EXPECT_TRUE(sink.os.good());
  11624. // Wait for the client to close the connection
  11625. auto count = 10;
  11626. while (count > 0 && sink.is_writable()) {
  11627. this_thread::sleep_for(chrono::milliseconds(10));
  11628. count--;
  11629. }
  11630. // After client disconnect, write repeatedly until the socket
  11631. // write actually fails (small writes may be absorbed by the
  11632. // kernel buffer)
  11633. std::string chunk(1024, 'x');
  11634. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11635. sink.os << chunk;
  11636. }
  11637. EXPECT_TRUE(sink.os.fail());
  11638. return true;
  11639. });
  11640. });
  11641. auto port = svr.bind_to_any_port("localhost");
  11642. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11643. auto se = detail::scope_exit([&] {
  11644. svr.stop();
  11645. listen_thread.join();
  11646. ASSERT_FALSE(svr.is_running());
  11647. });
  11648. svr.wait_until_ready();
  11649. Client cli("localhost", port);
  11650. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11651. EXPECT_EQ("hello", string(data, data_length));
  11652. return false; // close the socket immediately.
  11653. });
  11654. ASSERT_FALSE(res);
  11655. }
  11656. TEST(GetWithParametersTest, GetWithParameters) {
  11657. Server svr;
  11658. svr.Get("/", [&](const Request &req, Response &) {
  11659. EXPECT_EQ("world", req.get_param_value("hello"));
  11660. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11661. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11662. });
  11663. svr.Get("/params", [&](const Request &req, Response &) {
  11664. EXPECT_EQ("world", req.get_param_value("hello"));
  11665. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11666. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11667. });
  11668. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11669. EXPECT_EQ("resource-id", req.matches[1]);
  11670. EXPECT_EQ("foo", req.get_param_value("param1"));
  11671. EXPECT_EQ("bar", req.get_param_value("param2"));
  11672. });
  11673. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11674. EXPECT_EQ("user-id", req.path_params.at("id"));
  11675. EXPECT_EQ("foo", req.get_param_value("param1"));
  11676. EXPECT_EQ("bar", req.get_param_value("param2"));
  11677. });
  11678. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11679. auto se = detail::scope_exit([&] {
  11680. svr.stop();
  11681. listen_thread.join();
  11682. ASSERT_FALSE(svr.is_running());
  11683. });
  11684. svr.wait_until_ready();
  11685. {
  11686. Client cli(HOST, PORT);
  11687. Params params;
  11688. params.emplace("hello", "world");
  11689. params.emplace("hello2", "world2");
  11690. params.emplace("hello3", "world3");
  11691. auto res = cli.Get("/", params, Headers{});
  11692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11693. EXPECT_EQ(StatusCode::OK_200, res->status);
  11694. }
  11695. {
  11696. Client cli(HOST, PORT);
  11697. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11699. EXPECT_EQ(StatusCode::OK_200, res->status);
  11700. }
  11701. {
  11702. Client cli(HOST, PORT);
  11703. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11705. EXPECT_EQ(StatusCode::OK_200, res->status);
  11706. }
  11707. {
  11708. Client cli(HOST, PORT);
  11709. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11711. EXPECT_EQ(StatusCode::OK_200, res->status);
  11712. }
  11713. }
  11714. TEST(GetWithParametersTest, GetWithParameters2) {
  11715. Server svr;
  11716. svr.Get("/", [&](const Request &req, Response &res) {
  11717. auto text = req.get_param_value("hello");
  11718. res.set_content(text, "text/plain");
  11719. });
  11720. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11721. auto se = detail::scope_exit([&] {
  11722. svr.stop();
  11723. listen_thread.join();
  11724. ASSERT_FALSE(svr.is_running());
  11725. });
  11726. svr.wait_until_ready();
  11727. Client cli("localhost", PORT);
  11728. Params params;
  11729. params.emplace("hello", "world");
  11730. std::string body;
  11731. auto res = cli.Get("/", params, Headers{},
  11732. [&](const char *data, size_t data_length) {
  11733. body.append(data, data_length);
  11734. return true;
  11735. });
  11736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11737. EXPECT_EQ(StatusCode::OK_200, res->status);
  11738. EXPECT_EQ("world", body);
  11739. }
  11740. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11741. Server svr;
  11742. svr.Get("/search", [&](const Request &req, Response &res) {
  11743. auto q = req.get_param_value("q");
  11744. res.set_content(q, "text/plain");
  11745. });
  11746. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11747. auto se = detail::scope_exit([&] {
  11748. svr.stop();
  11749. listen_thread.join();
  11750. ASSERT_FALSE(svr.is_running());
  11751. });
  11752. svr.wait_until_ready();
  11753. Client cli("localhost", PORT);
  11754. // Verify that Get(path, params) works without requiring Headers argument
  11755. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11757. EXPECT_EQ(StatusCode::OK_200, res->status);
  11758. EXPECT_EQ("cpp-httplib", res->body);
  11759. }
  11760. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11761. auto host = "httpbingo.org";
  11762. auto path = std::string{"/range/32"};
  11763. #ifdef CPPHTTPLIB_SSL_ENABLED
  11764. SSLClient cli(host);
  11765. #else
  11766. Client cli(host);
  11767. #endif
  11768. cli.set_default_headers({make_range_header({{1, 10}})});
  11769. cli.set_connection_timeout(5);
  11770. {
  11771. auto res = cli.Get(path);
  11772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11773. EXPECT_EQ("bcdefghijk", res->body);
  11774. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11775. }
  11776. {
  11777. auto res = cli.Get(path);
  11778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11779. EXPECT_EQ("bcdefghijk", res->body);
  11780. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11781. }
  11782. }
  11783. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11784. Server svr;
  11785. svr.set_default_headers({{"Hello", "World"}});
  11786. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11787. res.set_content("ok", "text/plain");
  11788. });
  11789. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11790. auto se = detail::scope_exit([&] {
  11791. svr.stop();
  11792. listen_thread.join();
  11793. ASSERT_FALSE(svr.is_running());
  11794. });
  11795. svr.wait_until_ready();
  11796. Client cli("localhost", PORT);
  11797. auto res = cli.Get("/");
  11798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11799. EXPECT_EQ(StatusCode::OK_200, res->status);
  11800. EXPECT_EQ("ok", res->body);
  11801. EXPECT_EQ("World", res->get_header_value("Hello"));
  11802. }
  11803. #ifdef CPPHTTPLIB_SSL_ENABLED
  11804. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11805. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11806. ASSERT_TRUE(svr.is_valid());
  11807. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11808. std::this_thread::sleep_for(std::chrono::seconds(2));
  11809. res.set_content("a", "text/plain");
  11810. });
  11811. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11812. res.set_content("b", "text/plain");
  11813. });
  11814. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11815. auto se = detail::scope_exit([&] {
  11816. svr.stop();
  11817. listen_thread.join();
  11818. ASSERT_FALSE(svr.is_running());
  11819. });
  11820. svr.wait_until_ready();
  11821. SSLClient cli("localhost", PORT);
  11822. cli.enable_server_certificate_verification(false);
  11823. cli.set_keep_alive(true);
  11824. cli.set_read_timeout(std::chrono::seconds(1));
  11825. auto resa = cli.Get("/a");
  11826. ASSERT_TRUE(!resa);
  11827. EXPECT_EQ(Error::Read, resa.error());
  11828. auto resb = cli.Get("/b");
  11829. ASSERT_TRUE(resb);
  11830. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11831. EXPECT_EQ("b", resb->body);
  11832. }
  11833. // Closing an idle keep-alive connection sends close_notify and returns. The
  11834. // server must not wait for the client's close_notify: an idle client never
  11835. // sends one, so the worker would be held until the read timeout expires, and
  11836. // stop() would wait for it.
  11837. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11839. ASSERT_TRUE(svr.is_valid());
  11840. svr.set_keep_alive_timeout(1);
  11841. svr.set_read_timeout(10, 0);
  11842. svr.Get("/", [](const Request &, Response &res) {
  11843. res.set_content("ok", "text/plain");
  11844. });
  11845. auto port = svr.bind_to_any_port(HOST);
  11846. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11847. auto se = detail::scope_exit([&] {
  11848. if (listen_thread.joinable()) {
  11849. svr.stop();
  11850. listen_thread.join();
  11851. }
  11852. });
  11853. svr.wait_until_ready();
  11854. SSLClient cli(HOST, port);
  11855. cli.enable_server_certificate_verification(false);
  11856. cli.set_keep_alive(true);
  11857. auto res = cli.Get("/");
  11858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11859. EXPECT_EQ(StatusCode::OK_200, res->status);
  11860. // Stay idle past the keep-alive timeout so the server closes the connection.
  11861. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11862. auto start = std::chrono::steady_clock::now();
  11863. svr.stop();
  11864. listen_thread.join();
  11865. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11866. std::chrono::steady_clock::now() - start)
  11867. .count();
  11868. EXPECT_LT(elapsed, 3000);
  11869. }
  11870. #endif
  11871. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11872. protected:
  11873. ServerTestWithAI_PASSIVE()
  11874. : cli_(HOST, PORT)
  11875. #ifdef CPPHTTPLIB_SSL_ENABLED
  11876. ,
  11877. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11878. #endif
  11879. {
  11880. #ifdef CPPHTTPLIB_SSL_ENABLED
  11881. cli_.enable_server_certificate_verification(false);
  11882. #endif
  11883. }
  11884. virtual void SetUp() {
  11885. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11886. res.set_content("Hello World!", "text/plain");
  11887. });
  11888. t_ = thread(
  11889. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11890. svr_.wait_until_ready();
  11891. }
  11892. virtual void TearDown() {
  11893. svr_.stop();
  11894. t_.join();
  11895. }
  11896. #ifdef CPPHTTPLIB_SSL_ENABLED
  11897. SSLClient cli_;
  11898. SSLServer svr_;
  11899. #else
  11900. Client cli_;
  11901. Server svr_;
  11902. #endif
  11903. thread t_;
  11904. };
  11905. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11906. auto res = cli_.Get("/hi");
  11907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11908. EXPECT_EQ(StatusCode::OK_200, res->status);
  11909. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11910. EXPECT_EQ("Hello World!", res->body);
  11911. }
  11912. class ServerUpDownTest : public ::testing::Test {
  11913. protected:
  11914. ServerUpDownTest() : cli_(HOST, PORT) {}
  11915. virtual void SetUp() {
  11916. t_ = thread([&]() {
  11917. svr_.bind_to_any_port(HOST);
  11918. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11919. ASSERT_TRUE(svr_.listen_after_bind());
  11920. });
  11921. svr_.wait_until_ready();
  11922. }
  11923. virtual void TearDown() {
  11924. svr_.stop();
  11925. t_.join();
  11926. }
  11927. Client cli_;
  11928. Server svr_;
  11929. thread t_;
  11930. };
  11931. TEST_F(ServerUpDownTest, QuickStartStop) {
  11932. // Should not crash, especially when run with
  11933. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11934. }
  11935. class PayloadMaxLengthTest : public ::testing::Test {
  11936. protected:
  11937. PayloadMaxLengthTest()
  11938. : cli_(HOST, PORT)
  11939. #ifdef CPPHTTPLIB_SSL_ENABLED
  11940. ,
  11941. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11942. #endif
  11943. {
  11944. #ifdef CPPHTTPLIB_SSL_ENABLED
  11945. cli_.enable_server_certificate_verification(false);
  11946. #endif
  11947. }
  11948. virtual void SetUp() {
  11949. svr_.set_payload_max_length(8);
  11950. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11951. res.set_content("test", "text/plain");
  11952. });
  11953. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11954. svr_.wait_until_ready();
  11955. }
  11956. virtual void TearDown() {
  11957. svr_.stop();
  11958. t_.join();
  11959. }
  11960. #ifdef CPPHTTPLIB_SSL_ENABLED
  11961. SSLClient cli_;
  11962. SSLServer svr_;
  11963. #else
  11964. Client cli_;
  11965. Server svr_;
  11966. #endif
  11967. thread t_;
  11968. };
  11969. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11970. auto res = cli_.Post("/test", "123456789", "text/plain");
  11971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11972. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11973. res = cli_.Post("/test", "12345678", "text/plain");
  11974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11975. EXPECT_EQ(StatusCode::OK_200, res->status);
  11976. }
  11977. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11978. // Test chunked encoding with payload exceeding the 8-byte limit
  11979. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11980. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11982. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11983. }
  11984. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11985. // Test chunked encoding with payload within the 8-byte limit
  11986. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11987. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11989. EXPECT_EQ(StatusCode::OK_200, res->status);
  11990. }
  11991. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11992. // Test using send_request to send chunked data exceeding payload limit
  11993. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11994. "Host: " +
  11995. std::string(HOST) + ":" + std::to_string(PORT) +
  11996. "\r\n"
  11997. "Transfer-Encoding: chunked\r\n"
  11998. "Connection: close\r\n"
  11999. "\r\n"
  12000. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12001. "0123456789\r\n"
  12002. "0\r\n" // End chunk
  12003. "\r\n";
  12004. std::string response;
  12005. bool result = send_request(1, chunked_request, &response);
  12006. if (!result) {
  12007. // If send_request fails, it might be because the server closed the
  12008. // connection due to payload limit enforcement, which is acceptable
  12009. SUCCEED()
  12010. << "Server rejected oversized chunked request (connection closed)";
  12011. } else {
  12012. // If we got a response, check if it's an error response or connection was
  12013. // closed early Short response length indicates connection was closed due to
  12014. // payload limit
  12015. if (response.length() <= 10) {
  12016. SUCCEED() << "Server closed connection for oversized chunked request";
  12017. } else {
  12018. // Check for error status codes
  12019. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12020. response.find("Payload Too Large") != std::string::npos ||
  12021. response.find("400") != std::string::npos);
  12022. }
  12023. }
  12024. }
  12025. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  12026. // Test request without Content-Length header exceeding payload limit
  12027. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12028. "Host: " +
  12029. std::string(HOST) + ":" +
  12030. std::to_string(PORT) +
  12031. "\r\n"
  12032. "Connection: close\r\n"
  12033. "\r\n";
  12034. // Add payload exceeding the 8-byte limit
  12035. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  12036. request_without_content_length += large_payload;
  12037. std::string response;
  12038. bool result = send_request(1, request_without_content_length, &response);
  12039. if (!result) {
  12040. // If send_request fails, server likely closed connection due to payload
  12041. // limit
  12042. SUCCEED() << "Server rejected oversized request without Content-Length "
  12043. "(connection closed)";
  12044. } else {
  12045. // Check if server responded with error or closed connection early
  12046. if (response.length() <= 10) {
  12047. SUCCEED() << "Server closed connection for oversized request without "
  12048. "Content-Length";
  12049. } else {
  12050. // Check for error status codes
  12051. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12052. response.find("Payload Too Large") != std::string::npos ||
  12053. response.find("400") != std::string::npos);
  12054. }
  12055. }
  12056. }
  12057. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  12058. // Test request without Content-Length header within payload limit
  12059. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12060. "Host: " +
  12061. std::string(HOST) + ":" +
  12062. std::to_string(PORT) +
  12063. "\r\n"
  12064. "Connection: close\r\n"
  12065. "\r\n";
  12066. // Add payload within the 8-byte limit
  12067. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12068. request_without_content_length += small_payload;
  12069. std::string response;
  12070. bool result = send_request(1, request_without_content_length, &response);
  12071. // For requests without Content-Length, the server may have different behavior
  12072. // The key is that it should not reject due to payload limit for small
  12073. // payloads
  12074. if (result) {
  12075. // Check for any HTTP response (success or error, but not connection closed)
  12076. if (response.length() > 10) {
  12077. SUCCEED()
  12078. << "Server processed request without Content-Length within limit";
  12079. } else {
  12080. // Short response might indicate connection closed, which is acceptable
  12081. SUCCEED() << "Server closed connection for request without "
  12082. "Content-Length (acceptable behavior)";
  12083. }
  12084. } else {
  12085. // Connection failure might be due to protocol requirements
  12086. SUCCEED() << "Connection issue with request without Content-Length "
  12087. "(environment-specific)";
  12088. }
  12089. }
  12090. class LargePayloadMaxLengthTest : public ::testing::Test {
  12091. protected:
  12092. LargePayloadMaxLengthTest()
  12093. : cli_(HOST, PORT)
  12094. #ifdef CPPHTTPLIB_SSL_ENABLED
  12095. ,
  12096. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12097. #endif
  12098. {
  12099. #ifdef CPPHTTPLIB_SSL_ENABLED
  12100. cli_.enable_server_certificate_verification(false);
  12101. #endif
  12102. }
  12103. virtual void SetUp() {
  12104. // Set 10MB payload limit
  12105. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12106. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12107. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12108. res.set_content("Large payload test", "text/plain");
  12109. });
  12110. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12111. svr_.wait_until_ready();
  12112. }
  12113. virtual void TearDown() {
  12114. svr_.stop();
  12115. t_.join();
  12116. }
  12117. #ifdef CPPHTTPLIB_SSL_ENABLED
  12118. SSLClient cli_;
  12119. SSLServer svr_;
  12120. #else
  12121. Client cli_;
  12122. Server svr_;
  12123. #endif
  12124. thread t_;
  12125. };
  12126. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12127. // Test chunked encoding with payload within 10MB limit
  12128. std::string medium_payload(5 * 1024 * 1024,
  12129. 'A'); // 5MB payload, within 10MB limit
  12130. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12132. EXPECT_EQ(StatusCode::OK_200, res->status);
  12133. }
  12134. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12135. // Test chunked encoding with payload exceeding 10MB limit
  12136. std::string large_payload(12 * 1024 * 1024,
  12137. 'B'); // 12MB payload, exceeds 10MB limit
  12138. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12139. // Server may either return 413 or close the connection
  12140. if (res) {
  12141. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12142. } else {
  12143. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12144. }
  12145. }
  12146. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12147. // Test request without Content-Length header within 10MB limit
  12148. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12149. "Host: " +
  12150. std::string(HOST) + ":" +
  12151. std::to_string(PORT) +
  12152. "\r\n"
  12153. "Connection: close\r\n"
  12154. "\r\n";
  12155. // Add 1MB payload (within 10MB limit)
  12156. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12157. request_without_content_length += medium_payload;
  12158. std::string response;
  12159. bool result = send_request(5, request_without_content_length, &response);
  12160. if (result) {
  12161. // Should get a proper HTTP response for payloads within limit
  12162. if (response.length() > 10) {
  12163. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12164. "10MB limit";
  12165. } else {
  12166. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12167. "Content-Length)";
  12168. }
  12169. } else {
  12170. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12171. }
  12172. }
  12173. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12174. // Test request without Content-Length header exceeding 10MB limit
  12175. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12176. "Host: " +
  12177. std::string(HOST) + ":" +
  12178. std::to_string(PORT) +
  12179. "\r\n"
  12180. "Connection: close\r\n"
  12181. "\r\n";
  12182. // Add 12MB payload (exceeds 10MB limit)
  12183. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12184. request_without_content_length += large_payload;
  12185. std::string response;
  12186. bool result = send_request(10, request_without_content_length, &response);
  12187. if (!result) {
  12188. // Server should close connection due to payload limit
  12189. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12190. "(connection closed)";
  12191. } else {
  12192. // Check for error response
  12193. if (response.length() <= 10) {
  12194. SUCCEED()
  12195. << "Server closed connection for 12MB request exceeding 10MB limit";
  12196. } else {
  12197. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12198. response.find("Payload Too Large") != std::string::npos ||
  12199. response.find("400") != std::string::npos);
  12200. }
  12201. }
  12202. }
  12203. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12204. Server svr;
  12205. svr.Get("/", [](const Request &, Response &res) {
  12206. // Claims far more than it sends, then drops the connection.
  12207. res.set_content_provider(size_t(1) << 41, "text/plain",
  12208. [](size_t, size_t, DataSink &sink) {
  12209. sink.write("abc", 3);
  12210. return false;
  12211. });
  12212. });
  12213. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12214. auto se = detail::scope_exit([&] {
  12215. svr.stop();
  12216. thread.join();
  12217. ASSERT_FALSE(svr.is_running());
  12218. });
  12219. svr.wait_until_ready();
  12220. Client cli(HOST, PORT);
  12221. cli.set_payload_max_length(0);
  12222. EXPECT_FALSE(cli.Get("/"));
  12223. }
  12224. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12225. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12226. // path.
  12227. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12228. Server svr;
  12229. const size_t LIMIT = 64 * 1024; // 64KB
  12230. svr.set_payload_max_length(LIMIT);
  12231. size_t total = 0;
  12232. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12233. const ContentReader &content_reader) {
  12234. content_reader([&](const char * /*data*/, size_t len) {
  12235. total += len;
  12236. return true;
  12237. });
  12238. res.status = 200;
  12239. res.set_content("stream_ok", "text/plain");
  12240. });
  12241. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12242. auto se = detail::scope_exit([&] {
  12243. svr.stop();
  12244. thread.join();
  12245. ASSERT_FALSE(svr.is_running());
  12246. });
  12247. svr.wait_until_ready();
  12248. // Prepare 256KB raw data and gzip-compress it
  12249. std::string raw(256 * 1024, 'A');
  12250. std::string gz;
  12251. {
  12252. z_stream zs{};
  12253. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12254. Z_DEFAULT_STRATEGY);
  12255. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12256. zs.avail_in = static_cast<uInt>(raw.size());
  12257. char outbuf[4096];
  12258. int ret;
  12259. do {
  12260. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12261. zs.avail_out = sizeof(outbuf);
  12262. ret = deflate(&zs, Z_FINISH);
  12263. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12264. } while (ret != Z_STREAM_END);
  12265. deflateEnd(&zs);
  12266. }
  12267. Client cli(HOST, PORT);
  12268. cli.set_connection_timeout(std::chrono::seconds(5));
  12269. Headers headers = {{"Content-Encoding", "gzip"}};
  12270. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12271. "application/octet-stream");
  12272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12273. // Server must reject oversized decompressed payloads with 413.
  12274. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12275. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12276. EXPECT_LE(total, LIMIT);
  12277. }
  12278. #ifndef CPPHTTPLIB_SSL_ENABLED
  12279. // For a request with neither Content-Length nor Transfer-Encoding, the
  12280. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12281. // compressed wire bytes straight to the ContentReader without ever routing
  12282. // them through the decompressor, so payload_max_length_ only bounded the
  12283. // compressed size on the wire, not the decompressed size.
  12284. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12285. Server svr;
  12286. const size_t LIMIT = 64 * 1024; // 64KB
  12287. svr.set_payload_max_length(LIMIT);
  12288. size_t total = 0;
  12289. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12290. const ContentReader &content_reader) {
  12291. content_reader([&](const char * /*data*/, size_t len) {
  12292. total += len;
  12293. return true;
  12294. });
  12295. res.status = 200;
  12296. res.set_content("stream_ok", "text/plain");
  12297. });
  12298. auto port = svr.bind_to_any_port(HOST);
  12299. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12300. auto se = detail::scope_exit([&] {
  12301. svr.stop();
  12302. thread.join();
  12303. ASSERT_FALSE(svr.is_running());
  12304. });
  12305. svr.wait_until_ready();
  12306. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12307. // StreamingGzipDecompression test above.
  12308. std::string raw(256 * 1024, 'A');
  12309. std::string gz;
  12310. {
  12311. httplib::detail::gzip_compressor compressor;
  12312. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12313. [&](const char *chunk, size_t len) {
  12314. gz.append(chunk, len);
  12315. return true;
  12316. });
  12317. ASSERT_TRUE(result);
  12318. }
  12319. // Send the gzip body over raw TCP with neither Content-Length nor
  12320. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12321. // kicks in.
  12322. std::string req = "POST /stream HTTP/1.1\r\n"
  12323. "Host: " +
  12324. std::string(HOST) + ":" + std::to_string(port) +
  12325. "\r\n"
  12326. "Content-Encoding: gzip\r\n"
  12327. "Connection: close\r\n"
  12328. "\r\n" +
  12329. gz;
  12330. std::string response;
  12331. ASSERT_TRUE(send_request(5, req, &response, port));
  12332. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12333. EXPECT_LE(total, LIMIT);
  12334. }
  12335. #endif
  12336. #endif
  12337. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12338. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12339. // the payload must be passed through untouched instead of being rejected.
  12340. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12341. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12342. Server svr;
  12343. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12344. res.set_content(body, "image/jpeg");
  12345. res.set_header("Content-Encoding", "UTF-8");
  12346. });
  12347. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12348. res.set_content(body, "image/jpeg");
  12349. res.set_header("Content-Encoding", "identity");
  12350. });
  12351. svr.Post("/echo", [](const Request &req, Response &res) {
  12352. res.set_content(req.body, "image/jpeg");
  12353. });
  12354. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12355. auto se = detail::scope_exit([&] {
  12356. svr.stop();
  12357. t.join();
  12358. ASSERT_FALSE(svr.is_running());
  12359. });
  12360. svr.wait_until_ready();
  12361. Client cli(HOST, PORT);
  12362. {
  12363. auto res = cli.Get("/image");
  12364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12365. EXPECT_EQ(StatusCode::OK_200, res->status);
  12366. EXPECT_EQ(body, res->body);
  12367. }
  12368. {
  12369. auto res = cli.Get("/identity");
  12370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12371. EXPECT_EQ(StatusCode::OK_200, res->status);
  12372. EXPECT_EQ(body, res->body);
  12373. }
  12374. {
  12375. // The same applies to a request body reaching the server.
  12376. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12377. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12379. EXPECT_EQ(StatusCode::OK_200, res->status);
  12380. EXPECT_EQ(body, res->body);
  12381. }
  12382. }
  12383. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12384. // gzip-encoded response even when the build has no zlib support.
  12385. static const char GZIPPED_HELLO_WORLD[] = {
  12386. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12387. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12388. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12389. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12390. // A content coding is a whole token, not something the field value merely
  12391. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12392. // as "fibre" look like Brotli, and turned a multi-coding value like
  12393. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12394. // it was never meant to see.
  12395. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12396. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12397. Server svr;
  12398. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12399. res.set_content(body, "image/jpeg");
  12400. res.set_header("Content-Encoding", "fibre");
  12401. });
  12402. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12403. res.set_content(body, "image/jpeg");
  12404. res.set_header("Content-Encoding", "gzip, br");
  12405. });
  12406. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12407. res.set_content(body, "image/jpeg");
  12408. res.set_header("Content-Encoding", "x-zstd-ish");
  12409. });
  12410. auto port = svr.bind_to_any_port(HOST);
  12411. thread t = thread([&]() { svr.listen_after_bind(); });
  12412. auto se = detail::scope_exit([&] {
  12413. svr.stop();
  12414. t.join();
  12415. ASSERT_FALSE(svr.is_running());
  12416. });
  12417. svr.wait_until_ready();
  12418. Client cli(HOST, port);
  12419. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12420. auto res = cli.Get(path);
  12421. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12422. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12423. // Not a coding we recognize, so the payload comes back untouched
  12424. EXPECT_EQ(body, res->body) << path;
  12425. }
  12426. }
  12427. // A content coding cpp-httplib recognizes but was not built with must be
  12428. // reported as such. Handing the still-compressed payload back to the caller
  12429. // would silently corrupt it.
  12430. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12431. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12432. Server svr;
  12433. // "image/jpeg" keeps the server from applying a content coding of its own,
  12434. // so the hand-crafted Content-Encoding below survives.
  12435. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12436. res.set_content(gzipped, "image/jpeg");
  12437. res.set_header("Content-Encoding", "gzip");
  12438. });
  12439. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12440. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12441. res.set_content(gzipped, "image/jpeg");
  12442. res.set_header("Content-Encoding", "GZIP");
  12443. });
  12444. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12445. auto se = detail::scope_exit([&] {
  12446. svr.stop();
  12447. t.join();
  12448. ASSERT_FALSE(svr.is_running());
  12449. });
  12450. svr.wait_until_ready();
  12451. Client cli(HOST, PORT);
  12452. {
  12453. auto res = cli.Get("/gzipped");
  12454. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12456. EXPECT_EQ("Hello World!", res->body);
  12457. #else
  12458. ASSERT_FALSE(res);
  12459. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12460. #endif
  12461. }
  12462. {
  12463. // open_stream() must behave the same way.
  12464. auto handle = cli.open_stream("GET", "/gzipped");
  12465. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12466. ASSERT_TRUE(handle.is_valid());
  12467. std::string received;
  12468. char buf[256];
  12469. ssize_t n;
  12470. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12471. received.append(buf, static_cast<size_t>(n));
  12472. }
  12473. EXPECT_EQ("Hello World!", received);
  12474. #else
  12475. EXPECT_FALSE(handle.is_valid());
  12476. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12477. #endif
  12478. }
  12479. {
  12480. // A differently-cased coding must not be mistaken for an unknown one, or
  12481. // the body would be handed back still compressed.
  12482. auto res = cli.Get("/gzipped-uppercase");
  12483. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12485. EXPECT_EQ("Hello World!", res->body);
  12486. #else
  12487. ASSERT_FALSE(res);
  12488. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12489. #endif
  12490. }
  12491. }
  12492. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12493. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12494. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12495. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12496. // body a second time and appending a second Content-Encoding field line, so
  12497. // clients that decode one coding per listed value handed back raw gzip bytes.
  12498. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12499. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12500. Server svr;
  12501. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12502. // keeps the server from applying a coding of its own.
  12503. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12504. res.set_content(gzipped, "text/plain");
  12505. res.set_header("Content-Encoding", "gzip");
  12506. });
  12507. auto port = svr.bind_to_any_port(HOST);
  12508. thread t = thread([&]() { svr.listen_after_bind(); });
  12509. auto se = detail::scope_exit([&] {
  12510. svr.stop();
  12511. t.join();
  12512. ASSERT_FALSE(svr.is_running());
  12513. });
  12514. svr.wait_until_ready();
  12515. Client cli(HOST, port);
  12516. Headers headers = {{"Accept-Encoding", "gzip"}};
  12517. auto res = cli.Get("/pre-gzipped", headers);
  12518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12519. EXPECT_EQ(StatusCode::OK_200, res->status);
  12520. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12521. EXPECT_EQ("Hello World!", res->body);
  12522. }
  12523. // A chunked provider settles its coding where the headers are written and
  12524. // reuses it at write time. Both ends of that have to hold: a handler's own
  12525. // Content-Encoding suppresses the coding, and a response without one is still
  12526. // compressed as it always was.
  12527. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12528. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12529. const std::string plain = "Hello World! Hello World! Hello World!";
  12530. Server svr;
  12531. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12532. res.set_header("Content-Encoding", "gzip");
  12533. res.set_chunked_content_provider(
  12534. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12535. sink.write(gzipped.data(), gzipped.size());
  12536. sink.done();
  12537. return true;
  12538. });
  12539. });
  12540. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12541. res.set_chunked_content_provider(
  12542. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12543. sink.write(plain.data(), plain.size());
  12544. sink.done();
  12545. return true;
  12546. });
  12547. });
  12548. auto port = svr.bind_to_any_port(HOST);
  12549. thread t = thread([&]() { svr.listen_after_bind(); });
  12550. auto se = detail::scope_exit([&] {
  12551. svr.stop();
  12552. t.join();
  12553. ASSERT_FALSE(svr.is_running());
  12554. });
  12555. svr.wait_until_ready();
  12556. Client cli(HOST, port);
  12557. Headers headers = {{"Accept-Encoding", "gzip"}};
  12558. {
  12559. auto res = cli.Get("/pre-gzipped", headers);
  12560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12561. EXPECT_EQ(StatusCode::OK_200, res->status);
  12562. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12563. EXPECT_EQ("Hello World!", res->body);
  12564. }
  12565. {
  12566. auto res = cli.Get("/negotiated", headers);
  12567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12568. EXPECT_EQ(StatusCode::OK_200, res->status);
  12569. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12570. EXPECT_EQ(plain, res->body);
  12571. }
  12572. }
  12573. #endif
  12574. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12575. // the same message as the comma-joined one, so both have to be read the same
  12576. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12577. // single gzip coding, and a body the sender says was encoded twice was handed
  12578. // back after one pass, still compressed but presented as decoded.
  12579. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12580. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12581. Server svr;
  12582. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12583. res.set_content(body, "image/jpeg");
  12584. res.headers.emplace("Content-Encoding", "gzip");
  12585. res.headers.emplace("Content-Encoding", "gzip");
  12586. });
  12587. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12588. res.set_content(body, "image/jpeg");
  12589. res.set_header("Content-Encoding", "gzip, gzip");
  12590. });
  12591. auto port = svr.bind_to_any_port(HOST);
  12592. thread t = thread([&]() { svr.listen_after_bind(); });
  12593. auto se = detail::scope_exit([&] {
  12594. svr.stop();
  12595. t.join();
  12596. ASSERT_FALSE(svr.is_running());
  12597. });
  12598. svr.wait_until_ready();
  12599. Client cli(HOST, port);
  12600. // Two codings is not something cpp-httplib decodes, so both representations
  12601. // take the pass-through path rather than one of them being gunzipped once.
  12602. for (const char *path : {"/split", "/joined"}) {
  12603. auto res = cli.Get(path);
  12604. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12605. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12606. EXPECT_EQ(body, res->body) << path;
  12607. }
  12608. }
  12609. // Regression test for DoS vulnerability: a malicious server sending a response
  12610. // without Content-Length header must not cause unbounded memory consumption on
  12611. // the client side. The client should stop reading after a reasonable limit,
  12612. // similar to the server-side set_payload_max_length protection.
  12613. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12614. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12615. #ifndef _WIN32
  12616. signal(SIGPIPE, SIG_IGN);
  12617. #endif
  12618. auto server_thread = std::thread([] {
  12619. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12620. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12621. default_socket_options(srv);
  12622. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12623. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12624. sockaddr_in addr{};
  12625. addr.sin_family = AF_INET;
  12626. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12627. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12628. int opt = 1;
  12629. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12630. #ifdef _WIN32
  12631. reinterpret_cast<const char *>(&opt),
  12632. #else
  12633. &opt,
  12634. #endif
  12635. sizeof(opt));
  12636. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12637. ::listen(srv, 1);
  12638. sockaddr_in cli_addr{};
  12639. socklen_t cli_len = sizeof(cli_addr);
  12640. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12641. if (cli != INVALID_SOCKET) {
  12642. char buf[4096];
  12643. ::recv(cli, buf, sizeof(buf), 0);
  12644. // Malicious response: no Content-Length, no chunked encoding
  12645. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12646. "Connection: close\r\n"
  12647. "\r\n";
  12648. ::send(cli,
  12649. #ifdef _WIN32
  12650. static_cast<const char *>(response_header.c_str()),
  12651. static_cast<int>(response_header.size()),
  12652. #else
  12653. response_header.c_str(), response_header.size(),
  12654. #endif
  12655. 0);
  12656. // Send 10MB of data
  12657. std::string chunk(64 * 1024, 'A');
  12658. size_t total_sent = 0;
  12659. while (total_sent < MALICIOUS_DATA_SIZE) {
  12660. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12661. auto sent = ::send(cli,
  12662. #ifdef _WIN32
  12663. static_cast<const char *>(chunk.c_str()),
  12664. static_cast<int>(to_send),
  12665. #else
  12666. chunk.c_str(), to_send,
  12667. #endif
  12668. 0);
  12669. if (sent <= 0) break;
  12670. total_sent += static_cast<size_t>(sent);
  12671. }
  12672. detail::close_socket(cli);
  12673. }
  12674. detail::close_socket(srv);
  12675. });
  12676. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12677. size_t total_read = 0;
  12678. {
  12679. Client cli("127.0.0.1", PORT + 2);
  12680. cli.set_read_timeout(5, 0);
  12681. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12682. auto stream = cli.open_stream("GET", "/malicious");
  12683. ASSERT_TRUE(stream.is_valid());
  12684. char buffer[64 * 1024];
  12685. ssize_t n;
  12686. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12687. total_read += static_cast<size_t>(n);
  12688. }
  12689. } // StreamHandle and Client destroyed here, closing the socket
  12690. server_thread.join();
  12691. // With set_payload_max_length, the client must stop reading before consuming
  12692. // all 10MB. The read loop should be cut off at or near the configured limit.
  12693. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12694. << "Client read " << total_read << " bytes, exceeding the configured "
  12695. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12696. }
  12697. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12698. // the entire response body without truncation.
  12699. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12700. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12701. #ifndef _WIN32
  12702. signal(SIGPIPE, SIG_IGN);
  12703. #endif
  12704. auto server_thread = std::thread([] {
  12705. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12706. default_socket_options(srv);
  12707. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12708. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12709. sockaddr_in addr{};
  12710. addr.sin_family = AF_INET;
  12711. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12712. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12713. int opt = 1;
  12714. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12715. #ifdef _WIN32
  12716. reinterpret_cast<const char *>(&opt),
  12717. #else
  12718. &opt,
  12719. #endif
  12720. sizeof(opt));
  12721. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12722. ::listen(srv, 1);
  12723. sockaddr_in cli_addr{};
  12724. socklen_t cli_len = sizeof(cli_addr);
  12725. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12726. if (cli != INVALID_SOCKET) {
  12727. char buf[4096];
  12728. ::recv(cli, buf, sizeof(buf), 0);
  12729. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12730. "Connection: close\r\n"
  12731. "\r\n";
  12732. ::send(cli,
  12733. #ifdef _WIN32
  12734. static_cast<const char *>(response_header.c_str()),
  12735. static_cast<int>(response_header.size()),
  12736. #else
  12737. response_header.c_str(), response_header.size(),
  12738. #endif
  12739. 0);
  12740. std::string chunk(64 * 1024, 'A');
  12741. size_t total_sent = 0;
  12742. while (total_sent < DATA_SIZE) {
  12743. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12744. auto sent = ::send(cli,
  12745. #ifdef _WIN32
  12746. static_cast<const char *>(chunk.c_str()),
  12747. static_cast<int>(to_send),
  12748. #else
  12749. chunk.c_str(), to_send,
  12750. #endif
  12751. 0);
  12752. if (sent <= 0) break;
  12753. total_sent += static_cast<size_t>(sent);
  12754. }
  12755. #ifdef _WIN32
  12756. ::shutdown(cli, SD_SEND);
  12757. #else
  12758. ::shutdown(cli, SHUT_WR);
  12759. #endif
  12760. // Drain until the client closes its end, ensuring all data is delivered
  12761. char drain[1024];
  12762. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12763. detail::close_socket(cli);
  12764. }
  12765. detail::close_socket(srv);
  12766. });
  12767. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12768. size_t total_read = 0;
  12769. {
  12770. Client cli("127.0.0.1", PORT + 2);
  12771. cli.set_read_timeout(5, 0);
  12772. cli.set_payload_max_length(0); // 0 means no limit
  12773. auto stream = cli.open_stream("GET", "/data");
  12774. ASSERT_TRUE(stream.is_valid());
  12775. char buffer[64 * 1024];
  12776. ssize_t n;
  12777. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12778. total_read += static_cast<size_t>(n);
  12779. }
  12780. }
  12781. server_thread.join();
  12782. EXPECT_EQ(total_read, DATA_SIZE)
  12783. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12784. << " bytes without truncation, but only read " << total_read << " bytes.";
  12785. }
  12786. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12787. // enormous Content-Length must not cause the client to pre-allocate a huge
  12788. // response body buffer. The reservation is capped at payload_max_length_, and
  12789. // the read itself fails when the body exceeds the limit.
  12790. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12791. #ifndef _WIN32
  12792. signal(SIGPIPE, SIG_IGN);
  12793. #endif
  12794. auto server_thread = std::thread([] {
  12795. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12796. default_socket_options(srv);
  12797. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12798. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12799. sockaddr_in addr{};
  12800. addr.sin_family = AF_INET;
  12801. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12802. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12803. int opt = 1;
  12804. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12805. #ifdef _WIN32
  12806. reinterpret_cast<const char *>(&opt),
  12807. #else
  12808. &opt,
  12809. #endif
  12810. sizeof(opt));
  12811. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12812. ::listen(srv, 1);
  12813. sockaddr_in cli_addr{};
  12814. socklen_t cli_len = sizeof(cli_addr);
  12815. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12816. if (cli != INVALID_SOCKET) {
  12817. char buf[4096];
  12818. ::recv(cli, buf, sizeof(buf), 0);
  12819. // Malicious response: claim a 20GB body but send only a tiny payload.
  12820. std::string response = "HTTP/1.1 200 OK\r\n"
  12821. "Content-Length: 20000000000\r\n"
  12822. "\r\n"
  12823. "abc";
  12824. ::send(cli,
  12825. #ifdef _WIN32
  12826. static_cast<const char *>(response.c_str()),
  12827. static_cast<int>(response.size()),
  12828. #else
  12829. response.c_str(), response.size(),
  12830. #endif
  12831. 0);
  12832. detail::close_socket(cli);
  12833. }
  12834. detail::close_socket(srv);
  12835. });
  12836. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12837. {
  12838. Client cli("127.0.0.1", PORT + 2);
  12839. cli.set_read_timeout(5, 0);
  12840. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12841. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12842. // (server claims more bytes than payload_max_length permits), but it must
  12843. // not exhaust memory before getting there.
  12844. auto res = cli.Get("/malicious");
  12845. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12846. }
  12847. server_thread.join();
  12848. }
  12849. // Verify that content_receiver bypasses the default payload_max_length,
  12850. // allowing streaming downloads larger than 100MB without requiring an explicit
  12851. // set_payload_max_length call.
  12852. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12853. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12854. #ifndef _WIN32
  12855. signal(SIGPIPE, SIG_IGN);
  12856. #endif
  12857. auto server_thread = std::thread([] {
  12858. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12859. default_socket_options(srv);
  12860. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12861. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12862. sockaddr_in addr{};
  12863. addr.sin_family = AF_INET;
  12864. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12865. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12866. int opt = 1;
  12867. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12868. #ifdef _WIN32
  12869. reinterpret_cast<const char *>(&opt),
  12870. #else
  12871. &opt,
  12872. #endif
  12873. sizeof(opt));
  12874. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12875. ::listen(srv, 1);
  12876. sockaddr_in cli_addr{};
  12877. socklen_t cli_len = sizeof(cli_addr);
  12878. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12879. if (cli != INVALID_SOCKET) {
  12880. char buf[4096];
  12881. ::recv(cli, buf, sizeof(buf), 0);
  12882. // Response with Content-Length larger than default 100MB limit
  12883. auto content_length = std::to_string(DATA_SIZE);
  12884. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12885. "Content-Length: " +
  12886. content_length +
  12887. "\r\n"
  12888. "Connection: close\r\n"
  12889. "\r\n";
  12890. ::send(cli,
  12891. #ifdef _WIN32
  12892. static_cast<const char *>(response_header.c_str()),
  12893. static_cast<int>(response_header.size()),
  12894. #else
  12895. response_header.c_str(), response_header.size(),
  12896. #endif
  12897. 0);
  12898. std::string chunk(64 * 1024, 'A');
  12899. size_t total_sent = 0;
  12900. while (total_sent < DATA_SIZE) {
  12901. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12902. auto sent = ::send(cli,
  12903. #ifdef _WIN32
  12904. static_cast<const char *>(chunk.c_str()),
  12905. static_cast<int>(to_send),
  12906. #else
  12907. chunk.c_str(), to_send,
  12908. #endif
  12909. 0);
  12910. if (sent <= 0) break;
  12911. total_sent += static_cast<size_t>(sent);
  12912. }
  12913. detail::close_socket(cli);
  12914. }
  12915. detail::close_socket(srv);
  12916. });
  12917. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12918. size_t total_received = 0;
  12919. {
  12920. Client cli("127.0.0.1", PORT + 2);
  12921. cli.set_read_timeout(10, 0);
  12922. // Do NOT call set_payload_max_length — use the default 100MB limit
  12923. auto res =
  12924. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12925. total_received += data_length;
  12926. return true;
  12927. });
  12928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12929. EXPECT_EQ(StatusCode::OK_200, res->status);
  12930. }
  12931. server_thread.join();
  12932. EXPECT_EQ(total_received, DATA_SIZE)
  12933. << "With content_receiver, the client should read all " << DATA_SIZE
  12934. << " bytes despite the default 100MB payload_max_length, but only read "
  12935. << total_received << " bytes.";
  12936. }
  12937. // Verify that an explicit set_payload_max_length smaller than the response is
  12938. // enforced even when a content_receiver is used.
  12939. TEST(ClientVulnerabilityTest,
  12940. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12941. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12942. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12943. #ifndef _WIN32
  12944. signal(SIGPIPE, SIG_IGN);
  12945. #endif
  12946. auto server_thread = std::thread([] {
  12947. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12948. default_socket_options(srv);
  12949. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12950. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12951. sockaddr_in addr{};
  12952. addr.sin_family = AF_INET;
  12953. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12954. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12955. int opt = 1;
  12956. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12957. #ifdef _WIN32
  12958. reinterpret_cast<const char *>(&opt),
  12959. #else
  12960. &opt,
  12961. #endif
  12962. sizeof(opt));
  12963. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12964. ::listen(srv, 1);
  12965. sockaddr_in cli_addr{};
  12966. socklen_t cli_len = sizeof(cli_addr);
  12967. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12968. if (cli != INVALID_SOCKET) {
  12969. char buf[4096];
  12970. ::recv(cli, buf, sizeof(buf), 0);
  12971. auto content_length = std::to_string(DATA_SIZE);
  12972. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12973. "Content-Length: " +
  12974. content_length +
  12975. "\r\n"
  12976. "Connection: close\r\n"
  12977. "\r\n";
  12978. ::send(cli,
  12979. #ifdef _WIN32
  12980. static_cast<const char *>(response_header.c_str()),
  12981. static_cast<int>(response_header.size()),
  12982. #else
  12983. response_header.c_str(), response_header.size(),
  12984. #endif
  12985. 0);
  12986. std::string chunk(64 * 1024, 'A');
  12987. size_t total_sent = 0;
  12988. while (total_sent < DATA_SIZE) {
  12989. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12990. auto sent = ::send(cli,
  12991. #ifdef _WIN32
  12992. static_cast<const char *>(chunk.c_str()),
  12993. static_cast<int>(to_send),
  12994. #else
  12995. chunk.c_str(), to_send,
  12996. #endif
  12997. 0);
  12998. if (sent <= 0) break;
  12999. total_sent += static_cast<size_t>(sent);
  13000. }
  13001. detail::close_socket(cli);
  13002. }
  13003. detail::close_socket(srv);
  13004. });
  13005. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13006. size_t total_received = 0;
  13007. {
  13008. Client cli("127.0.0.1", PORT + 2);
  13009. cli.set_read_timeout(10, 0);
  13010. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13011. auto res =
  13012. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13013. total_received += data_length;
  13014. return true;
  13015. });
  13016. // Should fail because 200MB exceeds the explicit 150MB limit
  13017. EXPECT_FALSE(res);
  13018. }
  13019. server_thread.join();
  13020. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13021. << "Client with content_receiver should respect the explicit "
  13022. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13023. << total_received << " bytes.";
  13024. }
  13025. // Verify that an explicit set_payload_max_length larger than the response
  13026. // allows the content_receiver to read all data successfully.
  13027. TEST(ClientVulnerabilityTest,
  13028. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13029. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13030. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13031. #ifndef _WIN32
  13032. signal(SIGPIPE, SIG_IGN);
  13033. #endif
  13034. auto server_thread = std::thread([] {
  13035. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13036. default_socket_options(srv);
  13037. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13038. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13039. sockaddr_in addr{};
  13040. addr.sin_family = AF_INET;
  13041. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13042. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13043. int opt = 1;
  13044. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13045. #ifdef _WIN32
  13046. reinterpret_cast<const char *>(&opt),
  13047. #else
  13048. &opt,
  13049. #endif
  13050. sizeof(opt));
  13051. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13052. ::listen(srv, 1);
  13053. sockaddr_in cli_addr{};
  13054. socklen_t cli_len = sizeof(cli_addr);
  13055. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13056. if (cli != INVALID_SOCKET) {
  13057. char buf[4096];
  13058. ::recv(cli, buf, sizeof(buf), 0);
  13059. auto content_length = std::to_string(DATA_SIZE);
  13060. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13061. "Content-Length: " +
  13062. content_length +
  13063. "\r\n"
  13064. "Connection: close\r\n"
  13065. "\r\n";
  13066. ::send(cli,
  13067. #ifdef _WIN32
  13068. static_cast<const char *>(response_header.c_str()),
  13069. static_cast<int>(response_header.size()),
  13070. #else
  13071. response_header.c_str(), response_header.size(),
  13072. #endif
  13073. 0);
  13074. std::string chunk(64 * 1024, 'A');
  13075. size_t total_sent = 0;
  13076. while (total_sent < DATA_SIZE) {
  13077. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13078. auto sent = ::send(cli,
  13079. #ifdef _WIN32
  13080. static_cast<const char *>(chunk.c_str()),
  13081. static_cast<int>(to_send),
  13082. #else
  13083. chunk.c_str(), to_send,
  13084. #endif
  13085. 0);
  13086. if (sent <= 0) break;
  13087. total_sent += static_cast<size_t>(sent);
  13088. }
  13089. #ifdef _WIN32
  13090. ::shutdown(cli, SD_SEND);
  13091. #else
  13092. ::shutdown(cli, SHUT_WR);
  13093. #endif
  13094. char drain[1024];
  13095. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13096. detail::close_socket(cli);
  13097. }
  13098. detail::close_socket(srv);
  13099. });
  13100. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13101. size_t total_received = 0;
  13102. {
  13103. Client cli("127.0.0.1", PORT + 2);
  13104. cli.set_read_timeout(10, 0);
  13105. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13106. auto res =
  13107. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13108. total_received += data_length;
  13109. return true;
  13110. });
  13111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13112. EXPECT_EQ(StatusCode::OK_200, res->status);
  13113. }
  13114. server_thread.join();
  13115. EXPECT_EQ(total_received, DATA_SIZE)
  13116. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13117. << " bytes (larger than " << DATA_SIZE
  13118. << " bytes response), content_receiver should read all data, but only "
  13119. "read "
  13120. << total_received << " bytes.";
  13121. }
  13122. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13123. // Regression test for "zip bomb" attack on the client side: a malicious server
  13124. // sends a small gzip-compressed response that decompresses to a huge payload.
  13125. // The client must enforce payload_max_length on the decompressed size.
  13126. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13127. constexpr size_t DECOMPRESSED_SIZE =
  13128. 10 * 1024 * 1024; // 10MB after decompression
  13129. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13130. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13131. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13132. std::string compressed;
  13133. {
  13134. httplib::detail::gzip_compressor compressor;
  13135. bool ok =
  13136. compressor.compress(uncompressed.data(), uncompressed.size(),
  13137. /*last=*/true, [&](const char *buf, size_t len) {
  13138. compressed.append(buf, len);
  13139. return true;
  13140. });
  13141. ASSERT_TRUE(ok);
  13142. }
  13143. // Sanity: compressed data should be much smaller than the decompressed size
  13144. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13145. #ifndef _WIN32
  13146. signal(SIGPIPE, SIG_IGN);
  13147. #endif
  13148. // Set up the listening socket in the main thread so the server is guaranteed
  13149. // to be ready before the client connects (eliminates race condition).
  13150. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13151. default_socket_options(srv);
  13152. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13153. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13154. sockaddr_in addr{};
  13155. addr.sin_family = AF_INET;
  13156. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13157. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13158. int opt = 1;
  13159. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13160. #ifdef _WIN32
  13161. reinterpret_cast<const char *>(&opt),
  13162. #else
  13163. &opt,
  13164. #endif
  13165. sizeof(opt));
  13166. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13167. ASSERT_EQ(0, ::listen(srv, 1));
  13168. auto server_thread = std::thread([&compressed, srv] {
  13169. sockaddr_in cli_addr{};
  13170. socklen_t cli_len = sizeof(cli_addr);
  13171. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13172. if (cli != INVALID_SOCKET) {
  13173. // Read the full HTTP request (until \r\n\r\n)
  13174. char buf[4096];
  13175. size_t total = 0;
  13176. while (total < sizeof(buf)) {
  13177. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13178. if (n <= 0) break;
  13179. total += static_cast<size_t>(n);
  13180. // Check for end of headers
  13181. if (total >= 4) {
  13182. std::string req(buf, total);
  13183. if (req.find("\r\n\r\n") != std::string::npos) break;
  13184. }
  13185. }
  13186. // Malicious response: gzip-compressed body, no Content-Length
  13187. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13188. "Content-Encoding: gzip\r\n"
  13189. "Connection: close\r\n"
  13190. "\r\n";
  13191. ::send(cli,
  13192. #ifdef _WIN32
  13193. static_cast<const char *>(response_header.c_str()),
  13194. static_cast<int>(response_header.size()),
  13195. #else
  13196. response_header.c_str(), response_header.size(),
  13197. #endif
  13198. 0);
  13199. // Send the compressed payload (small on the wire, huge when decompressed)
  13200. size_t total_sent = 0;
  13201. while (total_sent < compressed.size()) {
  13202. auto to_send = std::min(compressed.size() - total_sent,
  13203. static_cast<size_t>(64 * 1024));
  13204. auto sent =
  13205. ::send(cli,
  13206. #ifdef _WIN32
  13207. static_cast<const char *>(compressed.c_str() + total_sent),
  13208. static_cast<int>(to_send),
  13209. #else
  13210. compressed.c_str() + total_sent, to_send,
  13211. #endif
  13212. 0);
  13213. if (sent <= 0) break;
  13214. total_sent += static_cast<size_t>(sent);
  13215. }
  13216. detail::close_socket(cli);
  13217. }
  13218. });
  13219. auto se = detail::scope_exit([&] {
  13220. detail::close_socket(srv);
  13221. server_thread.join();
  13222. });
  13223. size_t total_decompressed = 0;
  13224. {
  13225. Client cli("127.0.0.1", PORT + 3);
  13226. cli.set_read_timeout(5, 0);
  13227. cli.set_decompress(true);
  13228. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13229. auto stream = cli.open_stream("GET", "/zipbomb");
  13230. ASSERT_TRUE(stream.is_valid());
  13231. char buffer[64 * 1024];
  13232. ssize_t n;
  13233. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13234. total_decompressed += static_cast<size_t>(n);
  13235. }
  13236. }
  13237. // The decompressed size must be capped by payload_max_length. Without
  13238. // protection, the client would decompress the full 10MB from a tiny
  13239. // compressed payload, enabling a zip bomb DoS attack.
  13240. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13241. << "Client decompressed " << total_decompressed
  13242. << " bytes from a gzip response. The decompressed size should be "
  13243. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13244. }
  13245. #endif
  13246. TEST(HostAndPortPropertiesTest, NoSSL) {
  13247. httplib::Client cli("www.google.com", 1234);
  13248. ASSERT_EQ("www.google.com", cli.host());
  13249. ASSERT_EQ(1234, cli.port());
  13250. }
  13251. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13252. httplib::Client cli("www.google.com:1234");
  13253. ASSERT_EQ("www.google.com", cli.host());
  13254. ASSERT_EQ(1234, cli.port());
  13255. }
  13256. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13257. // Port number that overflows int — should not crash, client becomes invalid
  13258. httplib::Client cli("http://www.google.com:99999999999999999999");
  13259. ASSERT_FALSE(cli.is_valid());
  13260. }
  13261. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13262. // Port 99999 exceeds valid range (1-65535) — should not crash
  13263. httplib::Client cli("http://www.google.com:99999");
  13264. ASSERT_FALSE(cli.is_valid());
  13265. auto res = cli.Get("/");
  13266. EXPECT_FALSE(res);
  13267. EXPECT_EQ(Error::Connection, res.error());
  13268. }
  13269. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13270. httplib::Client cli("http://user:pass@localhost:1234");
  13271. ASSERT_FALSE(cli.is_valid());
  13272. EXPECT_FALSE(cli.Get("/"));
  13273. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13274. }
  13275. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13276. httplib::Client cli("http://www.google.com:80abc");
  13277. ASSERT_FALSE(cli.is_valid());
  13278. }
  13279. #ifdef CPPHTTPLIB_SSL_ENABLED
  13280. TEST(HostAndPortPropertiesTest, SSL) {
  13281. httplib::SSLClient cli("www.google.com");
  13282. ASSERT_EQ("www.google.com", cli.host());
  13283. ASSERT_EQ(443, cli.port());
  13284. }
  13285. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13286. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13287. std::string cert;
  13288. read_file(CA_CERT_FILE, cert);
  13289. httplib::SSLClient httplib_client("www.google.com");
  13290. // Load CA store first time
  13291. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13292. // Load CA store second time (update)
  13293. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13294. // Verify client is still valid and can make connections
  13295. httplib_client.enable_server_certificate_verification(true);
  13296. auto res = httplib_client.Get("/");
  13297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13298. // Google may return 200 or 301 depending on various factors
  13299. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13300. res->status == StatusCode::MovedPermanently_301);
  13301. }
  13302. TEST(SSLClientTest, ServerNameIndication_Online) {
  13303. auto host = "httpbingo.org";
  13304. auto path = std::string{"/get"};
  13305. SSLClient cli(host, 443);
  13306. auto res = cli.Get(path);
  13307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13308. ASSERT_EQ(StatusCode::OK_200, res->status);
  13309. }
  13310. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13311. // Use a site that will cause SSL verification failure due to self-signed cert
  13312. SSLClient cli("self-signed.badssl.com", 443);
  13313. cli.enable_server_certificate_verification(true);
  13314. auto res = cli.Get("/");
  13315. ASSERT_TRUE(!res);
  13316. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13317. // Verify backend error is captured for SSLServerVerification
  13318. // This occurs when certificate verification fails
  13319. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13320. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13321. EXPECT_NE(0UL, res.ssl_backend_error());
  13322. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13323. // For OpenSSL, ssl_error is 0 for verification errors
  13324. EXPECT_EQ(0, res.ssl_error());
  13325. #if !defined(_WIN32) || \
  13326. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13327. // On non-Windows or when Windows Schannel is disabled, the error comes
  13328. // from OpenSSL's verification
  13329. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13330. res.ssl_backend_error());
  13331. #endif
  13332. #endif
  13333. }
  13334. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13335. // Use a site where hostname doesn't match the certificate
  13336. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13337. SSLClient cli("wrong.host.badssl.com", 443);
  13338. cli.enable_server_certificate_verification(true);
  13339. cli.enable_server_hostname_verification(true);
  13340. auto res = cli.Get("/");
  13341. ASSERT_TRUE(!res);
  13342. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13343. // Verify backend error is captured for hostname verification failure
  13344. EXPECT_NE(0UL, res.ssl_backend_error());
  13345. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13346. // For OpenSSL, ssl_error is 0 for verification errors
  13347. EXPECT_EQ(0, res.ssl_error());
  13348. #if !defined(_WIN32) || \
  13349. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13350. // On non-Windows or when Windows Schannel is disabled, the error comes
  13351. // from OpenSSL's hostname verification
  13352. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13353. res.ssl_backend_error());
  13354. #endif
  13355. #endif
  13356. }
  13357. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13358. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13359. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13360. SSLClient cli("www.google.com", 443);
  13361. cli.enable_server_certificate_verification(true);
  13362. auto res = cli.Get("/");
  13363. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13364. }
  13365. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13366. SSLClient cli("www.google.com", 443);
  13367. cli.enable_server_certificate_verification(true);
  13368. cli.enable_windows_certificate_verification(false);
  13369. auto res = cli.Get("/");
  13370. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13371. }
  13372. // The server sends an intermediate cross-signed by a root Windows trusts,
  13373. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13374. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13375. SSLClient cli("accounts.spotify.com", 443);
  13376. auto res = cli.Get("/");
  13377. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13378. << " ssl_backend_error=" << res.ssl_backend_error();
  13379. }
  13380. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13381. // policy status, which no backend reports for a self-signed certificate.
  13382. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13383. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13384. ASSERT_TRUE(svr.is_valid());
  13385. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13386. auto se = detail::scope_exit([&] {
  13387. svr.stop();
  13388. t.join();
  13389. ASSERT_FALSE(svr.is_running());
  13390. });
  13391. svr.wait_until_ready();
  13392. SSLClient cli("127.0.0.1", PORT);
  13393. cli.set_connection_timeout(30);
  13394. auto res = cli.Get("/");
  13395. ASSERT_FALSE(res);
  13396. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13397. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13398. }
  13399. #endif
  13400. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13401. Client cli("https://google.com");
  13402. auto res = cli.Get("/");
  13403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13404. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13405. }
  13406. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13407. SSLClient cli("google.com");
  13408. cli.set_ca_cert_path(CA_CERT_FILE);
  13409. auto res = cli.Get("/");
  13410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13411. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13412. }
  13413. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13414. SSLClient cli("google.com");
  13415. cli.enable_server_certificate_verification(true);
  13416. cli.set_ca_cert_path("hello");
  13417. auto res = cli.Get("/");
  13418. ASSERT_TRUE(!res);
  13419. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13420. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13421. // should be set
  13422. EXPECT_EQ(0, res.ssl_error());
  13423. // Verify backend error is captured for SSLLoadingCerts
  13424. // This error occurs when loading CA certificates fails
  13425. EXPECT_NE(0UL, res.ssl_backend_error());
  13426. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13427. // OpenSSL specific error codes:
  13428. // > openssl errstr 0x80000002
  13429. // error:80000002:system library::No such file or directory
  13430. // > openssl errstr 0xA000126
  13431. // error:0A000126:SSL routines::unexpected eof while reading
  13432. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13433. res.ssl_backend_error() == 0xA000126);
  13434. #endif
  13435. }
  13436. TEST(SSLClientTest, ServerCertificateVerification4) {
  13437. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13438. ASSERT_TRUE(svr.is_valid());
  13439. svr.Get("/test", [&](const Request &, Response &res) {
  13440. res.set_content("test", "text/plain");
  13441. svr.stop();
  13442. ASSERT_TRUE(true);
  13443. });
  13444. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13445. auto se = detail::scope_exit([&] {
  13446. t.join();
  13447. ASSERT_FALSE(svr.is_running());
  13448. });
  13449. svr.wait_until_ready();
  13450. SSLClient cli("127.0.0.1", PORT);
  13451. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13452. cli.enable_server_certificate_verification(true);
  13453. cli.set_connection_timeout(30);
  13454. auto res = cli.Get("/test");
  13455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13456. ASSERT_EQ(StatusCode::OK_200, res->status);
  13457. }
  13458. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13459. std::string cert;
  13460. read_file(CA_CERT_FILE, cert);
  13461. SSLClient cli("google.com");
  13462. cli.load_ca_cert_store(cert.data(), cert.size());
  13463. const auto res = cli.Get("/");
  13464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13465. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13466. }
  13467. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13468. // clang-format off
  13469. static constexpr char cert[] =
  13470. "GlobalSign Root CA\n"
  13471. "==================\n"
  13472. "-----BEGIN CERTIFICATE-----\n"
  13473. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13474. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13475. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13476. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13477. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13478. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13479. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13480. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13481. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13482. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13483. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13484. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13485. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13486. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13487. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13488. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13489. "-----END CERTIFICATE-----\n";
  13490. // clang-format on
  13491. SSLClient cli("google.com");
  13492. cli.load_ca_cert_store(cert, sizeof(cert));
  13493. const auto res = cli.Get("/");
  13494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13495. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13496. }
  13497. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13498. SSLClient cli("www.youtube.com");
  13499. cli.set_ca_cert_path(CA_CERT_FILE);
  13500. cli.enable_server_certificate_verification(true);
  13501. cli.set_follow_location(true);
  13502. auto res = cli.Get("/");
  13503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13504. ASSERT_EQ(StatusCode::OK_200, res->status);
  13505. }
  13506. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13507. SSLClient cli("wWw.YouTube.Com");
  13508. cli.set_ca_cert_path(CA_CERT_FILE);
  13509. cli.enable_server_certificate_verification(true);
  13510. cli.enable_server_hostname_verification(true);
  13511. cli.set_follow_location(true);
  13512. auto res = cli.Get("/");
  13513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13514. ASSERT_EQ(StatusCode::OK_200, res->status);
  13515. }
  13516. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13517. SSLClient cli("gOoGlE.COm");
  13518. cli.enable_server_certificate_verification(true);
  13519. cli.enable_server_hostname_verification(true);
  13520. cli.set_follow_location(true);
  13521. auto res = cli.Get("/");
  13522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13523. ASSERT_EQ(StatusCode::OK_200, res->status);
  13524. }
  13525. TEST(SSLClientTest, Issue2004_Online) {
  13526. Client client("https://google.com");
  13527. client.set_follow_location(true);
  13528. auto res = client.Get("/");
  13529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13530. ASSERT_EQ(StatusCode::OK_200, res->status);
  13531. auto body = res->body;
  13532. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13533. }
  13534. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13535. // Create SSLClient with invalid cert/key to make is_valid() return false
  13536. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13537. "nonexistent_key.pem");
  13538. // is_valid() should be false due to cert loading failure
  13539. ASSERT_FALSE(cli.is_valid());
  13540. auto res = cli.Get("/");
  13541. ASSERT_FALSE(res);
  13542. EXPECT_EQ(Error::SSLConnection, res.error());
  13543. }
  13544. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13545. // Test for Issue #2251: SSL error not properly reported when client cert
  13546. // and key paths are swapped or mismatched
  13547. // This simulates the scenario where user accidentally swaps the cert and key
  13548. // files
  13549. // Using client cert file as private key and vice versa (completely wrong)
  13550. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13551. // Should fail validation due to cert/key mismatch
  13552. ASSERT_FALSE(cli.is_valid());
  13553. // Attempt to make a request should fail with proper error
  13554. auto res = cli.Get("/");
  13555. ASSERT_FALSE(res);
  13556. EXPECT_EQ(Error::SSLConnection, res.error());
  13557. // SSL error should be recorded in the Result object (this is the key fix for
  13558. // Issue #2251)
  13559. auto backend_error = res.ssl_backend_error();
  13560. EXPECT_NE(0u, backend_error);
  13561. }
  13562. // Tests cert/key mismatch detection at the TLS context level
  13563. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13564. // Test that using mismatched cert/key causes connection failure.
  13565. // We verify this at the SSLClient level rather than through internal
  13566. // TLS API functions.
  13567. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13568. cli.enable_server_certificate_verification(false);
  13569. cli.set_connection_timeout(2);
  13570. // The mismatch should cause a connection or handshake error
  13571. auto res = cli.Get("/test");
  13572. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13573. // Either way, the request should fail
  13574. EXPECT_FALSE(res);
  13575. }
  13576. #endif
  13577. #if 0
  13578. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13579. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13580. ASSERT_TRUE(cli != nullptr);
  13581. cli->set_address_family(AF_INET6);
  13582. cli->set_interface("en0");
  13583. auto res = cli->Get("/get");
  13584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13585. ASSERT_EQ(StatusCode::OK_200, res->status);
  13586. }
  13587. #endif
  13588. // Client certificate tests - work with all TLS backends
  13589. #ifdef CPPHTTPLIB_SSL_ENABLED
  13590. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13591. void ClientCertPresent(
  13592. const std::string &client_cert_file,
  13593. const std::string &client_private_key_file,
  13594. const std::string &client_encrypted_private_key_pass = std::string(),
  13595. const ClientCertServerSetup &setup = nullptr) {
  13596. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13597. ASSERT_TRUE(svr.is_valid());
  13598. if (setup) { setup(svr); }
  13599. svr.Get("/test", [&](const Request &req, Response &res) {
  13600. res.set_content("test", "text/plain");
  13601. auto cert = req.peer_cert();
  13602. ASSERT_TRUE(static_cast<bool>(cert));
  13603. std::string common_name = cert.subject_cn();
  13604. EXPECT_EQ("Common Name", common_name);
  13605. });
  13606. auto port = svr.bind_to_any_port(HOST);
  13607. ASSERT_LT(0, port);
  13608. thread t = thread([&]() { svr.listen_after_bind(); });
  13609. auto se = detail::scope_exit([&] {
  13610. svr.stop();
  13611. t.join();
  13612. ASSERT_FALSE(svr.is_running());
  13613. });
  13614. svr.wait_until_ready();
  13615. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13616. client_encrypted_private_key_pass);
  13617. cli.enable_server_certificate_verification(false);
  13618. cli.set_connection_timeout(30);
  13619. auto res = cli.Get("/test");
  13620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13621. ASSERT_EQ(StatusCode::OK_200, res->status);
  13622. }
  13623. TEST(SSLClientServerTest, ClientCertPresent) {
  13624. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13625. }
  13626. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13627. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13628. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13629. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13630. }
  13631. // Expects svr, which must require client certificates, to reject a client
  13632. // that has none
  13633. void RejectsClientWithoutCert(SSLServer &svr) {
  13634. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13635. auto port = svr.bind_to_any_port(HOST);
  13636. ASSERT_LT(0, port);
  13637. thread t = thread([&]() { svr.listen_after_bind(); });
  13638. auto se = detail::scope_exit([&] {
  13639. svr.stop();
  13640. t.join();
  13641. ASSERT_FALSE(svr.is_running());
  13642. });
  13643. svr.wait_until_ready();
  13644. SSLClient cli(HOST, port);
  13645. cli.set_connection_timeout(30);
  13646. // Skip the server certificate check, so that the request fails because the
  13647. // client certificate is missing rather than because cert.pem is not trusted
  13648. cli.enable_server_certificate_verification(false);
  13649. auto res = cli.Get("/test");
  13650. ASSERT_FALSE(res);
  13651. // The server rejects the client during the handshake, or on TLS 1.3 right
  13652. // after it, which the client notices on its first write or read
  13653. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13654. res.error() == Error::Write || res.error() == Error::Read)
  13655. << to_string(res.error());
  13656. if (res.error() == Error::SSLConnection) {
  13657. EXPECT_NE(0UL, res.ssl_backend_error());
  13658. }
  13659. // A rejection noticed on the write keeps the TLS error the write hit
  13660. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13661. }
  13662. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13663. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13664. ASSERT_TRUE(svr.is_valid());
  13665. if (setup) { setup(svr); }
  13666. RejectsClientWithoutCert(svr);
  13667. }
  13668. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13669. // A server that requires client certificates must keep requiring them after
  13670. // setup changes it, and keep accepting a client that has one
  13671. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13672. ClientCertMissing(setup);
  13673. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13674. setup);
  13675. }
  13676. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13677. ClientCertStillRequired([](SSLServer &svr) {
  13678. ASSERT_TRUE(tls::set_verify_callback(
  13679. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13680. });
  13681. }
  13682. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13683. ClientCertStillRequired([](SSLServer &svr) {
  13684. ASSERT_TRUE(tls::set_verify_callback(
  13685. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13686. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13687. });
  13688. }
  13689. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13690. ClientCertStillRequired([](SSLServer &svr) {
  13691. std::string cert_pem, key_pem, ca_pem;
  13692. read_file(SERVER_CERT_FILE, cert_pem);
  13693. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13694. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13695. ASSERT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  13696. ca_pem.c_str()));
  13697. });
  13698. }
  13699. // A TLS error from one request must not show up in a later request's Result
  13700. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13702. ASSERT_TRUE(svr.is_valid());
  13703. svr.Get("/test", [](const Request &, Response &res) {
  13704. res.set_content("test", "text/plain");
  13705. });
  13706. auto port = svr.bind_to_any_port(HOST);
  13707. ASSERT_LT(0, port);
  13708. thread t = thread([&]() { svr.listen_after_bind(); });
  13709. auto se = detail::scope_exit([&] {
  13710. svr.stop();
  13711. t.join();
  13712. ASSERT_FALSE(svr.is_running());
  13713. });
  13714. svr.wait_until_ready();
  13715. SSLClient cli(HOST, port);
  13716. cli.set_connection_timeout(30);
  13717. cli.enable_server_hostname_verification(false);
  13718. // cert.pem is not trusted, so the handshake fails
  13719. ASSERT_FALSE(cli.Get("/test"));
  13720. cli.enable_server_certificate_verification(false);
  13721. auto res = cli.Get("/test");
  13722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13723. EXPECT_EQ(0, res.ssl_error());
  13724. EXPECT_EQ(0UL, res.ssl_backend_error());
  13725. }
  13726. // PEM memory-based constructor tests (works with all TLS backends)
  13727. void PemMemoryClientCertPresent(
  13728. const std::string &client_cert_file,
  13729. const std::string &client_private_key_file,
  13730. const std::string &client_encrypted_private_key_pass = std::string()) {
  13731. // Read PEM files into memory
  13732. std::string server_cert_pem, server_key_pem;
  13733. std::string client_ca_pem;
  13734. std::string client_cert_pem, client_key_pem;
  13735. read_file(SERVER_CERT_FILE, server_cert_pem);
  13736. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13737. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13738. read_file(client_cert_file, client_cert_pem);
  13739. read_file(client_private_key_file, client_key_pem);
  13740. // Create server with PEM memory
  13741. SSLServer::PemMemory server_pem = {
  13742. server_cert_pem.c_str(),
  13743. server_cert_pem.size(),
  13744. server_key_pem.c_str(),
  13745. server_key_pem.size(),
  13746. client_ca_pem.c_str(),
  13747. client_ca_pem.size(),
  13748. nullptr // no password for server key
  13749. };
  13750. SSLServer svr(server_pem);
  13751. ASSERT_TRUE(svr.is_valid());
  13752. svr.Get("/test", [&](const Request &req, Response &res) {
  13753. res.set_content("test", "text/plain");
  13754. auto cert = req.peer_cert();
  13755. ASSERT_TRUE(static_cast<bool>(cert));
  13756. EXPECT_EQ("Common Name", cert.subject_cn());
  13757. });
  13758. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13759. auto se = detail::scope_exit([&] {
  13760. svr.stop();
  13761. t.join();
  13762. ASSERT_FALSE(svr.is_running());
  13763. });
  13764. svr.wait_until_ready();
  13765. // Create client with PEM memory
  13766. const char *password = client_encrypted_private_key_pass.empty()
  13767. ? nullptr
  13768. : client_encrypted_private_key_pass.c_str();
  13769. SSLClient::PemMemory client_pem = {
  13770. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13771. client_key_pem.size(), password};
  13772. SSLClient cli(HOST, PORT, client_pem);
  13773. cli.enable_server_certificate_verification(false);
  13774. cli.set_connection_timeout(30);
  13775. auto res = cli.Get("/test");
  13776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13777. ASSERT_EQ(StatusCode::OK_200, res->status);
  13778. }
  13779. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13780. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13781. }
  13782. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13783. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13784. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13785. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13786. }
  13787. // A server built from PEM memory with a client CA requires client certificates
  13788. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13789. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13790. read_file(SERVER_CERT_FILE, server_cert_pem);
  13791. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13792. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13793. SSLServer::PemMemory server_pem = {
  13794. server_cert_pem.c_str(),
  13795. server_cert_pem.size(),
  13796. server_key_pem.c_str(),
  13797. server_key_pem.size(),
  13798. client_ca_pem.c_str(),
  13799. client_ca_pem.size(),
  13800. nullptr // no password for server key
  13801. };
  13802. SSLServer svr(server_pem);
  13803. ASSERT_TRUE(svr.is_valid());
  13804. RejectsClientWithoutCert(svr);
  13805. }
  13806. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13807. class NoListenSSLServer : public SSLServer {
  13808. public:
  13809. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13810. const char *client_ca_cert_file_path,
  13811. const char *client_ca_cert_dir_path = nullptr)
  13812. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13813. client_ca_cert_dir_path),
  13814. stop_(false) {}
  13815. std::atomic_bool stop_;
  13816. private:
  13817. bool process_and_close_socket(socket_t /*sock*/) override {
  13818. // Don't create SSL context
  13819. while (!stop_.load()) {
  13820. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13821. }
  13822. return true;
  13823. }
  13824. };
  13825. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13826. CLIENT_CA_CERT_FILE);
  13827. ASSERT_TRUE(svr.is_valid());
  13828. svr.Get("/test", [&](const Request &, Response &res) {
  13829. res.set_content("test", "text/plain");
  13830. });
  13831. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13832. auto se = detail::scope_exit([&] {
  13833. svr.stop_ = true;
  13834. svr.stop();
  13835. t.join();
  13836. ASSERT_FALSE(svr.is_running());
  13837. });
  13838. svr.wait_until_ready();
  13839. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13840. cli.enable_server_certificate_verification(false);
  13841. cli.set_connection_timeout(1);
  13842. auto res = cli.Get("/test");
  13843. ASSERT_TRUE(!res);
  13844. EXPECT_EQ(Error::SSLConnection, res.error());
  13845. // Timeout results in WantRead error code (maps to backend-specific value)
  13846. EXPECT_NE(0, res.ssl_error());
  13847. }
  13848. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13849. // Test SSLServer with client certificate verification using the standard
  13850. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13851. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13852. CLIENT_CA_CERT_DIR);
  13853. ASSERT_TRUE(svr.is_valid());
  13854. svr.Get("/test", [&](const Request &req, Response &res) {
  13855. res.set_content("test", "text/plain");
  13856. auto cert = req.peer_cert();
  13857. ASSERT_TRUE(static_cast<bool>(cert));
  13858. auto common_name = cert.subject_cn();
  13859. EXPECT_EQ("Common Name", common_name);
  13860. });
  13861. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13862. auto se = detail::scope_exit([&] {
  13863. svr.stop();
  13864. t.join();
  13865. ASSERT_FALSE(svr.is_running());
  13866. });
  13867. svr.wait_until_ready();
  13868. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13869. cli.enable_server_certificate_verification(false);
  13870. cli.set_connection_timeout(30);
  13871. auto res = cli.Get("/test");
  13872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13873. ASSERT_EQ(StatusCode::OK_200, res->status);
  13874. }
  13875. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13876. // Verifies that wildcard matching and exact matching work consistently
  13877. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13878. using namespace httplib::tls;
  13879. // We need a running server to test against
  13880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13881. ASSERT_TRUE(svr.is_valid());
  13882. svr.Get("/test", [](const Request &, Response &res) {
  13883. res.set_content("ok", "text/plain");
  13884. });
  13885. thread t([&]() { svr.listen(HOST, PORT); });
  13886. auto se = detail::scope_exit([&] {
  13887. svr.stop();
  13888. t.join();
  13889. });
  13890. svr.wait_until_ready();
  13891. bool verify_callback_called = false;
  13892. bool verify_result_wrong = false;
  13893. SSLClient cli(HOST, PORT);
  13894. cli.enable_server_certificate_verification(true);
  13895. cli.set_ca_cert_path(CA_CERT_FILE);
  13896. cli.set_connection_timeout(5);
  13897. // Note: Test certificate has CN="Common Name", not "localhost"
  13898. bool verify_result_cn = false;
  13899. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13900. verify_callback_called = true;
  13901. if (!ctx.cert) return false;
  13902. // Test 1: "Common Name" should match (our test server cert CN)
  13903. verify_result_cn = ctx.check_hostname("Common Name");
  13904. // Test 2: wrong hostname should not match
  13905. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13906. return true; // Accept for the purpose of this test
  13907. });
  13908. auto res = cli.Get("/test");
  13909. // The request may succeed or fail depending on cert configuration
  13910. // but the callback should have been called
  13911. ASSERT_TRUE(verify_callback_called)
  13912. << "Verify callback should have been called";
  13913. // CN="Common Name" should match our test certificate
  13914. //
  13915. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13916. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13917. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13918. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13919. // <openssl/base.h>, which is included transitively when
  13920. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13921. #if defined(OPENSSL_IS_BORINGSSL)
  13922. EXPECT_FALSE(verify_result_cn)
  13923. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13924. #else
  13925. EXPECT_TRUE(verify_result_cn)
  13926. << "verify_hostname should match 'Common Name' (certificate CN)";
  13927. #endif
  13928. // Wrong hostname should not match
  13929. EXPECT_FALSE(verify_result_wrong)
  13930. << "verify_hostname should not match 'wronghost.example.com'";
  13931. }
  13932. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13933. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13934. // X509_check_ip behavior and must hold for every backend.
  13935. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13936. using namespace httplib::tls;
  13937. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13938. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13939. ASSERT_TRUE(svr.is_valid());
  13940. svr.Get("/test", [](const Request &, Response &res) {
  13941. res.set_content("ok", "text/plain");
  13942. });
  13943. thread t([&]() { svr.listen(HOST, PORT); });
  13944. auto se = detail::scope_exit([&] {
  13945. svr.stop();
  13946. t.join();
  13947. });
  13948. svr.wait_until_ready();
  13949. bool verify_callback_called = false;
  13950. bool ip_matched_via_cn = true;
  13951. SSLClient cli(HOST, PORT);
  13952. cli.enable_server_certificate_verification(true);
  13953. cli.set_ca_cert_path(CA_CERT_FILE);
  13954. cli.set_connection_timeout(5);
  13955. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13956. verify_callback_called = true;
  13957. if (!ctx.cert) return false;
  13958. // The IP appears only in the CN, so it must NOT be accepted.
  13959. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13960. return true; // Accept for the purpose of this test
  13961. });
  13962. cli.Get("/test");
  13963. ASSERT_TRUE(verify_callback_called)
  13964. << "Verify callback should have been called";
  13965. EXPECT_FALSE(ip_matched_via_cn)
  13966. << "An IP host must not be authenticated via the certificate CN";
  13967. }
  13968. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13969. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13970. using namespace httplib::tls;
  13971. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13972. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13973. ASSERT_TRUE(svr.is_valid());
  13974. svr.Get("/test", [](const Request &, Response &res) {
  13975. res.set_content("ok", "text/plain");
  13976. });
  13977. thread t([&]() { svr.listen(HOST, PORT); });
  13978. auto se = detail::scope_exit([&] {
  13979. svr.stop();
  13980. t.join();
  13981. });
  13982. svr.wait_until_ready();
  13983. bool verify_callback_called = false;
  13984. bool san_matched = false;
  13985. bool wrong_ipv6_matched = true;
  13986. bool cn_ipv6_matched = true;
  13987. SSLClient cli(HOST, PORT);
  13988. cli.enable_server_certificate_verification(true);
  13989. cli.set_ca_cert_path(CA_CERT_FILE);
  13990. cli.set_connection_timeout(5);
  13991. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13992. verify_callback_called = true;
  13993. if (!ctx.cert) return false;
  13994. // Matches the IPv6 iPAddress SAN.
  13995. san_matched = ctx.check_hostname("2001:db8::1");
  13996. // A different IPv6 address must not match.
  13997. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13998. // "::1" lives only in the CN, so it must not be accepted.
  13999. cn_ipv6_matched = ctx.check_hostname("::1");
  14000. return true; // Accept for the purpose of this test
  14001. });
  14002. cli.Get("/test");
  14003. ASSERT_TRUE(verify_callback_called)
  14004. << "Verify callback should have been called";
  14005. EXPECT_TRUE(san_matched)
  14006. << "verify_hostname should match an IPv6 iPAddress SAN";
  14007. EXPECT_FALSE(wrong_ipv6_matched)
  14008. << "verify_hostname should not match a non-matching IPv6 address";
  14009. EXPECT_FALSE(cn_ipv6_matched)
  14010. << "An IPv6 host must not be authenticated via the certificate CN";
  14011. }
  14012. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14013. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14014. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14015. using namespace httplib::tls;
  14016. // SANs: DNS:a.zz, IP:42.46.122.122
  14017. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14018. ASSERT_TRUE(svr.is_valid());
  14019. svr.Get("/test", [](const Request &, Response &res) {
  14020. res.set_content("ok", "text/plain");
  14021. });
  14022. auto port = svr.bind_to_any_port(HOST);
  14023. thread t([&]() { svr.listen_after_bind(); });
  14024. auto se = detail::scope_exit([&] {
  14025. svr.stop();
  14026. t.join();
  14027. });
  14028. svr.wait_until_ready();
  14029. bool verify_callback_called = false;
  14030. bool dns_san_matched = false;
  14031. bool ip_san_matched = false;
  14032. bool ip_matched_via_dns_san = true;
  14033. bool dns_matched_via_ip_san = true;
  14034. bool cn_matched_next_to_dns_san = true;
  14035. SSLClient cli(HOST, port);
  14036. cli.enable_server_certificate_verification(true);
  14037. cli.set_ca_cert_path(CA_CERT_FILE);
  14038. cli.set_connection_timeout(5);
  14039. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14040. verify_callback_called = true;
  14041. if (!ctx.cert) return false;
  14042. dns_san_matched = ctx.check_hostname("a.zz");
  14043. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14044. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14045. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14046. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14047. return true; // Accept for the purpose of this test
  14048. });
  14049. cli.Get("/test");
  14050. ASSERT_TRUE(verify_callback_called)
  14051. << "Verify callback should have been called";
  14052. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14053. EXPECT_TRUE(ip_san_matched)
  14054. << "verify_hostname should match an iPAddress SAN";
  14055. EXPECT_FALSE(ip_matched_via_dns_san)
  14056. << "An IP host must not be authenticated via a dNSName SAN";
  14057. EXPECT_FALSE(dns_matched_via_ip_san)
  14058. << "A DNS host must not be authenticated via an iPAddress SAN";
  14059. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14060. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14061. }
  14062. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14063. // "www.*.example.test" names one host and not every host under example.test.
  14064. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14065. using namespace httplib::tls;
  14066. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14067. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14068. ASSERT_TRUE(svr.is_valid());
  14069. svr.Get("/test", [](const Request &, Response &res) {
  14070. res.set_content("ok", "text/plain");
  14071. });
  14072. auto port = svr.bind_to_any_port(HOST);
  14073. thread t([&]() { svr.listen_after_bind(); });
  14074. auto se = detail::scope_exit([&] {
  14075. svr.stop();
  14076. t.join();
  14077. });
  14078. svr.wait_until_ready();
  14079. bool verify_callback_called = false;
  14080. bool leftmost_wildcard_matched = false;
  14081. bool wildcard_spanned_labels = true;
  14082. bool inner_wildcard_matched = true;
  14083. SSLClient cli(HOST, port);
  14084. cli.enable_server_certificate_verification(true);
  14085. cli.set_ca_cert_path(CA_CERT_FILE);
  14086. cli.set_connection_timeout(5);
  14087. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14088. verify_callback_called = true;
  14089. if (!ctx.cert) return false;
  14090. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14091. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14092. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14093. return true; // Accept for the purpose of this test
  14094. });
  14095. cli.Get("/test");
  14096. ASSERT_TRUE(verify_callback_called)
  14097. << "Verify callback should have been called";
  14098. EXPECT_TRUE(leftmost_wildcard_matched)
  14099. << "A leftmost wildcard should match a single label";
  14100. EXPECT_FALSE(wildcard_spanned_labels)
  14101. << "A wildcard label must not match more than one label";
  14102. EXPECT_FALSE(inner_wildcard_matched)
  14103. << "A wildcard outside the leftmost label must not be honoured";
  14104. }
  14105. // sans() must report each SAN entry under its own type.
  14106. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14107. using namespace httplib::tls;
  14108. // SANs: DNS:a.zz, IP:42.46.122.122
  14109. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14110. ASSERT_TRUE(svr.is_valid());
  14111. svr.Get("/test", [](const Request &, Response &res) {
  14112. res.set_content("ok", "text/plain");
  14113. });
  14114. auto port = svr.bind_to_any_port(HOST);
  14115. thread t([&]() { svr.listen_after_bind(); });
  14116. auto se = detail::scope_exit([&] {
  14117. svr.stop();
  14118. t.join();
  14119. });
  14120. svr.wait_until_ready();
  14121. bool verify_callback_called = false;
  14122. std::vector<SanEntry> sans;
  14123. SSLClient cli(HOST, port);
  14124. cli.enable_server_certificate_verification(true);
  14125. cli.set_ca_cert_path(CA_CERT_FILE);
  14126. cli.set_connection_timeout(5);
  14127. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14128. verify_callback_called = true;
  14129. if (!ctx.cert) return false;
  14130. sans = ctx.sans();
  14131. return true; // Accept for the purpose of this test
  14132. });
  14133. cli.Get("/test");
  14134. ASSERT_TRUE(verify_callback_called)
  14135. << "Verify callback should have been called";
  14136. auto has_san = [&](SanType type, const std::string &value) {
  14137. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14138. return san.type == type && san.value == value;
  14139. });
  14140. };
  14141. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14142. << "sans() should report the dNSName SAN";
  14143. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14144. << "sans() should report the iPAddress SAN";
  14145. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14146. << "sans() must not report the dNSName SAN as an address";
  14147. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14148. << "sans() must not report the iPAddress SAN as a DNS name";
  14149. }
  14150. #endif
  14151. // mbedTLS-specific callback constructor test
  14152. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14153. #ifdef CPPHTTPLIB_SSL_ENABLED
  14154. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14155. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14156. ASSERT_TRUE(svr.is_valid());
  14157. // Set up a handler to verify client certificate is present
  14158. bool client_cert_verified = false;
  14159. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14160. // Verify that client certificate was provided
  14161. client_cert_verified = true;
  14162. res.set_content("success", "text/plain");
  14163. });
  14164. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14165. auto se = detail::scope_exit([&] {
  14166. svr.stop();
  14167. t.join();
  14168. ASSERT_FALSE(svr.is_running());
  14169. });
  14170. svr.wait_until_ready();
  14171. // Client with certificate
  14172. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14173. cli.enable_server_certificate_verification(false);
  14174. cli.set_connection_timeout(30);
  14175. auto res = cli.Get("/test");
  14176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14177. ASSERT_EQ(StatusCode::OK_200, res->status);
  14178. ASSERT_TRUE(client_cert_verified);
  14179. EXPECT_EQ("success", res->body);
  14180. }
  14181. #endif
  14182. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14183. // backends
  14184. #ifdef CPPHTTPLIB_SSL_ENABLED
  14185. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14186. using namespace httplib::tls;
  14187. // Test that when client CA cert file is provided,
  14188. // the server properly requests and validates client certificates
  14189. // Create a server with client authentication
  14190. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14191. ASSERT_TRUE(svr.is_valid());
  14192. bool handler_called = false;
  14193. svr.Get("/test", [&](const Request &req, Response &res) {
  14194. handler_called = true;
  14195. // Verify that a client certificate was provided
  14196. auto cert = req.peer_cert();
  14197. ASSERT_TRUE(static_cast<bool>(cert));
  14198. // Get the issuer name
  14199. std::string issuer_str = cert.issuer_name();
  14200. ASSERT_FALSE(issuer_str.empty());
  14201. // The client certificate should be issued by our test CA
  14202. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14203. res.set_content("authenticated", "text/plain");
  14204. });
  14205. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14206. auto se = detail::scope_exit([&] {
  14207. svr.stop();
  14208. t.join();
  14209. ASSERT_FALSE(svr.is_running());
  14210. });
  14211. svr.wait_until_ready();
  14212. // Connect with a client certificate issued by the CA
  14213. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14214. cli.enable_server_certificate_verification(false);
  14215. cli.set_connection_timeout(30);
  14216. auto res = cli.Get("/test");
  14217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14218. ASSERT_EQ(StatusCode::OK_200, res->status);
  14219. ASSERT_TRUE(handler_called);
  14220. EXPECT_EQ("authenticated", res->body);
  14221. }
  14222. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14223. using namespace httplib::tls;
  14224. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14225. ASSERT_TRUE(svr.is_valid());
  14226. svr.Get("/test", [](const Request &, Response &res) {
  14227. res.set_content("ok", "text/plain");
  14228. });
  14229. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14230. auto se = detail::scope_exit([&] {
  14231. svr.stop();
  14232. t.join();
  14233. });
  14234. svr.wait_until_ready();
  14235. SSLClient cli(HOST, PORT);
  14236. cli.enable_server_certificate_verification(false);
  14237. cli.set_connection_timeout(30);
  14238. bool cert_checked = false;
  14239. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14240. if (ctx.cert) {
  14241. auto sans = ctx.sans();
  14242. // Test certificate may or may not have SANs - just verify the API
  14243. // works If SANs exist, verify the types are valid
  14244. for (const auto &san : sans) {
  14245. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14246. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14247. san.type == SanType::OTHER);
  14248. EXPECT_FALSE(san.value.empty());
  14249. }
  14250. cert_checked = true;
  14251. }
  14252. return true;
  14253. });
  14254. auto res = cli.Get("/test");
  14255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14256. EXPECT_TRUE(cert_checked);
  14257. }
  14258. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14259. using namespace httplib::tls;
  14260. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14261. ASSERT_TRUE(svr.is_valid());
  14262. svr.Get("/test", [](const Request &, Response &res) {
  14263. res.set_content("ok", "text/plain");
  14264. });
  14265. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14266. auto se = detail::scope_exit([&] {
  14267. svr.stop();
  14268. t.join();
  14269. });
  14270. svr.wait_until_ready();
  14271. SSLClient cli(HOST, PORT);
  14272. cli.enable_server_certificate_verification(false);
  14273. cli.set_connection_timeout(30);
  14274. bool validity_checked = false;
  14275. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14276. if (ctx.cert) {
  14277. time_t not_before = 0, not_after = 0;
  14278. bool result = ctx.validity(not_before, not_after);
  14279. EXPECT_TRUE(result);
  14280. // Verify that not_before < now < not_after for a valid cert
  14281. time_t now = time(nullptr);
  14282. EXPECT_LT(not_before, now);
  14283. EXPECT_GT(not_after, now);
  14284. validity_checked = true;
  14285. }
  14286. return true;
  14287. });
  14288. auto res = cli.Get("/test");
  14289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14290. EXPECT_TRUE(validity_checked);
  14291. }
  14292. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14293. using namespace httplib::tls;
  14294. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14295. ASSERT_TRUE(svr.is_valid());
  14296. svr.Get("/test", [](const Request &, Response &res) {
  14297. res.set_content("ok", "text/plain");
  14298. });
  14299. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14300. auto se = detail::scope_exit([&] {
  14301. svr.stop();
  14302. t.join();
  14303. });
  14304. svr.wait_until_ready();
  14305. SSLClient cli(HOST, PORT);
  14306. cli.enable_server_certificate_verification(false);
  14307. cli.set_connection_timeout(30);
  14308. bool serial_checked = false;
  14309. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14310. if (ctx.cert) {
  14311. std::string serial = ctx.serial();
  14312. EXPECT_FALSE(serial.empty());
  14313. // Serial should be a hex string
  14314. for (char c : serial) {
  14315. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14316. (c >= 'a' && c <= 'f'));
  14317. }
  14318. serial_checked = true;
  14319. }
  14320. return true;
  14321. });
  14322. auto res = cli.Get("/test");
  14323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14324. EXPECT_TRUE(serial_checked);
  14325. }
  14326. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14327. // Test 1: Valid CA file - no error should be recorded
  14328. {
  14329. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14330. CLIENT_CA_CERT_FILE);
  14331. ASSERT_TRUE(svr.is_valid());
  14332. // With valid setup, last_ssl_error should be 0
  14333. EXPECT_EQ(0, svr.ssl_last_error());
  14334. }
  14335. // Test 2: Invalid CA file content
  14336. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14337. {
  14338. // Create a temporary file with completely invalid content
  14339. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14340. {
  14341. std::ofstream ofs(temp_invalid_ca);
  14342. ofs << "This is not a certificate file at all\n";
  14343. ofs << "Just plain text content\n";
  14344. }
  14345. // Create server with invalid CA file
  14346. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14347. // Clean up temporary file
  14348. std::remove(temp_invalid_ca);
  14349. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14350. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14351. // Note: SSL_CTX_load_verify_locations typically fails first,
  14352. // but our error handling code path is still exercised
  14353. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14354. }
  14355. }
  14356. TEST(VerifyCallbackTest, VerifyContextFields) {
  14357. using namespace httplib::tls;
  14358. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14359. ASSERT_TRUE(svr.is_valid());
  14360. svr.Get("/test", [](const Request &, Response &res) {
  14361. res.set_content("ok", "text/plain");
  14362. });
  14363. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14364. auto se = detail::scope_exit([&] {
  14365. svr.stop();
  14366. t.join();
  14367. });
  14368. svr.wait_until_ready();
  14369. SSLClient cli(HOST, PORT);
  14370. cli.enable_server_certificate_verification(false);
  14371. cli.set_connection_timeout(30);
  14372. int callback_count = 0;
  14373. bool saw_leaf_cert = false;
  14374. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14375. if (ctx.cert) {
  14376. callback_count++;
  14377. // We should see at least one certificate (the leaf)
  14378. std::string cn = ctx.subject_cn();
  14379. if (!cn.empty()) { saw_leaf_cert = true; }
  14380. // Verify context fields are populated
  14381. EXPECT_NE(ctx.session, nullptr);
  14382. EXPECT_GE(ctx.depth, 0);
  14383. }
  14384. return true;
  14385. });
  14386. auto res = cli.Get("/test");
  14387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14388. EXPECT_GT(callback_count, 0);
  14389. EXPECT_TRUE(saw_leaf_cert);
  14390. }
  14391. // A verifier belongs to the client that set it, not to the thread that set it.
  14392. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14393. using namespace httplib::tls;
  14394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14395. ASSERT_TRUE(svr.is_valid());
  14396. svr.Get("/test", [](const Request &, Response &res) {
  14397. res.set_content("ok", "text/plain");
  14398. });
  14399. auto port = svr.bind_to_any_port(HOST);
  14400. thread t([&]() { svr.listen_after_bind(); });
  14401. auto se = detail::scope_exit([&] {
  14402. svr.stop();
  14403. t.join();
  14404. });
  14405. svr.wait_until_ready();
  14406. auto rejecting_calls = 0;
  14407. SSLClient rejecting(HOST, port);
  14408. rejecting.enable_server_certificate_verification(false);
  14409. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14410. rejecting_calls++;
  14411. return false;
  14412. });
  14413. auto accepting_calls = 0;
  14414. SSLClient accepting(HOST, port);
  14415. accepting.enable_server_certificate_verification(false);
  14416. // Set on another thread than the requests below.
  14417. thread([&]() {
  14418. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14419. accepting_calls++;
  14420. return true;
  14421. });
  14422. }).join();
  14423. // Requested on another thread than the verifier was set on.
  14424. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14425. EXPECT_GT(rejecting_calls, 0);
  14426. auto res = accepting.Get("/test");
  14427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14428. EXPECT_GT(accepting_calls, 0);
  14429. }
  14430. // A verifier replaced while a handshake runs it lives until it returns.
  14431. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14432. using namespace httplib::tls;
  14433. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14434. ASSERT_TRUE(svr.is_valid());
  14435. svr.Get("/test", [](const Request &, Response &res) {
  14436. res.set_content("ok", "text/plain");
  14437. });
  14438. auto port = svr.bind_to_any_port(HOST);
  14439. thread t([&]() { svr.listen_after_bind(); });
  14440. auto se = detail::scope_exit([&] {
  14441. svr.stop();
  14442. t.join();
  14443. });
  14444. svr.wait_until_ready();
  14445. SSLClient cli(HOST, port);
  14446. cli.enable_server_certificate_verification(false);
  14447. std::promise<void> entered;
  14448. std::promise<void> replaced;
  14449. auto replaced_future = replaced.get_future();
  14450. auto first_call = true;
  14451. // Long enough to live on the heap
  14452. std::string expected(64, 'v');
  14453. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14454. if (first_call) {
  14455. first_call = false;
  14456. entered.set_value();
  14457. replaced_future.wait();
  14458. }
  14459. return expected == std::string(64, 'v');
  14460. });
  14461. thread request([&]() {
  14462. auto res = cli.Get("/test");
  14463. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14464. });
  14465. entered.get_future().wait();
  14466. cli.set_server_certificate_verifier(
  14467. [](const VerifyContext &) { return true; });
  14468. replaced.set_value();
  14469. request.join();
  14470. }
  14471. // VerifyContext::session is the same handle the other tls:: functions take.
  14472. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14473. using namespace httplib::tls;
  14474. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14475. ASSERT_TRUE(svr.is_valid());
  14476. svr.Get("/test", [](const Request &, Response &res) {
  14477. res.set_content("ok", "text/plain");
  14478. });
  14479. auto port = svr.bind_to_any_port(HOST);
  14480. thread t([&]() { svr.listen_after_bind(); });
  14481. auto se = detail::scope_exit([&] {
  14482. svr.stop();
  14483. t.join();
  14484. });
  14485. svr.wait_until_ready();
  14486. SSLClient cli(HOST, port);
  14487. cli.enable_server_certificate_verification(false);
  14488. session_t verifier_session = nullptr;
  14489. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14490. verifier_session = ctx.session;
  14491. return true;
  14492. });
  14493. session_t session_verifier_session = nullptr;
  14494. cli.set_session_verifier([&](session_t session) {
  14495. session_verifier_session = session;
  14496. return SSLVerifierResponse::NoDecisionMade;
  14497. });
  14498. auto res = cli.Get("/test");
  14499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14500. EXPECT_NE(nullptr, verifier_session);
  14501. EXPECT_EQ(session_verifier_session, verifier_session);
  14502. }
  14503. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14504. using httplib::tls::TlsError;
  14505. // Test that verify_error_to_string returns empty for success
  14506. std::string success_str = TlsError::verify_error_to_string(0);
  14507. EXPECT_TRUE(success_str.empty());
  14508. // Test that verify_error_to_string returns non-empty for error codes
  14509. // Using a common error code (certificate expired)
  14510. std::string error_str =
  14511. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14512. EXPECT_FALSE(error_str.empty());
  14513. }
  14514. TEST(SessionVerifierTest, CertificateAccepted) {
  14515. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14516. ASSERT_TRUE(svr.is_valid());
  14517. svr.Get("/test", [](const Request &, Response &res) {
  14518. res.set_content("ok", "text/plain");
  14519. });
  14520. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14521. auto se = detail::scope_exit([&] {
  14522. svr.stop();
  14523. t.join();
  14524. });
  14525. svr.wait_until_ready();
  14526. SSLClient cli(HOST, PORT);
  14527. cli.enable_server_certificate_verification(false);
  14528. cli.set_connection_timeout(30);
  14529. bool callback_called = false;
  14530. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14531. EXPECT_NE(session, nullptr);
  14532. callback_called = true;
  14533. return SSLVerifierResponse::CertificateAccepted;
  14534. });
  14535. auto res = cli.Get("/test");
  14536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14537. EXPECT_EQ(200, res->status);
  14538. EXPECT_TRUE(callback_called);
  14539. }
  14540. TEST(SessionVerifierTest, CertificateRejected) {
  14541. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14542. ASSERT_TRUE(svr.is_valid());
  14543. svr.Get("/test", [](const Request &, Response &res) {
  14544. res.set_content("ok", "text/plain");
  14545. });
  14546. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14547. auto se = detail::scope_exit([&] {
  14548. svr.stop();
  14549. t.join();
  14550. });
  14551. svr.wait_until_ready();
  14552. SSLClient cli(HOST, PORT);
  14553. cli.enable_server_certificate_verification(false);
  14554. cli.set_connection_timeout(30);
  14555. bool callback_called = false;
  14556. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14557. EXPECT_NE(session, nullptr);
  14558. callback_called = true;
  14559. return SSLVerifierResponse::CertificateRejected;
  14560. });
  14561. auto res = cli.Get("/test");
  14562. EXPECT_FALSE(res);
  14563. EXPECT_TRUE(callback_called);
  14564. }
  14565. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14566. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14567. ASSERT_TRUE(svr.is_valid());
  14568. svr.Get("/test", [](const Request &, Response &res) {
  14569. res.set_content("ok", "text/plain");
  14570. });
  14571. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14572. auto se = detail::scope_exit([&] {
  14573. svr.stop();
  14574. t.join();
  14575. });
  14576. svr.wait_until_ready();
  14577. // NoDecisionMade with verification disabled should succeed (no default check)
  14578. SSLClient cli(HOST, PORT);
  14579. cli.enable_server_certificate_verification(false);
  14580. cli.set_connection_timeout(30);
  14581. bool callback_called = false;
  14582. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14583. EXPECT_NE(session, nullptr);
  14584. callback_called = true;
  14585. return SSLVerifierResponse::NoDecisionMade;
  14586. });
  14587. auto res = cli.Get("/test");
  14588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14589. EXPECT_EQ(200, res->status);
  14590. EXPECT_TRUE(callback_called);
  14591. }
  14592. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14594. ASSERT_TRUE(svr.is_valid());
  14595. svr.Get("/test", [](const Request &, Response &res) {
  14596. res.set_content("ok", "text/plain");
  14597. });
  14598. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14599. auto se = detail::scope_exit([&] {
  14600. svr.stop();
  14601. t.join();
  14602. });
  14603. svr.wait_until_ready();
  14604. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14605. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14606. // so we only check that the request fails, not whether the callback was
  14607. // called.
  14608. SSLClient cli(HOST, PORT);
  14609. cli.enable_server_certificate_verification(true);
  14610. cli.set_connection_timeout(30);
  14611. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14612. EXPECT_NE(session, nullptr);
  14613. return SSLVerifierResponse::NoDecisionMade;
  14614. });
  14615. auto res = cli.Get("/test");
  14616. EXPECT_FALSE(res);
  14617. }
  14618. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14619. // Test SSL server using PemMemory constructor with client CA certificates
  14620. // Read PEM files
  14621. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14622. read_file(SERVER_CERT_FILE, server_cert_pem);
  14623. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14624. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14625. // Create SSLServer with PemMemory constructor including client CA
  14626. SSLServer::PemMemory server_pem = {
  14627. server_cert_pem.c_str(),
  14628. server_cert_pem.size(),
  14629. server_key_pem.c_str(),
  14630. server_key_pem.size(),
  14631. client_ca_pem.c_str(),
  14632. client_ca_pem.size(),
  14633. nullptr // no password for server key
  14634. };
  14635. SSLServer svr(server_pem);
  14636. ASSERT_TRUE(svr.is_valid());
  14637. // No SSL error should be recorded for valid setup
  14638. EXPECT_EQ(0, svr.ssl_last_error());
  14639. // Set up server endpoints
  14640. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14641. res.set_content("ok", "text/plain");
  14642. });
  14643. // Start server in a thread
  14644. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14645. svr.wait_until_ready();
  14646. // Connect with client certificate (using constructor with paths)
  14647. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14648. cli.enable_server_certificate_verification(false);
  14649. auto res = cli.Get("/test-pem-ca");
  14650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14651. EXPECT_EQ(200, res->status);
  14652. EXPECT_EQ("ok", res->body);
  14653. svr.stop();
  14654. server_thread.join();
  14655. }
  14656. #endif
  14657. #ifdef _WIN32
  14658. TEST(CleanupTest, WSACleanup) {
  14659. int ret = WSACleanup();
  14660. ASSERT_EQ(0, ret);
  14661. }
  14662. #endif
  14663. #ifndef CPPHTTPLIB_SSL_ENABLED
  14664. TEST(NoSSLSupport, SimpleInterface) {
  14665. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14666. }
  14667. #endif
  14668. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14669. TEST(InvalidScheme, SimpleInterface) {
  14670. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14671. }
  14672. #endif
  14673. TEST(NoScheme, SimpleInterface) {
  14674. Client cli("yahoo.com:80");
  14675. ASSERT_TRUE(cli.is_valid());
  14676. }
  14677. TEST(SendAPI, SimpleInterface_Online) {
  14678. Client cli("http://yahoo.com");
  14679. Request req;
  14680. req.method = "GET";
  14681. req.path = "/";
  14682. auto res = cli.send(req);
  14683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14684. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14685. }
  14686. TEST(SendAPI, WithParamsInRequest) {
  14687. Server svr;
  14688. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14689. EXPECT_TRUE(req.has_param("test"));
  14690. EXPECT_EQ("test_value", req.get_param_value("test"));
  14691. });
  14692. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14693. auto se = detail::scope_exit([&] {
  14694. svr.stop();
  14695. t.join();
  14696. ASSERT_FALSE(svr.is_running());
  14697. });
  14698. svr.wait_until_ready();
  14699. Client cli(HOST, PORT);
  14700. {
  14701. Request req;
  14702. req.method = "GET";
  14703. req.path = "/";
  14704. req.params.emplace("test", "test_value");
  14705. auto res = cli.send(req);
  14706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14707. }
  14708. {
  14709. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14711. }
  14712. }
  14713. TEST(ClientImplMethods, GetSocketTest) {
  14714. httplib::Server svr;
  14715. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14716. res.status = StatusCode::OK_200;
  14717. });
  14718. auto port = svr.bind_to_any_port("127.0.0.1");
  14719. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14720. auto se = detail::scope_exit([&] {
  14721. svr.stop();
  14722. thread.join();
  14723. ASSERT_FALSE(svr.is_running());
  14724. });
  14725. svr.wait_until_ready();
  14726. {
  14727. httplib::Client cli("127.0.0.1", port);
  14728. cli.set_keep_alive(true);
  14729. // Use the behavior of cpp-httplib of opening the connection
  14730. // only when the first request happens. If that changes,
  14731. // this test would be obsolete.
  14732. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14733. // This also implicitly tests the server. But other tests would fail much
  14734. // earlier than this one to be considered.
  14735. auto res = cli.Get("/");
  14736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14737. EXPECT_EQ(StatusCode::OK_200, res->status);
  14738. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14739. }
  14740. }
  14741. #ifdef CPPHTTPLIB_SSL_ENABLED
  14742. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14743. Client cli("http://yahoo.com");
  14744. auto res = cli.Get("/");
  14745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14746. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14747. cli.set_follow_location(true);
  14748. res = cli.Get("/");
  14749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14750. EXPECT_EQ(StatusCode::OK_200, res->status);
  14751. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14752. }
  14753. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14754. Client cli("https://yahoo.com");
  14755. auto res = cli.Get("/");
  14756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14757. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14758. cli.set_follow_location(true);
  14759. res = cli.Get("/");
  14760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14761. EXPECT_EQ(StatusCode::OK_200, res->status);
  14762. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14763. }
  14764. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14765. Client cli("https://yahoo.com");
  14766. auto res = cli.Get("/");
  14767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14768. ASSERT_FALSE(!res);
  14769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14770. ASSERT_FALSE(res == nullptr);
  14771. ASSERT_TRUE(res != nullptr);
  14772. EXPECT_EQ(Error::Success, res.error());
  14773. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14774. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14775. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14776. cli.set_follow_location(true);
  14777. res = cli.Get("/");
  14778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14779. EXPECT_EQ(Error::Success, res.error());
  14780. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14781. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14782. EXPECT_EQ(StatusCode::OK_200, res->status);
  14783. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14784. }
  14785. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14786. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14787. Client cli("https://cdnjs.cloudflare.com");
  14788. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14789. Headers{{"Accept-Encoding", "br"}});
  14790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14791. EXPECT_EQ(StatusCode::OK_200, res->status);
  14792. EXPECT_EQ(287630U, res->body.size());
  14793. EXPECT_EQ("application/javascript; charset=utf-8",
  14794. res->get_header_value("Content-Type"));
  14795. }
  14796. #endif
  14797. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14798. #undef REDIR_HOST // Silence compiler warning
  14799. #define REDIR_HOST "https://httpbingo.org"
  14800. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14801. Client cli(REDIR_HOST);
  14802. cli.set_follow_location(true);
  14803. auto res =
  14804. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14806. EXPECT_EQ(StatusCode::OK_200, res->status);
  14807. }
  14808. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14809. Client cli(REDIR_HOST);
  14810. cli.set_follow_location(true);
  14811. Params params;
  14812. params.emplace("url", "http://example.com");
  14813. params.emplace("status_code", "302");
  14814. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14816. EXPECT_EQ(StatusCode::OK_200, res->status);
  14817. }
  14818. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14819. Client cli(REDIR_HOST);
  14820. cli.set_follow_location(true);
  14821. Params params;
  14822. params.emplace("url", "http://example.com");
  14823. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14825. EXPECT_EQ(StatusCode::OK_200, res->status);
  14826. }
  14827. TEST(HttpToHttpsRedirectTest, CertFile) {
  14828. auto ssl_port = PORT + 1;
  14829. Server svr;
  14830. ASSERT_TRUE(svr.is_valid());
  14831. svr.Get("/index", [&](const Request &, Response &res) {
  14832. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14833. "/index");
  14834. svr.stop();
  14835. });
  14836. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14837. ASSERT_TRUE(ssl_svr.is_valid());
  14838. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14839. res.set_content("test", "text/plain");
  14840. ssl_svr.stop();
  14841. });
  14842. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14843. thread t2 =
  14844. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14845. auto se = detail::scope_exit([&] {
  14846. t2.join();
  14847. t.join();
  14848. ASSERT_FALSE(svr.is_running());
  14849. });
  14850. svr.wait_until_ready();
  14851. ssl_svr.wait_until_ready();
  14852. Client cli("127.0.0.1", PORT);
  14853. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14854. cli.enable_server_certificate_verification(true);
  14855. cli.set_follow_location(true);
  14856. cli.set_connection_timeout(30);
  14857. auto res = cli.Get("/index");
  14858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14859. ASSERT_EQ(StatusCode::OK_200, res->status);
  14860. }
  14861. TEST(SSLClientRedirectTest, CertFile) {
  14862. auto ssl_port = PORT + 1;
  14863. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14864. ASSERT_TRUE(ssl_svr1.is_valid());
  14865. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14866. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14867. "/index");
  14868. ssl_svr1.stop();
  14869. });
  14870. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14871. ASSERT_TRUE(ssl_svr2.is_valid());
  14872. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14873. res.set_content("test", "text/plain");
  14874. ssl_svr2.stop();
  14875. });
  14876. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14877. thread t2 =
  14878. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14879. auto se = detail::scope_exit([&] {
  14880. t2.join();
  14881. t.join();
  14882. ASSERT_FALSE(ssl_svr1.is_running());
  14883. });
  14884. ssl_svr1.wait_until_ready();
  14885. ssl_svr2.wait_until_ready();
  14886. SSLClient cli("127.0.0.1", PORT);
  14887. std::string cert;
  14888. read_file(SERVER_CERT2_FILE, cert);
  14889. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14890. cli.enable_server_certificate_verification(true);
  14891. cli.set_follow_location(true);
  14892. cli.set_connection_timeout(30);
  14893. auto res = cli.Get("/index");
  14894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14895. ASSERT_EQ(StatusCode::OK_200, res->status);
  14896. }
  14897. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14898. // another port, so the client follows it with a new client.
  14899. static Result GetThroughTlsRedirectToDifferentPort(
  14900. const std::function<void(SSLClient &)> &setup,
  14901. const char *target_cert = SERVER_CERT2_FILE,
  14902. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  14903. auto ssl_port = PORT + 1;
  14904. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14905. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14906. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14907. "/index");
  14908. });
  14909. SSLServer ssl_svr2(target_cert, target_key);
  14910. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14911. res.set_content("test", "text/plain");
  14912. });
  14913. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14914. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14915. auto se = detail::scope_exit([&] {
  14916. ssl_svr2.stop();
  14917. ssl_svr1.stop();
  14918. t2.join();
  14919. t.join();
  14920. });
  14921. ssl_svr1.wait_until_ready();
  14922. ssl_svr2.wait_until_ready();
  14923. SSLClient cli("127.0.0.1", PORT);
  14924. cli.set_follow_location(true);
  14925. cli.set_connection_timeout(30);
  14926. setup(cli);
  14927. return cli.Get("/index");
  14928. }
  14929. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14930. auto calls = 0;
  14931. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14932. cli.enable_server_certificate_verification(false);
  14933. // Accept the first server only.
  14934. cli.set_session_verifier([&](tls::session_t) {
  14935. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14936. : SSLVerifierResponse::CertificateRejected;
  14937. });
  14938. });
  14939. ASSERT_FALSE(res);
  14940. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14941. EXPECT_EQ(2, calls);
  14942. }
  14943. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14944. std::string pinned;
  14945. auto res = GetThroughTlsRedirectToDifferentPort(
  14946. [&](SSLClient &cli) {
  14947. cli.enable_server_certificate_verification(false);
  14948. // Pin the first certificate seen.
  14949. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14950. if (pinned.empty()) { pinned = ctx.serial(); }
  14951. return ctx.serial() == pinned;
  14952. });
  14953. },
  14954. // A certificate other than the first server's.
  14955. SERVER_CERT_FILE);
  14956. EXPECT_FALSE(res);
  14957. EXPECT_FALSE(pinned.empty());
  14958. }
  14959. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14960. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14961. std::string cert;
  14962. read_file(SERVER_CERT2_FILE, cert);
  14963. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14964. });
  14965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14966. EXPECT_EQ(StatusCode::OK_200, res->status);
  14967. }
  14968. // The target's certificate is signed by the root CA, which the first server's
  14969. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  14970. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  14971. auto res = GetThroughTlsRedirectToDifferentPort(
  14972. [](SSLClient &cli) {
  14973. std::string root_ca, cert;
  14974. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14975. read_file(SERVER_CERT2_FILE, cert);
  14976. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14977. cli.load_ca_cert_store(cert.data(), cert.size());
  14978. cli.enable_server_hostname_verification(false);
  14979. },
  14980. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14982. EXPECT_EQ(StatusCode::OK_200, res->status);
  14983. }
  14984. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  14985. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  14986. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  14987. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  14988. auto res = GetThroughTlsRedirectToDifferentPort(
  14989. [](SSLClient &cli) {
  14990. std::string root_ca, cert;
  14991. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14992. read_file(SERVER_CERT2_FILE, cert);
  14993. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14994. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14995. cli.enable_server_hostname_verification(false);
  14996. },
  14997. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14998. ASSERT_FALSE(res);
  14999. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15000. }
  15001. #endif
  15002. #endif
  15003. #ifdef CPPHTTPLIB_SSL_ENABLED
  15004. // Test that set_ca_cert_store() skips system certs (consistent with
  15005. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15006. // should be trusted - system certs should NOT be loaded.
  15007. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15008. // Load a specific cert that is NOT a system CA cert
  15009. std::string cert;
  15010. read_file(SERVER_CERT2_FILE, cert);
  15011. SSLClient cli("google.com");
  15012. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15013. cli.enable_server_certificate_verification(true);
  15014. // This should FAIL because:
  15015. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15016. // 2. System certs should NOT be loaded when custom store is set
  15017. // If system certs WERE loaded, this would succeed
  15018. auto res = cli.Get("/");
  15019. ASSERT_FALSE(res);
  15020. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15021. }
  15022. // Same as above, but through the native store handle path. Regression test:
  15023. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15024. // merged system certs into the user-provided store.
  15025. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15026. std::string cert;
  15027. read_file(SERVER_CERT2_FILE, cert);
  15028. SSLClient cli("google.com");
  15029. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15030. cli.enable_server_certificate_verification(true);
  15031. auto res = cli.Get("/");
  15032. ASSERT_FALSE(res);
  15033. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15034. }
  15035. // A custom store set via the native handle must still verify a server whose
  15036. // cert it does contain.
  15037. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15038. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15039. ASSERT_TRUE(svr.is_valid());
  15040. svr.Get("/test", [&](const Request &, Response &res) {
  15041. res.set_content("test", "text/plain");
  15042. });
  15043. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15044. auto se = detail::scope_exit([&] {
  15045. svr.stop();
  15046. t.join();
  15047. ASSERT_FALSE(svr.is_running());
  15048. });
  15049. svr.wait_until_ready();
  15050. SSLClient cli("127.0.0.1", PORT);
  15051. std::string cert;
  15052. read_file(SERVER_CERT2_FILE, cert);
  15053. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15054. cli.enable_server_certificate_verification(true);
  15055. cli.set_connection_timeout(30);
  15056. auto res = cli.Get("/test");
  15057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15058. ASSERT_EQ(StatusCode::OK_200, res->status);
  15059. }
  15060. // CA certs loaded through the universal Client must be transferred to the
  15061. // client created internally for following an HTTPS redirect. Regression test:
  15062. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15063. // the CA data for redirect transfer.
  15064. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15065. auto ssl_port = PORT + 1;
  15066. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15067. ASSERT_TRUE(ssl_svr1.is_valid());
  15068. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15069. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15070. "/index");
  15071. });
  15072. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15073. ASSERT_TRUE(ssl_svr2.is_valid());
  15074. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15075. res.set_content("test", "text/plain");
  15076. });
  15077. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15078. thread t2 =
  15079. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15080. auto se = detail::scope_exit([&] {
  15081. ssl_svr2.stop();
  15082. ssl_svr1.stop();
  15083. t2.join();
  15084. t.join();
  15085. ASSERT_FALSE(ssl_svr1.is_running());
  15086. });
  15087. ssl_svr1.wait_until_ready();
  15088. ssl_svr2.wait_until_ready();
  15089. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15090. std::string cert;
  15091. read_file(SERVER_CERT2_FILE, cert);
  15092. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15093. cli.enable_server_certificate_verification(true);
  15094. cli.set_follow_location(true);
  15095. cli.set_connection_timeout(30);
  15096. auto res = cli.Get("/index");
  15097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15098. ASSERT_EQ(StatusCode::OK_200, res->status);
  15099. }
  15100. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15101. // so a host signed by a system CA verifies even though a custom CA is set
  15102. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15103. std::string cert;
  15104. read_file(SERVER_CERT2_FILE, cert);
  15105. SSLClient cli("google.com");
  15106. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15107. cli.enable_system_ca(true);
  15108. cli.enable_server_certificate_verification(true);
  15109. auto res = cli.Get("/");
  15110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15111. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15112. }
  15113. // The custom CA remains effective when combined with the system CA
  15114. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15115. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15116. ASSERT_TRUE(svr.is_valid());
  15117. svr.Get("/test", [&](const Request &, Response &res) {
  15118. res.set_content("test", "text/plain");
  15119. });
  15120. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15121. auto se = detail::scope_exit([&] {
  15122. svr.stop();
  15123. t.join();
  15124. ASSERT_FALSE(svr.is_running());
  15125. });
  15126. svr.wait_until_ready();
  15127. SSLClient cli("127.0.0.1", PORT);
  15128. std::string cert;
  15129. read_file(SERVER_CERT2_FILE, cert);
  15130. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15131. cli.enable_system_ca(true);
  15132. cli.enable_server_certificate_verification(true);
  15133. cli.set_connection_timeout(30);
  15134. auto res = cli.Get("/test");
  15135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15136. ASSERT_EQ(StatusCode::OK_200, res->status);
  15137. }
  15138. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15139. // skip chain verification entirely (only the certificate identity was
  15140. // checked), so a server presenting an untrusted certificate with a matching
  15141. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15142. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15143. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15144. ASSERT_TRUE(svr.is_valid());
  15145. svr.Get("/test", [&](const Request &, Response &res) {
  15146. res.set_content("test", "text/plain");
  15147. });
  15148. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15149. auto se = detail::scope_exit([&] {
  15150. svr.stop();
  15151. t.join();
  15152. ASSERT_FALSE(svr.is_running());
  15153. });
  15154. svr.wait_until_ready();
  15155. SSLClient cli("127.0.0.1", PORT);
  15156. std::string cert;
  15157. // A trusted CA that did not sign the server certificate. The server cert
  15158. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15159. // this connection.
  15160. read_file(CLIENT_CA_CERT_FILE, cert);
  15161. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15162. cli.enable_server_certificate_verification(true);
  15163. cli.set_connection_timeout(30);
  15164. auto res = cli.Get("/test");
  15165. ASSERT_FALSE(res);
  15166. }
  15167. // enable_system_ca(false) prevents system CA loading entirely
  15168. TEST(SSLClientTest, DisableSystemCa_Online) {
  15169. SSLClient cli("google.com");
  15170. cli.enable_system_ca(false);
  15171. cli.enable_server_certificate_verification(true);
  15172. auto res = cli.Get("/");
  15173. ASSERT_FALSE(res);
  15174. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15175. // itself when the CA chain is empty
  15176. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15177. res.error() == Error::SSLConnection);
  15178. }
  15179. // The universal Client forwards enable_system_ca()
  15180. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15181. std::string cert;
  15182. read_file(SERVER_CERT2_FILE, cert);
  15183. Client cli("https://google.com");
  15184. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15185. cli.enable_system_ca(true);
  15186. cli.enable_server_certificate_verification(true);
  15187. auto res = cli.Get("/");
  15188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15189. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15190. }
  15191. // The system CA policy must carry over to the client created internally for
  15192. // following a cross-host HTTPS redirect
  15193. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15194. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15195. ASSERT_TRUE(svr.is_valid());
  15196. svr.Get("/index", [&](const Request &, Response &res) {
  15197. res.set_redirect("https://www.google.com/");
  15198. });
  15199. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15200. auto se = detail::scope_exit([&] {
  15201. svr.stop();
  15202. t.join();
  15203. ASSERT_FALSE(svr.is_running());
  15204. });
  15205. svr.wait_until_ready();
  15206. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15207. std::string cert;
  15208. read_file(SERVER_CERT2_FILE, cert);
  15209. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15210. cli.enable_system_ca(true);
  15211. cli.enable_server_certificate_verification(true);
  15212. cli.set_follow_location(true);
  15213. cli.set_connection_timeout(30);
  15214. // Receiving any response proves the redirect client completed the TLS
  15215. // handshake with a system-CA-signed host
  15216. auto res = cli.Get("/index");
  15217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15218. }
  15219. TEST(MultipartFormDataTest, LargeData) {
  15220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15221. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15222. const ContentReader &content_reader) {
  15223. if (req.is_multipart_form_data()) {
  15224. std::vector<FormData> items;
  15225. content_reader(
  15226. [&](const FormData &file) {
  15227. items.push_back(file);
  15228. return true;
  15229. },
  15230. [&](const char *data, size_t data_length) {
  15231. items.back().content.append(data, data_length);
  15232. return true;
  15233. });
  15234. EXPECT_TRUE(std::string(items[0].name) == "document");
  15235. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15236. EXPECT_TRUE(items[0].filename == "2MB_data");
  15237. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15238. EXPECT_TRUE(items[1].name == "hello");
  15239. EXPECT_TRUE(items[1].content == "world");
  15240. EXPECT_TRUE(items[1].filename == "");
  15241. EXPECT_TRUE(items[1].content_type == "");
  15242. } else {
  15243. std::string body;
  15244. content_reader([&](const char *data, size_t data_length) {
  15245. body.append(data, data_length);
  15246. return true;
  15247. });
  15248. }
  15249. });
  15250. auto port = svr.bind_to_any_port(HOST);
  15251. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15252. auto se = detail::scope_exit([&] {
  15253. svr.stop();
  15254. t.join();
  15255. ASSERT_FALSE(svr.is_running());
  15256. });
  15257. svr.wait_until_ready();
  15258. {
  15259. std::string data(1024 * 1024 * 2, '.');
  15260. std::stringstream buffer;
  15261. buffer << data;
  15262. SSLClient cli(HOST, port);
  15263. cli.enable_server_certificate_verification(false);
  15264. UploadFormDataItems items{
  15265. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15266. {"hello", "world", "", ""},
  15267. };
  15268. auto res = cli.Post("/post", items);
  15269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15270. ASSERT_EQ(StatusCode::OK_200, res->status);
  15271. }
  15272. }
  15273. TEST(MultipartFormDataTest, DataProviderItems) {
  15274. std::random_device seed_gen;
  15275. std::mt19937 random(seed_gen());
  15276. std::string rand1;
  15277. rand1.resize(1000);
  15278. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15279. std::string rand2;
  15280. rand2.resize(3000);
  15281. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15282. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15283. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15284. const ContentReader &content_reader) {
  15285. ASSERT_FALSE(req.is_multipart_form_data());
  15286. std::string body;
  15287. content_reader([&](const char *data, size_t data_length) {
  15288. body.append(data, data_length);
  15289. return true;
  15290. });
  15291. EXPECT_EQ(body, "");
  15292. });
  15293. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15294. const ContentReader &content_reader) {
  15295. ASSERT_TRUE(req.is_multipart_form_data());
  15296. std::vector<FormData> items;
  15297. content_reader(
  15298. [&](const FormData &file) {
  15299. items.push_back(file);
  15300. return true;
  15301. },
  15302. [&](const char *data, size_t data_length) {
  15303. items.back().content.append(data, data_length);
  15304. return true;
  15305. });
  15306. ASSERT_TRUE(items.size() == 2);
  15307. EXPECT_EQ(std::string(items[0].name), "name1");
  15308. EXPECT_EQ(items[0].content, "Testing123");
  15309. EXPECT_EQ(items[0].filename, "filename1");
  15310. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15311. EXPECT_EQ(items[1].name, "name2");
  15312. EXPECT_EQ(items[1].content, "Testing456");
  15313. EXPECT_EQ(items[1].filename, "");
  15314. EXPECT_EQ(items[1].content_type, "");
  15315. });
  15316. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15317. const ContentReader &content_reader) {
  15318. ASSERT_TRUE(req.is_multipart_form_data());
  15319. std::vector<FormData> items;
  15320. content_reader(
  15321. [&](const FormData &file) {
  15322. items.push_back(file);
  15323. return true;
  15324. },
  15325. [&](const char *data, size_t data_length) {
  15326. items.back().content.append(data, data_length);
  15327. return true;
  15328. });
  15329. ASSERT_TRUE(items.size() == 2);
  15330. EXPECT_EQ(items[0].name, "name3");
  15331. EXPECT_EQ(items[0].content, rand1);
  15332. EXPECT_EQ(items[0].filename, "filename3");
  15333. EXPECT_EQ(items[0].content_type, "");
  15334. EXPECT_EQ(items[1].name, "name4");
  15335. EXPECT_EQ(items[1].content, rand2);
  15336. EXPECT_EQ(items[1].filename, "filename4");
  15337. EXPECT_EQ(items[1].content_type, "");
  15338. });
  15339. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15340. const ContentReader &content_reader) {
  15341. ASSERT_TRUE(req.is_multipart_form_data());
  15342. std::vector<FormData> items;
  15343. content_reader(
  15344. [&](const FormData &file) {
  15345. items.push_back(file);
  15346. return true;
  15347. },
  15348. [&](const char *data, size_t data_length) {
  15349. items.back().content.append(data, data_length);
  15350. return true;
  15351. });
  15352. ASSERT_TRUE(items.size() == 4);
  15353. EXPECT_EQ(std::string(items[0].name), "name1");
  15354. EXPECT_EQ(items[0].content, "Testing123");
  15355. EXPECT_EQ(items[0].filename, "filename1");
  15356. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15357. EXPECT_EQ(items[1].name, "name2");
  15358. EXPECT_EQ(items[1].content, "Testing456");
  15359. EXPECT_EQ(items[1].filename, "");
  15360. EXPECT_EQ(items[1].content_type, "");
  15361. EXPECT_EQ(items[2].name, "name3");
  15362. EXPECT_EQ(items[2].content, rand1);
  15363. EXPECT_EQ(items[2].filename, "filename3");
  15364. EXPECT_EQ(items[2].content_type, "");
  15365. EXPECT_EQ(items[3].name, "name4");
  15366. EXPECT_EQ(items[3].content, rand2);
  15367. EXPECT_EQ(items[3].filename, "filename4");
  15368. EXPECT_EQ(items[3].content_type, "");
  15369. });
  15370. auto port = svr.bind_to_any_port("localhost");
  15371. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15372. auto se = detail::scope_exit([&] {
  15373. svr.stop();
  15374. t.join();
  15375. ASSERT_FALSE(svr.is_running());
  15376. });
  15377. svr.wait_until_ready();
  15378. {
  15379. SSLClient cli("localhost", port);
  15380. cli.enable_server_certificate_verification(false);
  15381. UploadFormDataItems items{
  15382. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15383. {"name2", "Testing456", "", ""}, // not a file
  15384. };
  15385. {
  15386. auto res = cli.Post("/post-none", {}, {}, {});
  15387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15388. ASSERT_EQ(StatusCode::OK_200, res->status);
  15389. }
  15390. FormDataProviderItems providers;
  15391. {
  15392. auto res =
  15393. cli.Post("/post-items", {}, items, providers); // empty providers
  15394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15395. ASSERT_EQ(StatusCode::OK_200, res->status);
  15396. }
  15397. providers.push_back({"name3",
  15398. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15399. // test the offset is given correctly at each step
  15400. if (!offset)
  15401. sink.os.write(rand1.data(), 30);
  15402. else if (offset == 30)
  15403. sink.os.write(rand1.data() + 30, 300);
  15404. else if (offset == 330)
  15405. sink.os.write(rand1.data() + 330, 670);
  15406. else if (offset == rand1.size())
  15407. sink.done();
  15408. return true;
  15409. },
  15410. "filename3",
  15411. {}});
  15412. providers.push_back({"name4",
  15413. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15414. // test the offset is given correctly at each step
  15415. if (!offset)
  15416. sink.os.write(rand2.data(), 2000);
  15417. else if (offset == 2000)
  15418. sink.os.write(rand2.data() + 2000, 1);
  15419. else if (offset == 2001)
  15420. sink.os.write(rand2.data() + 2001, 999);
  15421. else if (offset == rand2.size())
  15422. sink.done();
  15423. return true;
  15424. },
  15425. "filename4",
  15426. {}});
  15427. {
  15428. auto res = cli.Post("/post-providers", {}, {}, providers);
  15429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15430. ASSERT_EQ(StatusCode::OK_200, res->status);
  15431. }
  15432. {
  15433. auto res = cli.Post("/post-both", {}, items, providers);
  15434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15435. ASSERT_EQ(StatusCode::OK_200, res->status);
  15436. }
  15437. }
  15438. }
  15439. TEST(MultipartFormDataTest, BadHeader) {
  15440. Server svr;
  15441. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15442. res.set_content("ok", "text/plain");
  15443. });
  15444. thread t = thread([&] { svr.listen(HOST, PORT); });
  15445. auto se = detail::scope_exit([&] {
  15446. svr.stop();
  15447. t.join();
  15448. ASSERT_FALSE(svr.is_running());
  15449. });
  15450. svr.wait_until_ready();
  15451. const std::string body =
  15452. "This is the preamble. It is to be ignored, though it\r\n"
  15453. "is a handy place for composition agents to include an\r\n"
  15454. "explanatory note to non-MIME conformant readers.\r\n"
  15455. "\r\n"
  15456. "\r\n"
  15457. "--simple boundary\r\n"
  15458. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15459. ": BAD...\r\n"
  15460. "\r\n"
  15461. "value1\r\n"
  15462. "--simple boundary\r\n"
  15463. "Content-Disposition: form-data; name=\"field2\"; "
  15464. "filename=\"example.txt\"\r\n"
  15465. "\r\n"
  15466. "value2\r\n"
  15467. "--simple boundary--\r\n"
  15468. "This is the epilogue. It is also to be ignored.\r\n";
  15469. std::string content_type =
  15470. R"(multipart/form-data; boundary="simple boundary")";
  15471. Client cli(HOST, PORT);
  15472. auto res = cli.Post("/post", body, content_type.c_str());
  15473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15474. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15475. }
  15476. TEST(MultipartFormDataTest, WithPreamble) {
  15477. Server svr;
  15478. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15479. res.set_content("ok", "text/plain");
  15480. });
  15481. thread t = thread([&] { svr.listen(HOST, PORT); });
  15482. auto se = detail::scope_exit([&] {
  15483. svr.stop();
  15484. t.join();
  15485. ASSERT_FALSE(svr.is_running());
  15486. });
  15487. svr.wait_until_ready();
  15488. const std::string body =
  15489. "This is the preamble. It is to be ignored, though it\r\n"
  15490. "is a handy place for composition agents to include an\r\n"
  15491. "explanatory note to non-MIME conformant readers.\r\n"
  15492. "\r\n"
  15493. "\r\n"
  15494. "--simple boundary\r\n"
  15495. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15496. "\r\n"
  15497. "value1\r\n"
  15498. "--simple boundary\r\n"
  15499. "Content-Disposition: form-data; name=\"field2\"; "
  15500. "filename=\"example.txt\"\r\n"
  15501. "\r\n"
  15502. "value2\r\n"
  15503. "--simple boundary--\r\n"
  15504. "This is the epilogue. It is also to be ignored.\r\n";
  15505. std::string content_type =
  15506. R"(multipart/form-data; boundary="simple boundary")";
  15507. Client cli(HOST, PORT);
  15508. auto res = cli.Post("/post", body, content_type.c_str());
  15509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15510. EXPECT_EQ(StatusCode::OK_200, res->status);
  15511. }
  15512. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15514. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15515. const ContentReader &content_reader) {
  15516. if (req.is_multipart_form_data()) {
  15517. std::vector<FormData> items;
  15518. content_reader(
  15519. [&](const FormData &file) {
  15520. items.push_back(file);
  15521. return true;
  15522. },
  15523. [&](const char *data, size_t data_length) {
  15524. items.back().content.append(data, data_length);
  15525. return true;
  15526. });
  15527. EXPECT_TRUE(std::string(items[0].name) == "document");
  15528. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15529. EXPECT_TRUE(items[0].filename == "2MB_data");
  15530. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15531. EXPECT_TRUE(items[1].name == "hello");
  15532. EXPECT_TRUE(items[1].content == "world");
  15533. EXPECT_TRUE(items[1].filename == "");
  15534. EXPECT_TRUE(items[1].content_type == "");
  15535. } else {
  15536. std::string body;
  15537. content_reader([&](const char *data, size_t data_length) {
  15538. body.append(data, data_length);
  15539. return true;
  15540. });
  15541. }
  15542. });
  15543. auto port = svr.bind_to_any_port("localhost");
  15544. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15545. auto se = detail::scope_exit([&] {
  15546. svr.stop();
  15547. t.join();
  15548. ASSERT_FALSE(svr.is_running());
  15549. });
  15550. svr.wait_until_ready();
  15551. {
  15552. std::string data(1024 * 1024 * 2, '.');
  15553. std::stringstream buffer;
  15554. buffer << data;
  15555. SSLClient cli("localhost", port);
  15556. cli.enable_server_certificate_verification(false);
  15557. UploadFormDataItems items{
  15558. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15559. {"hello", "world", "", ""},
  15560. };
  15561. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15563. ASSERT_EQ(StatusCode::OK_200, res->status);
  15564. }
  15565. }
  15566. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15567. std::string data(1024 * 1024 * 2, '&');
  15568. std::stringstream buffer;
  15569. buffer << data;
  15570. Client cli("https://localhost:8080");
  15571. UploadFormDataItems items{
  15572. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15573. {"hello", "world", "", ""},
  15574. };
  15575. for (const char &c : " \t\r\n") {
  15576. auto res =
  15577. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15578. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15579. ASSERT_FALSE(res);
  15580. }
  15581. }
  15582. TEST(MultipartFormDataTest, PutFormData) {
  15583. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15584. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15585. const ContentReader &content_reader) {
  15586. if (req.is_multipart_form_data()) {
  15587. std::vector<FormData> items;
  15588. content_reader(
  15589. [&](const FormData &file) {
  15590. items.push_back(file);
  15591. return true;
  15592. },
  15593. [&](const char *data, size_t data_length) {
  15594. items.back().content.append(data, data_length);
  15595. return true;
  15596. });
  15597. EXPECT_TRUE(std::string(items[0].name) == "document");
  15598. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15599. EXPECT_TRUE(items[0].filename == "2MB_data");
  15600. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15601. EXPECT_TRUE(items[1].name == "hello");
  15602. EXPECT_TRUE(items[1].content == "world");
  15603. EXPECT_TRUE(items[1].filename == "");
  15604. EXPECT_TRUE(items[1].content_type == "");
  15605. } else {
  15606. std::string body;
  15607. content_reader([&](const char *data, size_t data_length) {
  15608. body.append(data, data_length);
  15609. return true;
  15610. });
  15611. }
  15612. });
  15613. auto port = svr.bind_to_any_port("localhost");
  15614. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15615. auto se = detail::scope_exit([&] {
  15616. svr.stop();
  15617. t.join();
  15618. ASSERT_FALSE(svr.is_running());
  15619. });
  15620. svr.wait_until_ready();
  15621. {
  15622. std::string data(1024 * 1024 * 2, '&');
  15623. std::stringstream buffer;
  15624. buffer << data;
  15625. SSLClient cli("localhost", port);
  15626. cli.enable_server_certificate_verification(false);
  15627. UploadFormDataItems items{
  15628. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15629. {"hello", "world", "", ""},
  15630. };
  15631. auto res = cli.Put("/put", items);
  15632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15633. ASSERT_EQ(StatusCode::OK_200, res->status);
  15634. }
  15635. }
  15636. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15637. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15638. svr.Put("/put_customboundary",
  15639. [&](const Request &req, const Response & /*res*/,
  15640. const ContentReader &content_reader) {
  15641. if (req.is_multipart_form_data()) {
  15642. std::vector<FormData> items;
  15643. content_reader(
  15644. [&](const FormData &file) {
  15645. items.push_back(file);
  15646. return true;
  15647. },
  15648. [&](const char *data, size_t data_length) {
  15649. items.back().content.append(data, data_length);
  15650. return true;
  15651. });
  15652. EXPECT_TRUE(std::string(items[0].name) == "document");
  15653. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15654. EXPECT_TRUE(items[0].filename == "2MB_data");
  15655. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15656. EXPECT_TRUE(items[1].name == "hello");
  15657. EXPECT_TRUE(items[1].content == "world");
  15658. EXPECT_TRUE(items[1].filename == "");
  15659. EXPECT_TRUE(items[1].content_type == "");
  15660. } else {
  15661. std::string body;
  15662. content_reader([&](const char *data, size_t data_length) {
  15663. body.append(data, data_length);
  15664. return true;
  15665. });
  15666. }
  15667. });
  15668. auto port = svr.bind_to_any_port("localhost");
  15669. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15670. auto se = detail::scope_exit([&] {
  15671. svr.stop();
  15672. t.join();
  15673. ASSERT_FALSE(svr.is_running());
  15674. });
  15675. svr.wait_until_ready();
  15676. {
  15677. std::string data(1024 * 1024 * 2, '&');
  15678. std::stringstream buffer;
  15679. buffer << data;
  15680. SSLClient cli("localhost", port);
  15681. cli.enable_server_certificate_verification(false);
  15682. UploadFormDataItems items{
  15683. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15684. {"hello", "world", "", ""},
  15685. };
  15686. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15688. ASSERT_EQ(StatusCode::OK_200, res->status);
  15689. }
  15690. }
  15691. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15692. std::string data(1024 * 1024 * 2, '&');
  15693. std::stringstream buffer;
  15694. buffer << data;
  15695. Client cli("https://localhost:8080");
  15696. cli.enable_server_certificate_verification(false);
  15697. UploadFormDataItems items{
  15698. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15699. {"hello", "world", "", ""},
  15700. };
  15701. for (const char &c : " \t\r\n") {
  15702. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15703. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15704. ASSERT_FALSE(res);
  15705. }
  15706. }
  15707. TEST(MultipartFormDataTest, AlternateFilename) {
  15708. auto handled = false;
  15709. Server svr;
  15710. svr.Post("/test", [&](const Request &req, Response &res) {
  15711. ASSERT_EQ(2u, req.form.files.size());
  15712. ASSERT_EQ(1u, req.form.fields.size());
  15713. // Test files
  15714. const auto &file1 = req.form.get_file("file1");
  15715. ASSERT_EQ("file1", file1.name);
  15716. ASSERT_EQ("A.txt", file1.filename);
  15717. ASSERT_EQ("text/plain", file1.content_type);
  15718. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15719. const auto &file2 = req.form.get_file("file2");
  15720. ASSERT_EQ("file2", file2.name);
  15721. ASSERT_EQ("a.html", file2.filename);
  15722. ASSERT_EQ("text/html", file2.content_type);
  15723. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15724. file2.content);
  15725. // Test text field
  15726. const auto &text = req.form.get_field("text");
  15727. ASSERT_EQ("text default", text);
  15728. res.set_content("ok", "text/plain");
  15729. handled = true;
  15730. });
  15731. thread t = thread([&] { svr.listen(HOST, PORT); });
  15732. auto se = detail::scope_exit([&] {
  15733. svr.stop();
  15734. t.join();
  15735. ASSERT_FALSE(svr.is_running());
  15736. ASSERT_TRUE(handled);
  15737. });
  15738. svr.wait_until_ready();
  15739. auto req = "POST /test HTTP/1.1\r\n"
  15740. "Host: localhost\r\n"
  15741. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15742. "Content-Length: 399\r\n"
  15743. "\r\n"
  15744. "----------\r\n"
  15745. "Content-Disposition: form-data; name=\"text\"\r\n"
  15746. "\r\n"
  15747. "text default\r\n"
  15748. "----------\r\n"
  15749. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15750. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15751. "Content-Type: text/plain\r\n"
  15752. "\r\n"
  15753. "Content of a.txt.\r\n"
  15754. "\r\n"
  15755. "----------\r\n"
  15756. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15757. "\"a.html\"\r\n"
  15758. "Content-Type: text/html\r\n"
  15759. "\r\n"
  15760. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15761. "\r\n"
  15762. "------------\r\n";
  15763. ASSERT_TRUE(send_request(1, req));
  15764. }
  15765. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15766. auto handled = false;
  15767. Server svr;
  15768. svr.Post("/test", [&](const Request &req, Response &res) {
  15769. // Case-insensitive "utf-8''" prefix with a long value
  15770. const auto &file = req.form.get_file("file1");
  15771. ASSERT_EQ("file1", file.name);
  15772. // 8000 chars exercises both the Content-Disposition parser and the
  15773. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15774. // Prior to the fix, std::regex_match on this header would cause O(N)
  15775. // stack recursion in libstdc++, leading to SIGSEGV.
  15776. std::string expected_filename(8000, 'A');
  15777. ASSERT_EQ(expected_filename, file.filename);
  15778. res.set_content("ok", "text/plain");
  15779. handled = true;
  15780. });
  15781. thread t = thread([&] { svr.listen(HOST, PORT); });
  15782. auto se = detail::scope_exit([&] {
  15783. svr.stop();
  15784. t.join();
  15785. ASSERT_FALSE(svr.is_running());
  15786. ASSERT_TRUE(handled);
  15787. });
  15788. svr.wait_until_ready();
  15789. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15790. // Regression test for GHSA-qq6v-r583-3h69
  15791. std::string long_filename(8000, 'A');
  15792. std::string body = "----------\r\n"
  15793. "Content-Disposition: form-data; name=\"file1\"; "
  15794. "filename*=\"Utf-8''" +
  15795. long_filename +
  15796. "\"\r\n"
  15797. "\r\n"
  15798. "hello\r\n"
  15799. "------------\r\n";
  15800. auto req = "POST /test HTTP/1.1\r\n"
  15801. "Host: localhost\r\n"
  15802. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15803. "Content-Length: " +
  15804. std::to_string(body.size()) + "\r\n\r\n" + body;
  15805. ASSERT_TRUE(send_request(1, req));
  15806. }
  15807. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15808. auto handled = false;
  15809. Server svr;
  15810. svr.Post("/test", [&](const Request &req, Response &) {
  15811. ASSERT_EQ(2u, req.form.fields.size());
  15812. const auto &text1 = req.form.get_field("text1");
  15813. ASSERT_EQ("text1", text1);
  15814. const auto &text2 = req.form.get_field("text2");
  15815. ASSERT_EQ("text2", text2);
  15816. handled = true;
  15817. });
  15818. thread t = thread([&] { svr.listen(HOST, PORT); });
  15819. auto se = detail::scope_exit([&] {
  15820. svr.stop();
  15821. t.join();
  15822. ASSERT_FALSE(svr.is_running());
  15823. ASSERT_TRUE(handled);
  15824. });
  15825. svr.wait_until_ready();
  15826. auto req = "POST /test HTTP/1.1\r\n"
  15827. "Host: localhost\r\n"
  15828. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15829. "Content-Length: 146\r\n"
  15830. "\r\n----------\r\n"
  15831. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15832. "\r\n"
  15833. "text1"
  15834. "\r\n----------\r\n"
  15835. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15836. "\r\n"
  15837. "text2"
  15838. "\r\n------------";
  15839. std::string response;
  15840. ASSERT_TRUE(send_request(1, req, &response));
  15841. ASSERT_EQ("200", response.substr(9, 3));
  15842. }
  15843. TEST(MultipartFormDataTest, ContentLength) {
  15844. auto handled = false;
  15845. Server svr;
  15846. svr.Post("/test", [&](const Request &req, Response &) {
  15847. ASSERT_EQ(2u, req.form.fields.size());
  15848. const auto &text1 = req.form.get_field("text1");
  15849. ASSERT_EQ("text1", text1);
  15850. const auto &text2 = req.form.get_field("text2");
  15851. ASSERT_EQ("text2", text2);
  15852. handled = true;
  15853. });
  15854. thread t = thread([&] { svr.listen(HOST, PORT); });
  15855. auto se = detail::scope_exit([&] {
  15856. svr.stop();
  15857. t.join();
  15858. ASSERT_FALSE(svr.is_running());
  15859. ASSERT_TRUE(handled);
  15860. });
  15861. svr.wait_until_ready();
  15862. auto req = "POST /test HTTP/1.1\r\n"
  15863. "Host: localhost\r\n"
  15864. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15865. "Content-Length: 167\r\n"
  15866. "\r\n----------\r\n"
  15867. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15868. "Content-Length: 5\r\n"
  15869. "\r\n"
  15870. "text1"
  15871. "\r\n----------\r\n"
  15872. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15873. "\r\n"
  15874. "text2"
  15875. "\r\n------------\r\n";
  15876. std::string response;
  15877. ASSERT_TRUE(send_request(1, req, &response));
  15878. ASSERT_EQ("200", response.substr(9, 3));
  15879. }
  15880. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15881. auto handled = false;
  15882. Server svr;
  15883. svr.Post("/test", [&](const Request &req, Response &) {
  15884. ASSERT_EQ(2u, req.form.fields.size());
  15885. const auto &text1 = req.form.get_field("text1");
  15886. ASSERT_EQ("text1", text1);
  15887. // TODO: Add header access for text fields if needed
  15888. const auto &text2 = req.form.get_field("text2");
  15889. ASSERT_EQ("text2", text2);
  15890. // TODO: Header access for text fields needs to be implemented
  15891. // auto &headers = it->second.headers;
  15892. // ASSERT_EQ(3U, headers.size());
  15893. // auto custom_header = headers.find("x-whatever");
  15894. // ASSERT_TRUE(custom_header != headers.end());
  15895. // ASSERT_NE("customvalue", custom_header->second);
  15896. // ASSERT_EQ("CustomValue", custom_header->second);
  15897. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15898. handled = true;
  15899. });
  15900. thread t = thread([&] { svr.listen(HOST, PORT); });
  15901. auto se = detail::scope_exit([&] {
  15902. svr.stop();
  15903. t.join();
  15904. ASSERT_FALSE(svr.is_running());
  15905. ASSERT_TRUE(handled);
  15906. });
  15907. svr.wait_until_ready();
  15908. auto req = "POST /test HTTP/1.1\r\n"
  15909. "Host: localhost\r\n"
  15910. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15911. "Content-Length: 232\r\n"
  15912. "\r\n----------\r\n"
  15913. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15914. "Content-Length: 5\r\n"
  15915. "X-Test: 1\r\n"
  15916. "\r\n"
  15917. "text1"
  15918. "\r\n----------\r\n"
  15919. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15920. "Content-Type: text/plain\r\n"
  15921. "X-Whatever: CustomValue\r\n"
  15922. "\r\n"
  15923. "text2"
  15924. "\r\n------------\r\n"
  15925. "That should be disregarded. Not even read";
  15926. std::string response;
  15927. ASSERT_TRUE(send_request(1, req, &response));
  15928. ASSERT_EQ("200", response.substr(9, 3));
  15929. }
  15930. TEST(MultipartFormDataTest, LargeHeader) {
  15931. auto handled = false;
  15932. Server svr;
  15933. svr.Post("/test", [&](const Request &req, Response &) {
  15934. ASSERT_EQ(1u, req.form.fields.size());
  15935. const auto &text = req.form.get_field("name1");
  15936. ASSERT_EQ("text1", text);
  15937. handled = true;
  15938. });
  15939. thread t = thread([&] { svr.listen(HOST, PORT); });
  15940. auto se = detail::scope_exit([&] {
  15941. svr.stop();
  15942. t.join();
  15943. ASSERT_FALSE(svr.is_running());
  15944. ASSERT_TRUE(handled);
  15945. });
  15946. svr.wait_until_ready();
  15947. auto boundary = std::string("cpp-httplib-multipart-data");
  15948. std::string content = "--" + boundary +
  15949. "\r\n"
  15950. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15951. "\r\n"
  15952. "text1\r\n"
  15953. "--" +
  15954. boundary + "--\r\n";
  15955. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15956. "Host: localhost\r\n"
  15957. "Content-Type: multipart/form-data;boundary=" +
  15958. boundary +
  15959. "\r\n"
  15960. "Content-Length: " +
  15961. std::to_string(content.size()) +
  15962. "\r\n"
  15963. "Dummy-Header: ";
  15964. std::string header_suffix = "\r\n"
  15965. "\r\n";
  15966. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15967. size_t header_dummy_size =
  15968. read_buff_size -
  15969. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15970. auto header_dummy = std::string(header_dummy_size, '@');
  15971. auto req = header_prefix + header_dummy + header_suffix + content;
  15972. std::string response;
  15973. ASSERT_TRUE(send_request(1, req, &response));
  15974. ASSERT_EQ("200", response.substr(9, 3));
  15975. }
  15976. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15977. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15978. // (not chunked Transfer-Encoding) after the streaming refactor.
  15979. auto handled = false;
  15980. Server svr;
  15981. svr.Post("/upload", [&](const Request &req, Response &res) {
  15982. auto cl_it = req.headers.find("Content-Length");
  15983. EXPECT_TRUE(cl_it != req.headers.end());
  15984. auto te_it = req.headers.find("Transfer-Encoding");
  15985. EXPECT_TRUE(te_it == req.headers.end());
  15986. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15987. res.set_content("ok", "text/plain");
  15988. handled = true;
  15989. });
  15990. auto port = svr.bind_to_any_port(HOST);
  15991. auto t = thread([&] { svr.listen_after_bind(); });
  15992. auto se = detail::scope_exit([&] {
  15993. svr.stop();
  15994. t.join();
  15995. ASSERT_FALSE(svr.is_running());
  15996. ASSERT_TRUE(handled);
  15997. });
  15998. svr.wait_until_ready();
  15999. UploadFormDataItems items = {
  16000. {"field1", "hello", "", "text/plain"},
  16001. {"file1", "world", "test.txt", "application/octet-stream"},
  16002. };
  16003. Client cli(HOST, port);
  16004. auto res = cli.Post("/upload", {}, items);
  16005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16006. EXPECT_EQ(StatusCode::OK_200, res->status);
  16007. }
  16008. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16009. // Verify that make_multipart_content_provider coalesces many small segments
  16010. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16011. constexpr size_t kItemCount = 1000;
  16012. UploadFormDataItems items;
  16013. items.reserve(kItemCount);
  16014. for (size_t i = 0; i < kItemCount; i++) {
  16015. items.push_back(
  16016. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16017. }
  16018. const std::string boundary = "----test-boundary";
  16019. auto content_length = detail::get_multipart_content_length(items, boundary);
  16020. auto provider = detail::make_multipart_content_provider(items, boundary);
  16021. // Drive the provider the same way write_content_with_progress does
  16022. size_t write_count = 0;
  16023. size_t total_bytes = 0;
  16024. DataSink sink;
  16025. size_t offset = 0;
  16026. sink.write = [&](const char *d, size_t l) -> bool {
  16027. (void)d;
  16028. write_count++;
  16029. total_bytes += l;
  16030. offset += l;
  16031. return true;
  16032. };
  16033. sink.is_writable = []() -> bool { return true; };
  16034. while (offset < content_length) {
  16035. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16036. }
  16037. EXPECT_EQ(content_length, total_bytes);
  16038. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16039. // With buffering into 64KB blocks, write_count should be much smaller.
  16040. auto segment_count = 3 * kItemCount + 1;
  16041. EXPECT_LT(write_count, segment_count / 10);
  16042. }
  16043. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16044. // Integration test: send many UploadFormDataItems and verify the server
  16045. // receives all of them correctly (#2410).
  16046. constexpr size_t kItemCount = 500;
  16047. auto handled = false;
  16048. Server svr;
  16049. svr.Post("/upload", [&](const Request &req, Response &res) {
  16050. EXPECT_EQ(kItemCount, req.form.fields.size());
  16051. for (size_t i = 0; i < kItemCount; i++) {
  16052. auto key = "field" + std::to_string(i);
  16053. auto val = "value" + std::to_string(i);
  16054. auto it = req.form.fields.find(key);
  16055. if (it != req.form.fields.end()) {
  16056. EXPECT_EQ(val, it->second.content);
  16057. } else {
  16058. ADD_FAILURE() << "Missing field: " << key;
  16059. }
  16060. }
  16061. res.set_content("ok", "text/plain");
  16062. handled = true;
  16063. });
  16064. auto port = svr.bind_to_any_port(HOST);
  16065. auto t = thread([&] { svr.listen_after_bind(); });
  16066. auto se = detail::scope_exit([&] {
  16067. svr.stop();
  16068. t.join();
  16069. ASSERT_FALSE(svr.is_running());
  16070. ASSERT_TRUE(handled);
  16071. });
  16072. svr.wait_until_ready();
  16073. UploadFormDataItems items;
  16074. items.reserve(kItemCount);
  16075. for (size_t i = 0; i < kItemCount; i++) {
  16076. items.push_back(
  16077. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16078. }
  16079. Client cli(HOST, port);
  16080. auto res = cli.Post("/upload", items);
  16081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16082. EXPECT_EQ(StatusCode::OK_200, res->status);
  16083. }
  16084. TEST(MultipartFormDataTest, MakeFileProvider) {
  16085. // Verify make_file_provider sends a file's contents correctly.
  16086. const std::string file_content(4096, 'Z');
  16087. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16088. {
  16089. std::ofstream ofs(tmp_path, std::ios::binary);
  16090. ofs.write(file_content.data(),
  16091. static_cast<std::streamsize>(file_content.size()));
  16092. }
  16093. auto handled = false;
  16094. Server svr;
  16095. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16096. const ContentReader &content_reader) {
  16097. ASSERT_TRUE(req.is_multipart_form_data());
  16098. std::vector<FormData> items;
  16099. content_reader(
  16100. [&](const FormData &file) {
  16101. items.push_back(file);
  16102. return true;
  16103. },
  16104. [&](const char *data, size_t data_length) {
  16105. items.back().content.append(data, data_length);
  16106. return true;
  16107. });
  16108. ASSERT_EQ(1u, items.size());
  16109. EXPECT_EQ("myfile", items[0].name);
  16110. EXPECT_EQ("data.bin", items[0].filename);
  16111. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16112. EXPECT_EQ(file_content, items[0].content);
  16113. handled = true;
  16114. });
  16115. auto port = svr.bind_to_any_port(HOST);
  16116. auto t = thread([&] { svr.listen_after_bind(); });
  16117. auto se = detail::scope_exit([&] {
  16118. svr.stop();
  16119. t.join();
  16120. ASSERT_FALSE(svr.is_running());
  16121. ASSERT_TRUE(handled);
  16122. std::remove(tmp_path.c_str());
  16123. });
  16124. svr.wait_until_ready();
  16125. FormDataProviderItems providers;
  16126. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16127. "application/octet-stream"));
  16128. Client cli(HOST, port);
  16129. auto res = cli.Post("/upload", {}, {}, providers);
  16130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16131. EXPECT_EQ(StatusCode::OK_200, res->status);
  16132. }
  16133. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16134. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16135. // (100) headers is rejected with a 400 Bad Request response.
  16136. Server svr;
  16137. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16138. res.set_content("ok", "text/plain");
  16139. });
  16140. thread t = thread([&] { svr.listen(HOST, PORT); });
  16141. auto se = detail::scope_exit([&] {
  16142. svr.stop();
  16143. t.join();
  16144. ASSERT_FALSE(svr.is_running());
  16145. });
  16146. svr.wait_until_ready();
  16147. // Build a multipart part with 101 custom headers (exceeding
  16148. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16149. std::stringstream body;
  16150. body << "--simpleboundary\r\n"
  16151. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16152. for (int i = 0; i < 101; i++) {
  16153. body << "X-Custom-Header-" << i << ": value\r\n";
  16154. }
  16155. body << "\r\n"
  16156. << "value1\r\n"
  16157. << "--simpleboundary--\r\n";
  16158. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16159. Client cli(HOST, PORT);
  16160. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16162. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16163. }
  16164. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16165. // A body that never contains the declared boundary must not be accumulated
  16166. // while the parser waits for it. Buffering it would also make every read
  16167. // rescan everything seen so far, which is quadratic in the body size.
  16168. Server svr;
  16169. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16170. res.set_content("ok", "text/plain");
  16171. });
  16172. auto port = svr.bind_to_any_port(HOST);
  16173. thread t = thread([&] { svr.listen_after_bind(); });
  16174. auto se = detail::scope_exit([&] {
  16175. svr.stop();
  16176. t.join();
  16177. ASSERT_FALSE(svr.is_running());
  16178. });
  16179. svr.wait_until_ready();
  16180. Client cli(HOST, port);
  16181. cli.set_read_timeout(60, 0);
  16182. cli.set_write_timeout(60, 0);
  16183. // '-' is the worst case: it matches the first character of the boundary, so
  16184. // every position has to be checked against it.
  16185. auto post_dashes = [&](size_t size) {
  16186. const std::string body(size, '-');
  16187. auto start = std::chrono::steady_clock::now();
  16188. auto res =
  16189. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16190. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16191. std::chrono::steady_clock::now() - start)
  16192. .count();
  16193. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16194. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16195. return ms;
  16196. };
  16197. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16198. // Windows.
  16199. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16200. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16201. // Comparing the two sizes rather than checking an absolute duration keeps
  16202. // this meaningful across build types and CI load, both of which move the
  16203. // absolute numbers by more than an order of magnitude. Four times the bytes
  16204. // costs about four times the time when parsing is linear, and about sixteen
  16205. // times when the body is buffered and rescanned.
  16206. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16207. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16208. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16209. << "ms, which suggests the body is being buffered and rescanned";
  16210. }
  16211. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16212. // A boundary can only be followed by CRLF or by "--", so anything else is
  16213. // malformed no matter what comes next. The parser must say so right away
  16214. // instead of buffering the rest of the declared body.
  16215. Server svr;
  16216. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16217. res.set_content("ok", "text/plain");
  16218. });
  16219. auto port = svr.bind_to_any_port(HOST);
  16220. thread t = thread([&] { svr.listen_after_bind(); });
  16221. auto se = detail::scope_exit([&] {
  16222. svr.stop();
  16223. t.join();
  16224. ASSERT_FALSE(svr.is_running());
  16225. });
  16226. svr.wait_until_ready();
  16227. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16228. // buffers instead of failing would still be waiting for the remaining bytes.
  16229. const std::string body = "--zzzz\r\n"
  16230. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16231. "\r\n"
  16232. "text1"
  16233. "\r\n--zzzzXX";
  16234. const std::string req = "POST /post HTTP/1.1\r\n"
  16235. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16236. "Content-Length: 1048576\r\n"
  16237. "\r\n" +
  16238. body;
  16239. std::string response;
  16240. ASSERT_TRUE(send_request(3, req, &response, port));
  16241. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16242. EXPECT_EQ("400", response.substr(9, 3));
  16243. }
  16244. // Posts a multipart body split into two writes, so that the server sees the
  16245. // split at whatever offset the caller chose, and expects the single "text1"
  16246. // field to come through.
  16247. static void expect_split_multipart_ok(const std::string &body1,
  16248. const std::string &body2) {
  16249. auto handled = false;
  16250. Server svr;
  16251. svr.Post("/post", [&](const Request &req, Response &) {
  16252. EXPECT_EQ(1u, req.form.fields.size());
  16253. EXPECT_EQ("text1", req.form.get_field("text1"));
  16254. handled = true;
  16255. });
  16256. auto port = svr.bind_to_any_port(HOST);
  16257. thread t = thread([&] { svr.listen_after_bind(); });
  16258. auto se = detail::scope_exit([&] {
  16259. svr.stop();
  16260. t.join();
  16261. ASSERT_FALSE(svr.is_running());
  16262. ASSERT_TRUE(handled);
  16263. });
  16264. svr.wait_until_ready();
  16265. // "Connection: close" makes the server close once it has answered, so the
  16266. // response drain ends immediately instead of idling until the read timeout.
  16267. const std::string head =
  16268. "POST /post HTTP/1.1\r\n"
  16269. "Host: localhost\r\n"
  16270. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16271. "Connection: close\r\n"
  16272. "Content-Length: " +
  16273. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16274. std::string response;
  16275. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16276. ASSERT_GE(response.size(), 12u) << "no response";
  16277. EXPECT_EQ("200", response.substr(9, 3));
  16278. }
  16279. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16280. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16281. // ignored, including when it does not arrive in the same read as the
  16282. // close-delimiter itself.
  16283. expect_split_multipart_ok("--zzzz\r\n"
  16284. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16285. "\r\n"
  16286. "text1"
  16287. "\r\n--zzzz--",
  16288. "\r\nthis epilogue must be ignored\r\n");
  16289. }
  16290. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16291. // The initial boundary may be preceded by a preamble of any length and may
  16292. // straddle a read boundary. Discarding data while waiting for it must not
  16293. // throw away a partial boundary sitting at the end of the buffer.
  16294. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16295. "zz\r\n"
  16296. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16297. "\r\n"
  16298. "text1"
  16299. "\r\n--zzzz--\r\n");
  16300. }
  16301. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16302. // The received boundary was only checked for being non-empty, so it could be
  16303. // as long as a header is allowed to be. The parser scans the body for
  16304. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16305. // costs a nearly full comparison at nearly every position, making the
  16306. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16307. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16308. Server svr;
  16309. svr.Post("/post", [](const Request &req, Response &res) {
  16310. EXPECT_EQ(1u, req.form.fields.size());
  16311. EXPECT_EQ("text1", req.form.get_field("text1"));
  16312. res.set_content("ok", "text/plain");
  16313. });
  16314. auto port = svr.bind_to_any_port(HOST);
  16315. thread t = thread([&] { svr.listen_after_bind(); });
  16316. auto se = detail::scope_exit([&] {
  16317. svr.stop();
  16318. t.join();
  16319. ASSERT_FALSE(svr.is_running());
  16320. });
  16321. svr.wait_until_ready();
  16322. Client cli(HOST, port);
  16323. auto post_with_boundary_of_length = [&](size_t len) {
  16324. const std::string boundary(len, 'a');
  16325. const std::string body =
  16326. "--" + boundary +
  16327. "\r\n"
  16328. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16329. "\r\n"
  16330. "text1"
  16331. "\r\n--" +
  16332. boundary + "--\r\n";
  16333. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16334. };
  16335. auto res = post_with_boundary_of_length(70);
  16336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16337. EXPECT_EQ(StatusCode::OK_200, res->status);
  16338. res = post_with_boundary_of_length(71);
  16339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16340. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16341. }
  16342. TEST(MakeFileBodyTest, Basic) {
  16343. const std::string file_content(4096, 'Z');
  16344. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16345. {
  16346. std::ofstream ofs(tmp_path, std::ios::binary);
  16347. ofs.write(file_content.data(),
  16348. static_cast<std::streamsize>(file_content.size()));
  16349. }
  16350. auto handled = false;
  16351. Server svr;
  16352. svr.Post("/upload", [&](const Request &req, Response &res) {
  16353. EXPECT_EQ(file_content, req.body);
  16354. handled = true;
  16355. res.status = StatusCode::OK_200;
  16356. });
  16357. auto port = svr.bind_to_any_port(HOST);
  16358. auto t = thread([&] { svr.listen_after_bind(); });
  16359. auto se = detail::scope_exit([&] {
  16360. svr.stop();
  16361. t.join();
  16362. ASSERT_FALSE(svr.is_running());
  16363. ASSERT_TRUE(handled);
  16364. std::remove(tmp_path.c_str());
  16365. });
  16366. svr.wait_until_ready();
  16367. auto fb = make_file_body(tmp_path);
  16368. ASSERT_GT(fb.first, 0u);
  16369. Client cli(HOST, port);
  16370. auto res =
  16371. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16373. EXPECT_EQ(StatusCode::OK_200, res->status);
  16374. }
  16375. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16376. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16377. {
  16378. std::ofstream ofs(path, std::ios::binary);
  16379. const std::string content(100, 'A');
  16380. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16381. }
  16382. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16383. auto body = make_file_body(path);
  16384. ASSERT_EQ(100u, body.first);
  16385. ASSERT_TRUE(static_cast<bool>(body.second));
  16386. // Rewritten shorter after its length was measured - and, on a server, after
  16387. // that length has already gone out as Content-Length.
  16388. {
  16389. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16390. const std::string content(10, 'A');
  16391. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16392. }
  16393. std::string written;
  16394. DataSink sink;
  16395. sink.write = [&](const char *d, size_t l) {
  16396. written.append(d, l);
  16397. return true;
  16398. };
  16399. // The provider has to report failure. write_content_with_progress() advances
  16400. // its offset only by what was written, so a provider that returns true
  16401. // without completing the length it promised is called again straight away,
  16402. // and again.
  16403. EXPECT_FALSE(body.second(0, body.first, sink));
  16404. EXPECT_EQ(std::string(10, 'A'), written);
  16405. }
  16406. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16407. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16408. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16409. {
  16410. std::ofstream ofs(path, std::ios::binary);
  16411. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16412. }
  16413. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16414. auto body = make_file_body(path);
  16415. ASSERT_EQ(content.size(), body.first);
  16416. ASSERT_TRUE(static_cast<bool>(body.second));
  16417. std::string written;
  16418. DataSink sink;
  16419. sink.write = [&](const char *d, size_t l) {
  16420. written.append(d, l);
  16421. return true;
  16422. };
  16423. EXPECT_TRUE(body.second(0, body.first, sink));
  16424. EXPECT_EQ(content, written);
  16425. }
  16426. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16427. static constexpr unsigned int number_of_tasks{1000000};
  16428. std::atomic_uint count{0};
  16429. std::unique_ptr<TaskQueue> task_queue{
  16430. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16431. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16432. auto queued = task_queue->enqueue(
  16433. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16434. EXPECT_TRUE(queued);
  16435. }
  16436. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16437. task_queue->shutdown();
  16438. #else
  16439. EXPECT_NO_THROW(task_queue->shutdown());
  16440. #endif
  16441. EXPECT_EQ(number_of_tasks, count.load());
  16442. }
  16443. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16444. static constexpr unsigned int number_of_tasks{1000000};
  16445. static constexpr unsigned int qlimit{2};
  16446. unsigned int queued_count{0};
  16447. std::atomic_uint count{0};
  16448. std::unique_ptr<TaskQueue> task_queue{
  16449. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16450. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16451. if (task_queue->enqueue(
  16452. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16453. queued_count++;
  16454. }
  16455. }
  16456. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16457. task_queue->shutdown();
  16458. #else
  16459. EXPECT_NO_THROW(task_queue->shutdown());
  16460. #endif
  16461. EXPECT_EQ(queued_count, count.load());
  16462. EXPECT_TRUE(queued_count <= number_of_tasks);
  16463. EXPECT_TRUE(queued_count >= qlimit);
  16464. }
  16465. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16466. // Use a short idle timeout so a dynamic thread spawns, times out and
  16467. // exits during the test, and the pool keeps working afterwards.
  16468. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16469. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16470. /*idle_timeout_sec=*/1}};
  16471. std::atomic_uint count{0};
  16472. std::condition_variable cv;
  16473. std::mutex mtx;
  16474. bool release = false;
  16475. // Block the base thread so the second task spawns a dynamic thread.
  16476. EXPECT_TRUE(task_queue->enqueue([&] {
  16477. std::unique_lock<std::mutex> lock(mtx);
  16478. while (!release) {
  16479. cv.wait(lock);
  16480. }
  16481. count++;
  16482. }));
  16483. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16484. // Let the dynamic thread finish its task and exceed the idle timeout.
  16485. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16486. {
  16487. std::unique_lock<std::mutex> lock(mtx);
  16488. release = true;
  16489. }
  16490. cv.notify_all();
  16491. // The pool must still accept and run tasks after the dynamic thread exited.
  16492. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16493. task_queue->shutdown();
  16494. EXPECT_EQ(3u, count.load());
  16495. }
  16496. TEST(TaskQueueTest, MaxQueuedRequests) {
  16497. static constexpr unsigned int qlimit{3};
  16498. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16499. std::condition_variable sem_cv;
  16500. std::mutex sem_mtx;
  16501. int credits = 0;
  16502. bool queued;
  16503. /* Fill up the queue with tasks that will block until we give them credits to
  16504. * complete. */
  16505. for (unsigned int n = 0; n <= qlimit;) {
  16506. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16507. std::unique_lock<std::mutex> lock(sem_mtx);
  16508. while (credits <= 0) {
  16509. sem_cv.wait(lock);
  16510. }
  16511. /* Consume the credit and signal the test code if they are all gone. */
  16512. if (--credits == 0) { sem_cv.notify_one(); }
  16513. });
  16514. if (n < qlimit) {
  16515. /* The first qlimit enqueues must succeed. */
  16516. EXPECT_TRUE(queued);
  16517. } else {
  16518. /* The last one will succeed only when the worker thread
  16519. * starts and dequeues the first blocking task. Although
  16520. * not necessary for the correctness of this test, we sleep for
  16521. * a short while to avoid busy waiting. */
  16522. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16523. }
  16524. if (queued) { n++; }
  16525. }
  16526. /* Further enqueues must fail since the queue is full. */
  16527. for (auto i = 0; i < 4; i++) {
  16528. queued = task_queue->enqueue([] {});
  16529. EXPECT_FALSE(queued);
  16530. }
  16531. /* Give the credits to allow the previous tasks to complete. */
  16532. {
  16533. std::unique_lock<std::mutex> lock(sem_mtx);
  16534. credits += qlimit + 1;
  16535. }
  16536. sem_cv.notify_all();
  16537. /* Wait for all the credits to be consumed. */
  16538. {
  16539. std::unique_lock<std::mutex> lock(sem_mtx);
  16540. while (credits > 0) {
  16541. sem_cv.wait(lock);
  16542. }
  16543. }
  16544. /* Check that we are able again to enqueue at least qlimit tasks. */
  16545. for (unsigned int i = 0; i < qlimit; i++) {
  16546. queued = task_queue->enqueue([] {});
  16547. EXPECT_TRUE(queued);
  16548. }
  16549. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16550. task_queue->shutdown();
  16551. #else
  16552. EXPECT_NO_THROW(task_queue->shutdown());
  16553. #endif
  16554. }
  16555. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16556. Server svr;
  16557. std::string method;
  16558. std::string body;
  16559. auto has_content_length = false;
  16560. auto has_transfer_encoding = false;
  16561. std::atomic<int> bad_requests{0};
  16562. // Leftover body bytes get parsed as a malformed request and answered with
  16563. // 400
  16564. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16565. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16566. });
  16567. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16568. res.set_redirect("/down", StatusCode::SeeOther_303);
  16569. });
  16570. svr.Get("/down", [&](const Request &req, Response &res) {
  16571. method = req.method;
  16572. body = req.body;
  16573. has_content_length = req.has_header("Content-Length");
  16574. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16575. res.set_content("ok", "text/plain");
  16576. });
  16577. auto port = svr.bind_to_any_port(HOST);
  16578. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16579. auto se = detail::scope_exit([&] {
  16580. svr.stop();
  16581. thread.join();
  16582. ASSERT_FALSE(svr.is_running());
  16583. });
  16584. svr.wait_until_ready();
  16585. const std::string payload = "SECRET-BODY";
  16586. auto check = [&](Client &cli, const Result &res) {
  16587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16588. EXPECT_EQ(StatusCode::OK_200, res->status);
  16589. EXPECT_EQ("ok", res->body);
  16590. EXPECT_EQ("GET", method);
  16591. EXPECT_TRUE(body.empty());
  16592. EXPECT_FALSE(has_content_length);
  16593. EXPECT_FALSE(has_transfer_encoding);
  16594. // Nothing of the original body may be left on the connection
  16595. auto res2 = cli.Get("/down");
  16596. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16597. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16598. EXPECT_EQ("ok", res2->body);
  16599. EXPECT_EQ(0, bad_requests);
  16600. };
  16601. // With content length
  16602. {
  16603. Client cli(HOST, port);
  16604. cli.set_keep_alive(true);
  16605. cli.set_follow_location(true);
  16606. auto res = cli.Post(
  16607. "/up", payload.size(),
  16608. [&](size_t offset, size_t length, DataSink &sink) {
  16609. return sink.write(payload.data() + offset, length);
  16610. },
  16611. "text/plain");
  16612. check(cli, res);
  16613. }
  16614. // Without content length (chunked)
  16615. {
  16616. Client cli(HOST, port);
  16617. cli.set_keep_alive(true);
  16618. cli.set_follow_location(true);
  16619. auto res = cli.Post(
  16620. "/up",
  16621. [&](size_t /*offset*/, DataSink &sink) {
  16622. sink.write(payload.data(), payload.size());
  16623. sink.done();
  16624. return true;
  16625. },
  16626. "text/plain");
  16627. check(cli, res);
  16628. }
  16629. }
  16630. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16631. Server svr;
  16632. std::string target;
  16633. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16634. // Echo the still-encoded name back in the Location
  16635. const std::string prefix = "/start/";
  16636. res.status = StatusCode::Found_302;
  16637. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16638. });
  16639. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16640. target = req.target;
  16641. res.set_content("ok", "text/plain");
  16642. });
  16643. auto port = svr.bind_to_any_port(HOST);
  16644. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16645. auto se = detail::scope_exit([&] {
  16646. svr.stop();
  16647. thread.join();
  16648. ASSERT_FALSE(svr.is_running());
  16649. });
  16650. svr.wait_until_ready();
  16651. // Decoding the Location path would turn the first four into a path
  16652. // separator, a query delimiter, a fragment delimiter and a different
  16653. // percent-encoded octet. The rest must keep reaching the server as they are.
  16654. const std::vector<std::string> names = {
  16655. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16656. };
  16657. for (auto path_encode : {true, false}) {
  16658. Client cli(HOST, port);
  16659. cli.set_follow_location(true);
  16660. cli.set_path_encode(path_encode);
  16661. for (const auto &name : names) {
  16662. target.clear();
  16663. auto res = cli.Get("/start/" + name);
  16664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16665. EXPECT_EQ(StatusCode::OK_200, res->status);
  16666. EXPECT_EQ("/dest/" + name, target);
  16667. }
  16668. }
  16669. }
  16670. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16671. Server svr;
  16672. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16673. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16674. });
  16675. svr.Get("/hello", [](const Request &req, Response &res) {
  16676. res.set_content(req.get_param_value("key"), "text/plain");
  16677. });
  16678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16679. auto se = detail::scope_exit([&] {
  16680. svr.stop();
  16681. thread.join();
  16682. ASSERT_FALSE(svr.is_running());
  16683. });
  16684. svr.wait_until_ready();
  16685. {
  16686. Client cli(HOST, PORT);
  16687. cli.set_follow_location(true);
  16688. auto res = cli.Get("/");
  16689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16690. EXPECT_EQ(StatusCode::OK_200, res->status);
  16691. EXPECT_EQ("val&key2=val2", res->body);
  16692. }
  16693. }
  16694. #endif
  16695. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16696. Server svr;
  16697. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16698. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16699. });
  16700. svr.Get("/hello", [](const Request &req, Response &res) {
  16701. res.set_content(req.get_param_value("key"), "text/plain");
  16702. });
  16703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16704. auto se = detail::scope_exit([&] {
  16705. svr.stop();
  16706. thread.join();
  16707. ASSERT_FALSE(svr.is_running());
  16708. });
  16709. svr.wait_until_ready();
  16710. {
  16711. Client cli(HOST, PORT);
  16712. cli.set_follow_location(true);
  16713. auto res = cli.Get("/");
  16714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16715. EXPECT_EQ(StatusCode::OK_200, res->status);
  16716. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16717. }
  16718. }
  16719. TEST(RedirectTest, RedirectWithPlusInPath) {
  16720. Server svr;
  16721. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16722. res.set_redirect("/a+b");
  16723. });
  16724. // Route pattern uses regex; escape + as \\+
  16725. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16726. res.set_content(req.path, "text/plain");
  16727. });
  16728. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16729. auto se = detail::scope_exit([&] {
  16730. svr.stop();
  16731. thread.join();
  16732. ASSERT_FALSE(svr.is_running());
  16733. });
  16734. svr.wait_until_ready();
  16735. {
  16736. Client cli(HOST, PORT);
  16737. cli.set_follow_location(true);
  16738. auto res = cli.Get("/");
  16739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16740. EXPECT_EQ(StatusCode::OK_200, res->status);
  16741. EXPECT_EQ("/a+b", res->body);
  16742. }
  16743. }
  16744. TEST(RedirectTest, ResolveRelativeLocation) {
  16745. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16746. const std::vector<std::pair<std::string, std::string>> cases = {
  16747. {"g", "/b/c/g"},
  16748. {"./g", "/b/c/g"},
  16749. {"g/", "/b/c/g/"},
  16750. {"?y", "/b/c/d;p?y"},
  16751. {"g?y", "/b/c/g?y"},
  16752. {"#s", "/b/c/d;p?q#s"},
  16753. {"g#s", "/b/c/g#s"},
  16754. {"g?y#s", "/b/c/g?y#s"},
  16755. {";x", "/b/c/;x"},
  16756. {"g;x", "/b/c/g;x"},
  16757. {".", "/b/c/"},
  16758. {"./", "/b/c/"},
  16759. {"..", "/b/"},
  16760. {"../", "/b/"},
  16761. {"../g", "/b/g"},
  16762. {"../..", "/"},
  16763. {"../../", "/"},
  16764. {"../../g", "/g"},
  16765. {"../../../g", "/g"},
  16766. {"g.", "/b/c/g."},
  16767. {".g", "/b/c/.g"},
  16768. {"g..", "/b/c/g.."},
  16769. {"..g", "/b/c/..g"},
  16770. {"./../g", "/b/g"},
  16771. {"./g/.", "/b/c/g/"},
  16772. {"g/./h", "/b/c/g/h"},
  16773. {"g/../h", "/b/c/h"},
  16774. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16775. {"g;x=1/../y", "/b/c/y"},
  16776. {"g?y/./x", "/b/c/g?y/./x"},
  16777. {"g#s/../x", "/b/c/g#s/../x"},
  16778. // Not relative-path references, so left for parse_url.
  16779. {"/g", "/g"},
  16780. {"//g", "//g"},
  16781. {"http://g/x", "http://g/x"},
  16782. {"g:h", "g:h"},
  16783. };
  16784. for (const auto &c : cases) {
  16785. EXPECT_EQ(c.second,
  16786. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16787. << c.first;
  16788. }
  16789. }
  16790. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16791. Server svr;
  16792. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16793. res.set_redirect(req.get_param_value("to"));
  16794. });
  16795. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16796. res.set_content(req.target, "text/plain");
  16797. });
  16798. svr.Get("/other", [](const Request &req, Response &res) {
  16799. res.set_content(req.target, "text/plain");
  16800. });
  16801. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16802. auto se = detail::scope_exit([&] {
  16803. svr.stop();
  16804. thread.join();
  16805. ASSERT_FALSE(svr.is_running());
  16806. });
  16807. svr.wait_until_ready();
  16808. const std::vector<std::pair<std::string, std::string>> cases = {
  16809. {"next", "/dir/next"},
  16810. {"./next?x=1", "/dir/next?x=1"},
  16811. {"../other", "/other"},
  16812. };
  16813. for (const auto &c : cases) {
  16814. Client cli(HOST, PORT);
  16815. cli.set_follow_location(true);
  16816. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16817. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16818. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16819. EXPECT_EQ(c.second, res->body) << c.first;
  16820. }
  16821. }
  16822. #ifdef CPPHTTPLIB_SSL_ENABLED
  16823. TEST(RedirectTest, Issue2185_Online) {
  16824. SSLClient client("github.com");
  16825. client.set_follow_location(true);
  16826. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16827. "Coollab-Windows.zip");
  16828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16829. EXPECT_EQ(StatusCode::OK_200, res->status);
  16830. EXPECT_EQ(9920427U, res->body.size());
  16831. }
  16832. #endif
  16833. TEST(VulnerabilityTest, CRLFInjection) {
  16834. Server svr;
  16835. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16836. res.set_content("Hello 1", "text/plain");
  16837. });
  16838. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16839. res.set_content("Hello 2", "text/plain");
  16840. });
  16841. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16842. res.set_content("Hello 3", "text/plain");
  16843. });
  16844. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16845. res.set_content("Hello 4", "text/plain");
  16846. });
  16847. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16848. for (const auto &x : req.headers) {
  16849. auto key = x.first;
  16850. EXPECT_STRNE("evil", key.c_str());
  16851. }
  16852. });
  16853. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16854. auto se = detail::scope_exit([&] {
  16855. svr.stop();
  16856. thread.join();
  16857. ASSERT_FALSE(svr.is_running());
  16858. });
  16859. svr.wait_until_ready();
  16860. {
  16861. Client cli(HOST, PORT);
  16862. cli.Post("/test1", "A=B",
  16863. "application/x-www-form-urlencoded\r\nevil: hello1");
  16864. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16865. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16866. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16867. }
  16868. }
  16869. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16870. auto server_thread = std::thread([] {
  16871. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16872. default_socket_options(srv);
  16873. sockaddr_in addr{};
  16874. addr.sin_family = AF_INET;
  16875. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16876. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16877. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16878. ::listen(srv, 1);
  16879. sockaddr_in cli_addr{};
  16880. socklen_t cli_len = sizeof(cli_addr);
  16881. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16882. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16883. std::string buf_all;
  16884. char buf[2048];
  16885. ssize_t n;
  16886. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16887. buf_all.append(buf, static_cast<size_t>(n));
  16888. size_t pos;
  16889. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16890. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16891. auto e = request_block.find("\r\n");
  16892. if (e != std::string::npos) {
  16893. auto request_line = request_block.substr(0, e);
  16894. std::string msg =
  16895. "CRLF injection detected in request line: '" + request_line + "'";
  16896. EXPECT_FALSE(true) << msg;
  16897. }
  16898. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16899. ::send(cli,
  16900. #ifdef _WIN32
  16901. static_cast<const char *>(resp.c_str()),
  16902. static_cast<int>(resp.size()),
  16903. #else
  16904. resp.c_str(), resp.size(),
  16905. #endif
  16906. 0);
  16907. buf_all.erase(0, pos + 4);
  16908. }
  16909. }
  16910. detail::close_socket(cli);
  16911. detail::close_socket(srv);
  16912. });
  16913. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16914. auto cli = Client("127.0.0.1", PORT + 1);
  16915. auto headers = Headers{
  16916. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16917. {"Connection", "keep-alive"}};
  16918. auto res = cli.Get("/hi", headers);
  16919. EXPECT_FALSE(res);
  16920. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16921. server_thread.join();
  16922. }
  16923. // A request rejected before any byte reaches the socket must fail right away
  16924. // instead of waiting for a response the server will never send.
  16925. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16926. // The kernel completes the TCP handshake from the listen backlog, so the
  16927. // client connects, but nothing ever reads, responds or closes.
  16928. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16929. default_socket_options(srv);
  16930. sockaddr_in addr{};
  16931. addr.sin_family = AF_INET;
  16932. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16933. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16934. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16935. ASSERT_EQ(0, ::listen(srv, 8));
  16936. auto cli = Client("127.0.0.1", PORT + 1);
  16937. cli.set_read_timeout(10, 0);
  16938. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16939. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16940. std::chrono::steady_clock::now() - start)
  16941. .count();
  16942. };
  16943. {
  16944. Request req;
  16945. req.method = "GE T";
  16946. req.path = "/";
  16947. auto start = std::chrono::steady_clock::now();
  16948. auto res = cli.send(req);
  16949. EXPECT_FALSE(res);
  16950. EXPECT_EQ(Error::Write, res.error());
  16951. EXPECT_LT(elapsed_ms(start), 1000);
  16952. }
  16953. {
  16954. auto start = std::chrono::steady_clock::now();
  16955. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16956. EXPECT_FALSE(res);
  16957. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16958. EXPECT_LT(elapsed_ms(start), 1000);
  16959. }
  16960. EXPECT_FALSE(cli.is_socket_open());
  16961. detail::close_socket(srv);
  16962. }
  16963. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16964. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16965. default_socket_options(srv);
  16966. sockaddr_in addr{};
  16967. addr.sin_family = AF_INET;
  16968. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16969. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16970. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16971. ASSERT_EQ(0, ::listen(srv, 1));
  16972. std::string received;
  16973. auto server_thread = std::thread([&] {
  16974. auto sock = ::accept(srv, nullptr, nullptr);
  16975. if (sock == INVALID_SOCKET) { return; }
  16976. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16977. char buf[2048];
  16978. ssize_t n;
  16979. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16980. received.append(buf, static_cast<size_t>(n));
  16981. }
  16982. detail::close_socket(sock);
  16983. });
  16984. {
  16985. auto cli = Client("127.0.0.1", PORT + 1);
  16986. // "Z" sorts after the default headers, so writing straight to the socket
  16987. // would have sent the request line and those headers before the rejection.
  16988. auto handle =
  16989. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16990. EXPECT_FALSE(handle.is_valid());
  16991. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16992. }
  16993. server_thread.join();
  16994. detail::close_socket(srv);
  16995. EXPECT_TRUE(received.empty()) << received;
  16996. }
  16997. TEST(PathParamsTest, StaticMatch) {
  16998. const auto pattern = "/users/all";
  16999. detail::PathParamsMatcher matcher(pattern);
  17000. Request request;
  17001. request.path = "/users/all";
  17002. ASSERT_TRUE(matcher.match(request));
  17003. std::unordered_map<std::string, std::string> expected_params = {};
  17004. EXPECT_EQ(request.path_params, expected_params);
  17005. }
  17006. TEST(PathParamsTest, StaticMismatch) {
  17007. const auto pattern = "/users/all";
  17008. detail::PathParamsMatcher matcher(pattern);
  17009. Request request;
  17010. request.path = "/users/1";
  17011. ASSERT_FALSE(matcher.match(request));
  17012. }
  17013. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17014. const auto pattern = "/users/:id/subscriptions";
  17015. detail::PathParamsMatcher matcher(pattern);
  17016. Request request;
  17017. request.path = "/users/42/subscriptions";
  17018. ASSERT_TRUE(matcher.match(request));
  17019. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17020. EXPECT_EQ(request.path_params, expected_params);
  17021. }
  17022. TEST(PathParamsTest, SingleParamInTheEnd) {
  17023. const auto pattern = "/users/:id";
  17024. detail::PathParamsMatcher matcher(pattern);
  17025. Request request;
  17026. request.path = "/users/24";
  17027. ASSERT_TRUE(matcher.match(request));
  17028. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17029. EXPECT_EQ(request.path_params, expected_params);
  17030. }
  17031. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17032. const auto pattern = "/users/:id/";
  17033. detail::PathParamsMatcher matcher(pattern);
  17034. Request request;
  17035. request.path = "/users/42/";
  17036. ASSERT_TRUE(matcher.match(request));
  17037. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17038. EXPECT_EQ(request.path_params, expected_params);
  17039. }
  17040. TEST(PathParamsTest, EmptyParam) {
  17041. const auto pattern = "/users/:id/";
  17042. detail::PathParamsMatcher matcher(pattern);
  17043. Request request;
  17044. request.path = "/users//";
  17045. ASSERT_TRUE(matcher.match(request));
  17046. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17047. EXPECT_EQ(request.path_params, expected_params);
  17048. }
  17049. TEST(PathParamsTest, FragmentMismatch) {
  17050. const auto pattern = "/users/:id/";
  17051. detail::PathParamsMatcher matcher(pattern);
  17052. Request request;
  17053. request.path = "/admins/24/";
  17054. ASSERT_FALSE(matcher.match(request));
  17055. }
  17056. TEST(PathParamsTest, ExtraFragments) {
  17057. const auto pattern = "/users/:id";
  17058. detail::PathParamsMatcher matcher(pattern);
  17059. Request request;
  17060. request.path = "/users/42/subscriptions";
  17061. ASSERT_FALSE(matcher.match(request));
  17062. }
  17063. TEST(PathParamsTest, MissingTrailingParam) {
  17064. const auto pattern = "/users/:id";
  17065. detail::PathParamsMatcher matcher(pattern);
  17066. Request request;
  17067. request.path = "/users";
  17068. ASSERT_FALSE(matcher.match(request));
  17069. }
  17070. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17071. const auto pattern = "/users/:id/subscriptions";
  17072. detail::PathParamsMatcher matcher(pattern);
  17073. Request request;
  17074. request.path = "/users/subscriptions";
  17075. ASSERT_FALSE(matcher.match(request));
  17076. }
  17077. TEST(PathParamsTest, MultipleParams) {
  17078. const auto pattern = "/users/:userid/subscriptions/:subid";
  17079. detail::PathParamsMatcher matcher(pattern);
  17080. Request request;
  17081. request.path = "/users/42/subscriptions/2";
  17082. ASSERT_TRUE(matcher.match(request));
  17083. std::unordered_map<std::string, std::string> expected_params = {
  17084. {"userid", "42"}, {"subid", "2"}};
  17085. EXPECT_EQ(request.path_params, expected_params);
  17086. }
  17087. TEST(PathParamsTest, SequenceOfParams) {
  17088. const auto pattern = "/values/:x/:y/:z";
  17089. detail::PathParamsMatcher matcher(pattern);
  17090. Request request;
  17091. request.path = "/values/1/2/3";
  17092. ASSERT_TRUE(matcher.match(request));
  17093. std::unordered_map<std::string, std::string> expected_params = {
  17094. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17095. EXPECT_EQ(request.path_params, expected_params);
  17096. }
  17097. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17098. const auto pattern = "/prefix:suffix";
  17099. detail::PathParamsMatcher matcher(pattern);
  17100. Request request;
  17101. request.path = "/prefix:suffix";
  17102. ASSERT_TRUE(matcher.match(request));
  17103. const std::unordered_map<std::string, std::string> expected_params = {};
  17104. EXPECT_EQ(request.path_params, expected_params);
  17105. }
  17106. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17107. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17108. // calling thread's stack on a long enough path for a quantified pattern;
  17109. // RegexMatcher must refuse to run regex matching on paths beyond
  17110. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17111. detail::RegexMatcher matcher("/files/(.*)");
  17112. Request within_limit;
  17113. within_limit.path = "/files/" + std::string(10, 'A');
  17114. EXPECT_TRUE(matcher.match(within_limit));
  17115. Request over_limit;
  17116. over_limit.path =
  17117. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17118. EXPECT_FALSE(matcher.match(over_limit));
  17119. }
  17120. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17121. Server svr;
  17122. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17123. res.set_content("ok", "text/plain");
  17124. });
  17125. auto port = svr.bind_to_any_port(HOST);
  17126. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17127. auto se = detail::scope_exit([&] {
  17128. svr.stop();
  17129. thread.join();
  17130. ASSERT_FALSE(svr.is_running());
  17131. });
  17132. svr.wait_until_ready();
  17133. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17134. // request URI limit; this used to be able to crash the process.
  17135. std::string path =
  17136. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17137. std::string req = "GET " + path +
  17138. " HTTP/1.1\r\n"
  17139. "Host: " +
  17140. std::string(HOST) + ":" + std::to_string(port) +
  17141. "\r\n"
  17142. "Connection: close\r\n"
  17143. "\r\n";
  17144. std::string response;
  17145. ASSERT_TRUE(send_request(5, req, &response, port));
  17146. EXPECT_NE(std::string::npos, response.find("404"));
  17147. }
  17148. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17149. Server svr;
  17150. auto handler = [](const Request & /*req*/, Response &res) {
  17151. res.set_content("hit", "text/plain");
  17152. };
  17153. // No regex metacharacter, so this one is compared literally
  17154. svr.Get("/literal/route", handler);
  17155. // '.' is a regex metacharacter, so this one must keep regex semantics
  17156. svr.Get("/a.c", handler);
  17157. auto port = svr.bind_to_any_port(HOST);
  17158. std::thread t([&]() { svr.listen_after_bind(); });
  17159. auto se = detail::scope_exit([&] {
  17160. svr.stop();
  17161. t.join();
  17162. ASSERT_FALSE(svr.is_running());
  17163. });
  17164. svr.wait_until_ready();
  17165. Client cli(HOST, port);
  17166. struct {
  17167. const char *path;
  17168. int status;
  17169. } cases[] = {
  17170. {"/literal/route", StatusCode::OK_200},
  17171. {"/literal/routes", StatusCode::NotFound_404},
  17172. {"/literal/rout", StatusCode::NotFound_404},
  17173. {"/abc", StatusCode::OK_200},
  17174. {"/a.c", StatusCode::OK_200},
  17175. };
  17176. for (const auto &x : cases) {
  17177. auto res = cli.Get(x.path);
  17178. ASSERT_TRUE(res) << x.path;
  17179. EXPECT_EQ(x.status, res->status) << x.path;
  17180. }
  17181. }
  17182. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17183. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17184. // from exhausting the stack, so it must only constrain routes that actually
  17185. // run a regular expression. A literal route is matched by comparison and
  17186. // stays usable at any length.
  17187. Server svr;
  17188. const std::string pattern =
  17189. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17190. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17191. res.set_content("hit", "text/plain");
  17192. });
  17193. auto port = svr.bind_to_any_port(HOST);
  17194. std::thread t([&]() { svr.listen_after_bind(); });
  17195. auto se = detail::scope_exit([&] {
  17196. svr.stop();
  17197. t.join();
  17198. ASSERT_FALSE(svr.is_running());
  17199. });
  17200. svr.wait_until_ready();
  17201. Client cli(HOST, port);
  17202. auto res = cli.Get(pattern);
  17203. ASSERT_TRUE(res);
  17204. EXPECT_EQ(StatusCode::OK_200, res->status);
  17205. }
  17206. TEST(ParseUrlTest, VariousPatterns) {
  17207. {
  17208. detail::UrlComponents uc;
  17209. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17210. EXPECT_EQ("http", uc.scheme);
  17211. EXPECT_EQ("example.com", uc.host);
  17212. EXPECT_EQ("8080", uc.port);
  17213. EXPECT_EQ("/path", uc.path);
  17214. EXPECT_EQ("?q=1", uc.query);
  17215. }
  17216. {
  17217. detail::UrlComponents uc;
  17218. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17219. EXPECT_EQ("https", uc.scheme);
  17220. EXPECT_EQ("example.com", uc.host);
  17221. EXPECT_TRUE(uc.port.empty());
  17222. EXPECT_EQ("/path", uc.path);
  17223. }
  17224. {
  17225. detail::UrlComponents uc;
  17226. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17227. EXPECT_EQ("::1", uc.host);
  17228. EXPECT_EQ("8080", uc.port);
  17229. EXPECT_EQ("/path", uc.path);
  17230. }
  17231. {
  17232. detail::UrlComponents uc;
  17233. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17234. }
  17235. {
  17236. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17237. // the path while the connection still targets the bracketed host.
  17238. detail::UrlComponents uc;
  17239. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17240. }
  17241. {
  17242. detail::UrlComponents uc;
  17243. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17244. }
  17245. {
  17246. detail::UrlComponents uc;
  17247. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17248. EXPECT_EQ("::1", uc.host);
  17249. EXPECT_TRUE(uc.port.empty());
  17250. EXPECT_EQ("/path", uc.path);
  17251. }
  17252. {
  17253. detail::UrlComponents uc;
  17254. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17255. EXPECT_TRUE(uc.scheme.empty());
  17256. EXPECT_EQ("example.com", uc.host);
  17257. EXPECT_EQ("/path", uc.path);
  17258. EXPECT_EQ("?q=1", uc.query);
  17259. }
  17260. {
  17261. detail::UrlComponents uc;
  17262. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17263. EXPECT_TRUE(uc.host.empty());
  17264. EXPECT_EQ("/path", uc.path);
  17265. EXPECT_EQ("?q=1", uc.query);
  17266. }
  17267. {
  17268. detail::UrlComponents uc;
  17269. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17270. EXPECT_EQ("example.com", uc.host);
  17271. EXPECT_EQ("8080", uc.port);
  17272. }
  17273. {
  17274. // Unix socket path — must not be parsed as host
  17275. detail::UrlComponents uc;
  17276. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17277. EXPECT_TRUE(uc.host.empty());
  17278. }
  17279. {
  17280. detail::UrlComponents uc;
  17281. ASSERT_TRUE(detail::parse_url("", uc));
  17282. EXPECT_TRUE(uc.host.empty());
  17283. EXPECT_TRUE(uc.path.empty());
  17284. }
  17285. {
  17286. detail::UrlComponents uc;
  17287. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17288. }
  17289. {
  17290. detail::UrlComponents uc;
  17291. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17292. }
  17293. {
  17294. // Accepted by parse_url; callers restrict to http/https
  17295. detail::UrlComponents uc;
  17296. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17297. EXPECT_EQ("ftp", uc.scheme);
  17298. }
  17299. {
  17300. detail::UrlComponents uc;
  17301. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17302. }
  17303. {
  17304. detail::UrlComponents uc;
  17305. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17306. }
  17307. }
  17308. TEST(ParseUrlTest, FragmentHandling) {
  17309. {
  17310. detail::UrlComponents uc;
  17311. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17312. EXPECT_EQ("/path", uc.path);
  17313. EXPECT_TRUE(uc.query.empty());
  17314. }
  17315. {
  17316. detail::UrlComponents uc;
  17317. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17318. EXPECT_TRUE(uc.path.empty());
  17319. EXPECT_TRUE(uc.query.empty());
  17320. }
  17321. }
  17322. TEST(ParseUrlTest, UserinfoHandling) {
  17323. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17324. // parsers would see evil.com as the host.
  17325. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17326. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17327. for (auto url : urls) {
  17328. detail::UrlComponents uc;
  17329. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17330. }
  17331. }
  17332. TEST(ParseUrlTest, IPv6EdgeCases) {
  17333. {
  17334. detail::UrlComponents uc;
  17335. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17336. EXPECT_TRUE(uc.scheme.empty());
  17337. EXPECT_EQ("::1", uc.host);
  17338. EXPECT_EQ("8080", uc.port);
  17339. }
  17340. {
  17341. // Zone ID '%25' is not in [a-fA-F0-9:]
  17342. detail::UrlComponents uc;
  17343. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17344. }
  17345. }
  17346. TEST(ParseUrlTest, SchemeEdgeCases) {
  17347. {
  17348. detail::UrlComponents uc;
  17349. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17350. }
  17351. {
  17352. detail::UrlComponents uc;
  17353. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17354. }
  17355. {
  17356. detail::UrlComponents uc;
  17357. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17358. }
  17359. }
  17360. TEST(ParseUrlTest, PortEdgeCases) {
  17361. {
  17362. detail::UrlComponents uc;
  17363. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17364. EXPECT_TRUE(uc.port.empty());
  17365. EXPECT_EQ("/path", uc.path);
  17366. }
  17367. {
  17368. // parse_url accepts any port string; validation is done by parse_port
  17369. detail::UrlComponents uc;
  17370. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17371. EXPECT_EQ("abc", uc.port);
  17372. }
  17373. }
  17374. TEST(ParseUrlTest, WebSocketPatterns) {
  17375. {
  17376. detail::UrlComponents uc;
  17377. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17378. EXPECT_EQ("ws", uc.scheme);
  17379. EXPECT_EQ("echo.example.com", uc.host);
  17380. EXPECT_EQ("8080", uc.port);
  17381. EXPECT_EQ("/ws", uc.path);
  17382. }
  17383. {
  17384. detail::UrlComponents uc;
  17385. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17386. EXPECT_EQ("wss", uc.scheme);
  17387. EXPECT_EQ("echo.example.com", uc.host);
  17388. EXPECT_TRUE(uc.port.empty());
  17389. EXPECT_EQ("/ws", uc.path);
  17390. }
  17391. }
  17392. TEST(ParseUrlTest, QueryOnly) {
  17393. detail::UrlComponents uc;
  17394. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17395. EXPECT_TRUE(uc.host.empty());
  17396. EXPECT_TRUE(uc.path.empty());
  17397. EXPECT_EQ("?q=1&r=2", uc.query);
  17398. }
  17399. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17400. detail::UrlComponents uc;
  17401. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17402. EXPECT_TRUE(uc.scheme.empty());
  17403. EXPECT_EQ("example.com", uc.host);
  17404. EXPECT_EQ("443", uc.port);
  17405. EXPECT_EQ("/path", uc.path);
  17406. }
  17407. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17408. // If ipv6 regex working, regex match codepath is taken.
  17409. // else port will default to 80 in Client impl
  17410. int clientImplMagicPort = 80;
  17411. int port = 4321;
  17412. // above ports must be different to avoid false negative
  17413. EXPECT_NE(clientImplMagicPort, port);
  17414. std::string ipV6TestURL = "http://[ff06::c3]";
  17415. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17416. CLIENT_PRIVATE_KEY_FILE);
  17417. EXPECT_EQ(cli.port(), port);
  17418. }
  17419. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17420. auto file_path = "./www/dir/index.html";
  17421. auto dir_path = "./www/dir";
  17422. detail::FileStat stat_file(file_path);
  17423. EXPECT_TRUE(stat_file.is_file());
  17424. EXPECT_FALSE(stat_file.is_dir());
  17425. detail::FileStat stat_dir(dir_path);
  17426. EXPECT_FALSE(stat_dir.is_file());
  17427. EXPECT_TRUE(stat_dir.is_dir());
  17428. }
  17429. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17430. // IPv4 with default HTTP port (80)
  17431. EXPECT_EQ("example.com",
  17432. detail::make_host_and_port_string("example.com", 80, false));
  17433. // IPv4 with default HTTPS port (443)
  17434. EXPECT_EQ("example.com",
  17435. detail::make_host_and_port_string("example.com", 443, true));
  17436. // IPv4 with non-default HTTP port
  17437. EXPECT_EQ("example.com:8080",
  17438. detail::make_host_and_port_string("example.com", 8080, false));
  17439. // IPv4 with non-default HTTPS port
  17440. EXPECT_EQ("example.com:8443",
  17441. detail::make_host_and_port_string("example.com", 8443, true));
  17442. // IPv6 with default HTTP port (80)
  17443. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17444. // IPv6 with default HTTPS port (443)
  17445. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17446. // IPv6 with non-default HTTP port
  17447. EXPECT_EQ("[::1]:8080",
  17448. detail::make_host_and_port_string("::1", 8080, false));
  17449. // IPv6 with non-default HTTPS port
  17450. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17451. // IPv6 full address with default port
  17452. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17453. detail::make_host_and_port_string(
  17454. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17455. // IPv6 full address with non-default port
  17456. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17457. detail::make_host_and_port_string(
  17458. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17459. // IPv6 localhost with non-default port
  17460. EXPECT_EQ("[::1]:3000",
  17461. detail::make_host_and_port_string("::1", 3000, false));
  17462. // IPv6 with zone ID (link-local address) with default port
  17463. EXPECT_EQ("[fe80::1%eth0]",
  17464. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17465. // IPv6 with zone ID (link-local address) with non-default port
  17466. EXPECT_EQ("[fe80::1%eth0]:8080",
  17467. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17468. // Edge case: Port 443 with is_ssl=false (should add port)
  17469. EXPECT_EQ("example.com:443",
  17470. detail::make_host_and_port_string("example.com", 443, false));
  17471. // Edge case: Port 80 with is_ssl=true (should add port)
  17472. EXPECT_EQ("example.com:80",
  17473. detail::make_host_and_port_string("example.com", 80, true));
  17474. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17475. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17476. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17477. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17478. // Security fix: Already bracketed IPv6 should not get double brackets
  17479. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17480. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17481. EXPECT_EQ("[::1]:8080",
  17482. detail::make_host_and_port_string("[::1]", 8080, false));
  17483. EXPECT_EQ("[2001:db8::1]:8080",
  17484. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17485. EXPECT_EQ("[fe80::1%eth0]",
  17486. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17487. EXPECT_EQ("[fe80::1%eth0]:8080",
  17488. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17489. // Edge case: Empty host (should return as-is)
  17490. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17491. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17492. // This is a known limitation but shouldn't crash
  17493. EXPECT_EQ("[host:name]",
  17494. detail::make_host_and_port_string("host:name", 80, false));
  17495. // Port number edge cases (no validation, but should not crash)
  17496. EXPECT_EQ("example.com:0",
  17497. detail::make_host_and_port_string("example.com", 0, false));
  17498. EXPECT_EQ("example.com:-1",
  17499. detail::make_host_and_port_string("example.com", -1, false));
  17500. EXPECT_EQ("example.com:65535",
  17501. detail::make_host_and_port_string("example.com", 65535, false));
  17502. EXPECT_EQ("example.com:65536",
  17503. detail::make_host_and_port_string("example.com", 65536, false));
  17504. }
  17505. #ifdef CPPHTTPLIB_SSL_ENABLED
  17506. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17507. httplib::SSLClient cli("roblox.com", 443);
  17508. cli.set_follow_location(true);
  17509. auto res = cli.Get("/");
  17510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17511. EXPECT_EQ(StatusCode::OK_200, res->status);
  17512. }
  17513. #endif
  17514. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17515. Server svr;
  17516. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17517. EXPECT_EQ(res.status, 400);
  17518. });
  17519. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17520. auto se = detail::scope_exit([&] {
  17521. svr.stop();
  17522. thread.join();
  17523. ASSERT_FALSE(svr.is_running());
  17524. });
  17525. svr.wait_until_ready();
  17526. Client cli(HOST, PORT);
  17527. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17528. }
  17529. TEST(InvalidHeaderCharsTest, is_field_name) {
  17530. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17531. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17532. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17533. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17534. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17535. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17536. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17537. EXPECT_FALSE(detail::fields::is_field_name(""));
  17538. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17539. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17540. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17541. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17542. }
  17543. TEST(InvalidHeaderCharsTest, is_field_value) {
  17544. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17545. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17546. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17547. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17548. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17549. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17550. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17551. EXPECT_TRUE(detail::fields::is_field_value(""));
  17552. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17553. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17554. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17555. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17556. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17557. }
  17558. TEST(InvalidHeaderCharsTest, OnServer) {
  17559. Server svr;
  17560. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17561. std::string header = "Not Set";
  17562. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17563. res.set_header(header, "value");
  17564. res.set_content("Page Content Page Content", "text/plain");
  17565. });
  17566. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17567. std::string header = "Not Set";
  17568. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17569. res.set_header("X-Test", header);
  17570. res.set_content("Page Content Page Content", "text/plain");
  17571. });
  17572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17573. auto se = detail::scope_exit([&] {
  17574. svr.stop();
  17575. thread.join();
  17576. ASSERT_FALSE(svr.is_running());
  17577. });
  17578. svr.wait_until_ready();
  17579. Client cli(HOST, PORT);
  17580. {
  17581. auto res = cli.Get(
  17582. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17584. EXPECT_EQ("Page Content Page Content", res->body);
  17585. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17586. }
  17587. {
  17588. auto res = cli.Get(
  17589. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17591. EXPECT_EQ("Page Content Page Content", res->body);
  17592. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17593. }
  17594. }
  17595. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17596. auto handled = false;
  17597. Server svr;
  17598. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17599. thread t = thread([&] { svr.listen(HOST, PORT); });
  17600. auto se = detail::scope_exit([&] {
  17601. svr.stop();
  17602. t.join();
  17603. ASSERT_FALSE(svr.is_running());
  17604. ASSERT_FALSE(handled);
  17605. });
  17606. svr.wait_until_ready();
  17607. auto req = "POST /test HTTP/1.1\r\n"
  17608. "Content-Length: x\r\n"
  17609. "\r\n";
  17610. std::string response;
  17611. ASSERT_TRUE(send_request(1, req, &response));
  17612. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17613. response.substr(0, response.find("\r\n")));
  17614. }
  17615. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17616. // case-insensitive, and a server that receives a 100-continue expectation in
  17617. // an HTTP/1.0 request MUST ignore it.
  17618. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17619. std::string response;
  17620. ASSERT_TRUE(send_request(1, req, &response, port));
  17621. *got_100 = response.find("100 Continue") != std::string::npos;
  17622. }
  17623. class ExpectTokenTest : public ::testing::Test {
  17624. protected:
  17625. void SetUp() override {
  17626. svr_.Post("/p", [](const Request &, Response &res) {
  17627. res.set_content("ok", "text/plain");
  17628. });
  17629. port_ = svr_.bind_to_any_port(HOST);
  17630. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17631. svr_.wait_until_ready();
  17632. }
  17633. void TearDown() override {
  17634. svr_.stop();
  17635. if (thread_.joinable()) { thread_.join(); }
  17636. }
  17637. std::string request(const char *version, const char *expect_value) const {
  17638. return std::string("POST /p ") + version +
  17639. "\r\n"
  17640. "Host: localhost\r\n"
  17641. "Content-Length: 2\r\n"
  17642. "Connection: close\r\n"
  17643. "Expect: " +
  17644. expect_value +
  17645. "\r\n"
  17646. "\r\n"
  17647. "hi";
  17648. }
  17649. Server svr_;
  17650. int port_ = 0;
  17651. thread thread_;
  17652. };
  17653. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17654. bool got_100 = false;
  17655. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17656. EXPECT_TRUE(got_100);
  17657. }
  17658. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17659. bool got_100 = true;
  17660. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17661. EXPECT_FALSE(got_100);
  17662. }
  17663. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17664. bool got_100 = false;
  17665. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17666. EXPECT_TRUE(got_100);
  17667. }
  17668. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17669. bool got_100 = false;
  17670. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17671. EXPECT_TRUE(got_100);
  17672. }
  17673. // `100 Continue` is sent only when the server starts reading the body, so a
  17674. // request rejected before that never invites the client to send it. The
  17675. // requests below carry the expectation but withhold the body, as a client
  17676. // waiting for `100 Continue` would.
  17677. // A POST that expects `100 Continue` and withholds its two-byte body.
  17678. static std::string expect_headers_only(const std::string &path) {
  17679. return "POST " + path +
  17680. " HTTP/1.1\r\n"
  17681. "Host: localhost\r\n"
  17682. "Content-Length: 2\r\n"
  17683. "Expect: 100-continue\r\n"
  17684. "\r\n";
  17685. }
  17686. class ExpectLazyContinueTest : public ::testing::Test {
  17687. protected:
  17688. void SetUp() override {
  17689. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17690. if (req.path == "/pre-routing") {
  17691. res.status = StatusCode::Unauthorized_401;
  17692. return Server::HandlerResponse::Handled;
  17693. }
  17694. return Server::HandlerResponse::Unhandled;
  17695. });
  17696. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17697. if (req.matched_route == "/pre-request") {
  17698. res.status = StatusCode::Forbidden_403;
  17699. return Server::HandlerResponse::Handled;
  17700. }
  17701. return Server::HandlerResponse::Unhandled;
  17702. });
  17703. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17704. res.set_content("ok", "text/plain");
  17705. });
  17706. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17707. res.set_content("ok", "text/plain");
  17708. });
  17709. svr_.Post("/reader-used", [](const Request &, Response &res,
  17710. const ContentReader &content_reader) {
  17711. std::string body;
  17712. content_reader([&](const char *data, size_t len) {
  17713. body.append(data, len);
  17714. return true;
  17715. });
  17716. res.set_content(body, "text/plain");
  17717. });
  17718. svr_.Post("/reader-unused",
  17719. [](const Request &, Response &res, const ContentReader &) {
  17720. res.set_content("ignored", "text/plain");
  17721. });
  17722. port_ = svr_.bind_to_any_port(HOST);
  17723. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17724. svr_.wait_until_ready();
  17725. }
  17726. void TearDown() override {
  17727. svr_.stop();
  17728. if (thread_.joinable()) { thread_.join(); }
  17729. }
  17730. // Sends `req` and reads until the server closes the connection. Returns
  17731. // false if the read had to wait for the client-side timeout instead.
  17732. bool send_until_closed(const std::string &req, std::string *resp) const {
  17733. auto start = std::chrono::steady_clock::now();
  17734. if (!send_request(3, req, resp, port_)) { return false; }
  17735. auto elapsed = std::chrono::steady_clock::now() - start;
  17736. return elapsed < std::chrono::seconds(2);
  17737. }
  17738. // The final response comes without `100 Continue`, and the server closes
  17739. // the connection since the body may or may not follow.
  17740. void expect_final_without_interim(const std::string &path,
  17741. const char *status_line) const {
  17742. std::string resp;
  17743. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17744. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17745. EXPECT_EQ(0u, resp.find(status_line));
  17746. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17747. }
  17748. Server svr_;
  17749. int port_ = 0;
  17750. thread thread_;
  17751. };
  17752. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17753. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17754. }
  17755. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17756. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17757. }
  17758. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17759. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17760. }
  17761. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17762. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17763. }
  17764. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17765. // The body follows once `100 Continue` has had time to arrive.
  17766. auto req = expect_headers_only("/reader-used");
  17767. req.insert(req.size() - 2, "Connection: close\r\n");
  17768. std::string resp;
  17769. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17770. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17771. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17772. EXPECT_NE(std::string::npos, resp.find("hi"));
  17773. }
  17774. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17775. // Large enough for the client to add `Expect: 100-continue` itself.
  17776. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17777. std::atomic<bool> body_sent{false};
  17778. Client cli(HOST, port_);
  17779. auto res = cli.Post(
  17780. "/pre-request", length,
  17781. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17782. body_sent = true;
  17783. std::string chunk(len, 'x');
  17784. sink.write(chunk.data(), chunk.size());
  17785. return true;
  17786. },
  17787. "application/octet-stream");
  17788. ASSERT_TRUE(res);
  17789. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17790. EXPECT_FALSE(body_sent);
  17791. }
  17792. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17793. Server svr;
  17794. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17795. return StatusCode::ExpectationFailed_417;
  17796. });
  17797. svr.Post("/p", [](const Request &, Response &res) {
  17798. res.set_content("ok", "text/plain");
  17799. });
  17800. auto port = svr.bind_to_any_port(HOST);
  17801. thread t = thread([&] { svr.listen_after_bind(); });
  17802. auto se = detail::scope_exit([&] {
  17803. svr.stop();
  17804. t.join();
  17805. });
  17806. svr.wait_until_ready();
  17807. std::string resp;
  17808. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17809. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17810. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17811. // Exactly one response: the route handler must not run after the 417.
  17812. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17813. }
  17814. #ifndef _WIN32
  17815. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17816. static constexpr char reject[] = "Unauthorized";
  17817. static constexpr char accept[] = "Upload accepted";
  17818. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17819. Server svr;
  17820. svr.set_expect_100_continue_handler(
  17821. [](const Request & /*req*/, Response &res) {
  17822. res.status = StatusCode::Unauthorized_401;
  17823. res.set_content(reject, "text/plain");
  17824. return res.status;
  17825. });
  17826. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17827. res.set_content(accept, "text/plain");
  17828. });
  17829. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17830. auto se = detail::scope_exit([&] {
  17831. svr.stop();
  17832. thread.join();
  17833. ASSERT_FALSE(svr.is_running());
  17834. });
  17835. svr.wait_until_ready();
  17836. {
  17837. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17838. curl_easy_init(), &curl_easy_cleanup};
  17839. ASSERT_NE(curl, nullptr);
  17840. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17841. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17842. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17843. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17844. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17845. &curl_slist_free_all};
  17846. ASSERT_NE(list, nullptr);
  17847. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17848. struct read_data {
  17849. size_t read_size;
  17850. size_t total_size;
  17851. } data = {0, total_size};
  17852. using read_callback_t =
  17853. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17854. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17855. void *userdata) -> size_t {
  17856. read_data *d = (read_data *)userdata;
  17857. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17858. std::fill_n(ptr, size * nmemb, 'A');
  17859. d->read_size += size * nmemb;
  17860. return size * nmemb;
  17861. };
  17862. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17863. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17864. std::vector<char> buffer;
  17865. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17866. using write_callback_t =
  17867. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17868. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17869. void *userdata) -> size_t {
  17870. std::vector<char> *buf = (std::vector<char> *)userdata;
  17871. buf->reserve(buf->size() + size * nmemb + 1);
  17872. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17873. return size * nmemb;
  17874. };
  17875. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17876. {
  17877. const auto res = curl_easy_perform(curl.get());
  17878. ASSERT_EQ(res, CURLE_OK);
  17879. }
  17880. {
  17881. auto response_code = long{};
  17882. const auto res =
  17883. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17884. ASSERT_EQ(res, CURLE_OK);
  17885. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17886. }
  17887. {
  17888. auto dl = curl_off_t{};
  17889. const auto res =
  17890. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17891. ASSERT_EQ(res, CURLE_OK);
  17892. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17893. }
  17894. {
  17895. buffer.push_back('\0');
  17896. ASSERT_STRCASEEQ(buffer.data(), reject);
  17897. }
  17898. }
  17899. }
  17900. #endif
  17901. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17902. // Regression test for #2458.
  17903. //
  17904. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17905. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17906. // ticket can make the client socket spuriously readable during the
  17907. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17908. // the client withholds the body and then blocks reading a response that never
  17909. // comes, failing with `Failed to read connection`.
  17910. //
  17911. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17912. // within the timeout. This raw OpenSSL server deliberately never sends
  17913. // `100 Continue`; the client must still deliver the body and receive 200.
  17914. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17915. signal(SIGPIPE, SIG_IGN);
  17916. const auto port = PORT + 4;
  17917. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17918. ASSERT_NE(srv, INVALID_SOCKET);
  17919. int opt = 1;
  17920. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17921. sockaddr_in addr{};
  17922. addr.sin_family = AF_INET;
  17923. addr.sin_port = htons(static_cast<uint16_t>(port));
  17924. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17925. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17926. ASSERT_EQ(0, ::listen(srv, 1));
  17927. std::atomic<size_t> server_body_bytes{0};
  17928. auto server_thread = std::thread([&] {
  17929. sockaddr_in cli_addr{};
  17930. socklen_t cli_len = sizeof(cli_addr);
  17931. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17932. if (cli == INVALID_SOCKET) { return; }
  17933. // Bound the lifetime of the server side so a buggy client (which never
  17934. // sends the body) cannot make this thread block forever on join.
  17935. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17936. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17937. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17938. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17939. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17940. SSL *ssl = SSL_new(ctx);
  17941. SSL_set_fd(ssl, static_cast<int>(cli));
  17942. if (SSL_accept(ssl) > 0) {
  17943. // Read the request headers. Reading here also flushes the TLS 1.3
  17944. // session tickets to the client. Deliberately do NOT send
  17945. // `100 Continue`.
  17946. std::string buf;
  17947. char tmp[1024];
  17948. while (buf.find("\r\n\r\n") == std::string::npos) {
  17949. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17950. if (n <= 0) { break; }
  17951. buf.append(tmp, static_cast<size_t>(n));
  17952. }
  17953. // A correct client sends the body now; count what arrives.
  17954. auto pos = buf.find("\r\n\r\n");
  17955. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17956. while (body < 4096) {
  17957. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17958. if (n <= 0) { break; }
  17959. body += static_cast<size_t>(n);
  17960. }
  17961. server_body_bytes = body;
  17962. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17963. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17964. SSL_shutdown(ssl);
  17965. }
  17966. SSL_free(ssl);
  17967. detail::close_socket(cli);
  17968. SSL_CTX_free(ctx);
  17969. });
  17970. auto se = detail::scope_exit([&] {
  17971. server_thread.join();
  17972. detail::close_socket(srv);
  17973. });
  17974. SSLClient cli("127.0.0.1", port);
  17975. cli.enable_server_certificate_verification(false);
  17976. cli.set_connection_timeout(5, 0);
  17977. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17978. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17979. std::string body(4096, 'A');
  17980. auto res = cli.Put("/api/test", body, "application/json");
  17981. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17982. EXPECT_EQ(StatusCode::OK_200, res->status);
  17983. EXPECT_EQ(body.size(), server_body_bytes.load());
  17984. }
  17985. #endif
  17986. template <typename S, typename C>
  17987. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17988. svr.Get("/stream", [&](const Request &, Response &res) {
  17989. auto data = new std::string("01234567890123456789");
  17990. res.set_content_provider(
  17991. data->size(), "text/plain",
  17992. [&, data](size_t offset, size_t length, DataSink &sink) {
  17993. const size_t DATA_CHUNK_SIZE = 4;
  17994. const auto &d = *data;
  17995. std::this_thread::sleep_for(std::chrono::seconds(1));
  17996. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17997. return true;
  17998. },
  17999. [data](bool success) {
  18000. EXPECT_FALSE(success);
  18001. delete data;
  18002. });
  18003. });
  18004. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18005. auto i = new size_t(0);
  18006. res.set_content_provider(
  18007. "text/plain",
  18008. [i](size_t, DataSink &sink) {
  18009. if (*i < 5) {
  18010. std::this_thread::sleep_for(std::chrono::seconds(1));
  18011. sink.write("abcd", 4);
  18012. (*i)++;
  18013. } else {
  18014. sink.done();
  18015. }
  18016. return true;
  18017. },
  18018. [i](bool success) {
  18019. EXPECT_FALSE(success);
  18020. delete i;
  18021. });
  18022. });
  18023. svr.Get("/chunked", [&](const Request &, Response &res) {
  18024. auto i = new size_t(0);
  18025. res.set_chunked_content_provider(
  18026. "text/plain",
  18027. [i](size_t, DataSink &sink) {
  18028. if (*i < 5) {
  18029. std::this_thread::sleep_for(std::chrono::seconds(1));
  18030. sink.os << "abcd";
  18031. (*i)++;
  18032. } else {
  18033. sink.done();
  18034. }
  18035. return true;
  18036. },
  18037. [i](bool success) {
  18038. EXPECT_FALSE(success);
  18039. delete i;
  18040. });
  18041. });
  18042. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18043. auto se = detail::scope_exit([&] {
  18044. svr.stop();
  18045. listen_thread.join();
  18046. ASSERT_FALSE(svr.is_running());
  18047. });
  18048. svr.wait_until_ready();
  18049. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18050. {
  18051. auto start = std::chrono::steady_clock::now();
  18052. auto res = cli.Get("/stream");
  18053. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18054. std::chrono::steady_clock::now() - start)
  18055. .count();
  18056. ASSERT_FALSE(res);
  18057. EXPECT_EQ(Error::Read, res.error());
  18058. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18059. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18060. }
  18061. {
  18062. auto start = std::chrono::steady_clock::now();
  18063. auto res = cli.Get("/stream_without_length");
  18064. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18065. std::chrono::steady_clock::now() - start)
  18066. .count();
  18067. ASSERT_FALSE(res);
  18068. EXPECT_EQ(Error::Read, res.error());
  18069. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18070. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18071. }
  18072. {
  18073. auto start = std::chrono::steady_clock::now();
  18074. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18075. EXPECT_EQ("abcd", string(data, data_length));
  18076. return true;
  18077. });
  18078. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18079. std::chrono::steady_clock::now() - start)
  18080. .count();
  18081. ASSERT_FALSE(res);
  18082. EXPECT_EQ(Error::Read, res.error());
  18083. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18084. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18085. }
  18086. }
  18087. TEST(MaxTimeoutTest, ContentStream) {
  18088. time_t timeout = 2000;
  18089. time_t threshold = 200;
  18090. Server svr;
  18091. Client cli("localhost", PORT);
  18092. max_timeout_test(svr, cli, timeout, threshold);
  18093. }
  18094. #ifdef CPPHTTPLIB_SSL_ENABLED
  18095. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18096. time_t timeout = 2000;
  18097. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18098. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18099. SSLClient cli("localhost", PORT);
  18100. cli.enable_server_certificate_verification(false);
  18101. max_timeout_test(svr, cli, timeout, threshold);
  18102. }
  18103. #endif
  18104. class EventDispatcher {
  18105. public:
  18106. EventDispatcher() {}
  18107. bool wait_event(DataSink *sink) {
  18108. unique_lock<mutex> lk(m_);
  18109. int id = id_;
  18110. // Wait with timeout to prevent hanging if client disconnects
  18111. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18112. [&] { return cid_ == id; })) {
  18113. return false; // Timeout occurred
  18114. }
  18115. sink->write(message_.data(), message_.size());
  18116. return true;
  18117. }
  18118. void send_event(const string &message) {
  18119. lock_guard<mutex> lk(m_);
  18120. cid_ = id_++;
  18121. message_ = message;
  18122. cv_.notify_all();
  18123. }
  18124. private:
  18125. mutex m_;
  18126. condition_variable cv_;
  18127. atomic_int id_{0};
  18128. atomic_int cid_{-1};
  18129. string message_;
  18130. };
  18131. TEST(ClientInThreadTest, Issue2068) {
  18132. EventDispatcher ed;
  18133. Server svr;
  18134. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18135. res.set_chunked_content_provider("text/event-stream",
  18136. [&](size_t /*offset*/, DataSink &sink) {
  18137. return ed.wait_event(&sink);
  18138. });
  18139. });
  18140. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18141. svr.wait_until_ready();
  18142. thread event_thread([&] {
  18143. int id = 0;
  18144. while (svr.is_running()) {
  18145. this_thread::sleep_for(chrono::milliseconds(500));
  18146. std::stringstream ss;
  18147. ss << "data: " << id << "\n\n";
  18148. ed.send_event(ss.str());
  18149. id++;
  18150. }
  18151. });
  18152. auto se = detail::scope_exit([&] {
  18153. svr.stop();
  18154. listen_thread.join();
  18155. event_thread.join();
  18156. ASSERT_FALSE(svr.is_running());
  18157. });
  18158. {
  18159. auto client = detail::make_unique<Client>(HOST, PORT);
  18160. client->set_read_timeout(std::chrono::minutes(10));
  18161. std::atomic<bool> stop{false};
  18162. std::thread t([&] {
  18163. client->Get("/event1",
  18164. [&](const char *, size_t) -> bool { return !stop; });
  18165. });
  18166. std::this_thread::sleep_for(std::chrono::seconds(2));
  18167. stop = true;
  18168. client->stop();
  18169. t.join();
  18170. // Reset client after thread has finished
  18171. client.reset();
  18172. }
  18173. }
  18174. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18175. auto handled = false;
  18176. Server svr;
  18177. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18178. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18179. auto se = detail::scope_exit([&] {
  18180. svr.stop();
  18181. t.join();
  18182. ASSERT_FALSE(svr.is_running());
  18183. ASSERT_FALSE(handled);
  18184. });
  18185. svr.wait_until_ready();
  18186. // Two Content-Length headers with different values — must be rejected
  18187. auto req = "POST /test HTTP/1.1\r\n"
  18188. "Content-Length: 5\r\n"
  18189. "Content-Length: 10\r\n"
  18190. "\r\n"
  18191. "hello";
  18192. std::string response;
  18193. ASSERT_TRUE(send_request(1, req, &response));
  18194. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18195. response.substr(0, response.find("\r\n")));
  18196. }
  18197. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18198. auto handled = false;
  18199. Server svr;
  18200. svr.Post("/test", [&](const Request &, Response &res) {
  18201. handled = true;
  18202. res.set_content("ok", "text/plain");
  18203. });
  18204. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18205. auto se = detail::scope_exit([&] {
  18206. svr.stop();
  18207. t.join();
  18208. ASSERT_FALSE(svr.is_running());
  18209. ASSERT_TRUE(handled);
  18210. });
  18211. svr.wait_until_ready();
  18212. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18213. auto req = "POST /test HTTP/1.1\r\n"
  18214. "Host: localhost\r\n"
  18215. "Content-Length: 5\r\n"
  18216. "Content-Length: 5\r\n"
  18217. "\r\n"
  18218. "hello";
  18219. std::string response;
  18220. ASSERT_TRUE(send_request(1, req, &response));
  18221. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18222. }
  18223. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18224. Server svr;
  18225. svr.Get("/test", [](const Request &, Response &res) {
  18226. res.set_content("ok", "text/plain");
  18227. });
  18228. auto port = svr.bind_to_any_port(HOST);
  18229. thread t = thread([&] { svr.listen_after_bind(); });
  18230. auto se = detail::scope_exit([&] {
  18231. svr.stop();
  18232. t.join();
  18233. ASSERT_FALSE(svr.is_running());
  18234. });
  18235. svr.wait_until_ready();
  18236. auto status_line = [&](const std::string &host_lines) {
  18237. std::string res;
  18238. send_request(
  18239. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18240. &res, port);
  18241. return res.substr(0, res.find("\r\n"));
  18242. };
  18243. const char *accepted[] = {
  18244. "Host: localhost\r\n",
  18245. "Host: a.example:8080\r\n",
  18246. "Host: my_service\r\n",
  18247. "Host: [::1]:8080\r\n",
  18248. "Host: [fe80::1%25eth0]\r\n",
  18249. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18250. };
  18251. for (auto host_lines : accepted) {
  18252. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18253. }
  18254. const char *rejected[] = {
  18255. "Host: a.example\r\nHost: b.example\r\n",
  18256. "Host: a.example\r\nHost: a.example\r\n",
  18257. "Host: a@b.example\r\n",
  18258. "Host: a.example/b\r\n",
  18259. "Host: a.example\\b\r\n",
  18260. "Host: a.example?b\r\n",
  18261. "Host: a.example#b\r\n",
  18262. "Host: a.example b.example\r\n",
  18263. };
  18264. for (auto host_lines : rejected) {
  18265. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18266. << host_lines;
  18267. }
  18268. }
  18269. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18270. Server svr;
  18271. svr.Get("/", [](const Request &req, Response &res) {
  18272. EXPECT_EQ(2U, req.trailers.size());
  18273. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18274. // Denied
  18275. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18276. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18277. // Accepted
  18278. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18279. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18280. EXPECT_TRUE(req.has_trailer("X-World"));
  18281. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18282. res.set_content("ok", "text/plain");
  18283. });
  18284. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18285. auto se = detail::scope_exit([&] {
  18286. svr.stop();
  18287. t.join();
  18288. ASSERT_FALSE(svr.is_running());
  18289. });
  18290. svr.wait_until_ready();
  18291. const std::string req = "GET / HTTP/1.1\r\n"
  18292. "Transfer-Encoding: chunked\r\n"
  18293. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18294. "\r\n"
  18295. "0\r\n"
  18296. "Content-Length: 10\r\n"
  18297. "Host: internal.local\r\n"
  18298. "Content-Type: malicious/content\r\n"
  18299. "Cookie: any\r\n"
  18300. "Set-Cookie: any\r\n"
  18301. "X-Forwarded-For: attacker.com\r\n"
  18302. "X-Real-Ip: 1.1.1.1\r\n"
  18303. "X-Hello: hello\r\n"
  18304. "X-World: world\r\n"
  18305. "\r\n";
  18306. std::string res;
  18307. ASSERT_TRUE(send_request(1, req, &res));
  18308. }
  18309. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18310. // several field lines, and the combined value is what has to be parsed. A
  18311. // Trailer field split across lines therefore declares every name it lists;
  18312. // reading only the first line silently drops the trailers the later lines
  18313. // declare. The prohibited-trailer filter still applies to every line.
  18314. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18315. Server svr;
  18316. size_t observed_trailer_count = 0;
  18317. std::string observed_hello;
  18318. std::string observed_world;
  18319. bool observed_content_length = true;
  18320. svr.Get("/", [&](const Request &req, Response &res) {
  18321. observed_trailer_count = req.trailers.size();
  18322. observed_hello = req.get_trailer_value("X-Hello");
  18323. observed_world = req.get_trailer_value("X-World");
  18324. observed_content_length = req.has_trailer("Content-Length");
  18325. res.set_content("ok", "text/plain");
  18326. });
  18327. auto port = svr.bind_to_any_port(HOST);
  18328. thread t = thread([&]() { svr.listen_after_bind(); });
  18329. auto se = detail::scope_exit([&] {
  18330. svr.stop();
  18331. t.join();
  18332. ASSERT_FALSE(svr.is_running());
  18333. });
  18334. svr.wait_until_ready();
  18335. const std::string req = "GET / HTTP/1.1\r\n"
  18336. "Host: localhost\r\n"
  18337. "Transfer-Encoding: chunked\r\n"
  18338. "Trailer: X-Hello\r\n"
  18339. "Trailer: X-World, Content-Length\r\n"
  18340. "\r\n"
  18341. "0\r\n"
  18342. "X-Hello: hello\r\n"
  18343. "X-World: world\r\n"
  18344. "Content-Length: 10\r\n"
  18345. "\r\n";
  18346. std::string res;
  18347. ASSERT_TRUE(send_request(1, req, &res, port));
  18348. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18349. // Accepted: both field lines contribute to the declared set
  18350. EXPECT_EQ(2U, observed_trailer_count);
  18351. EXPECT_EQ(observed_hello, "hello");
  18352. EXPECT_EQ(observed_world, "world");
  18353. // Denied: a prohibited name stays prohibited on a later field line
  18354. EXPECT_FALSE(observed_content_length);
  18355. }
  18356. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18357. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18358. // unbounded run of fields that are never declared, because the counter would
  18359. // only advance for declared fields.
  18360. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18361. Server svr;
  18362. bool handler_called = false;
  18363. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18364. handler_called = true;
  18365. res.set_content("ok", "text/plain");
  18366. });
  18367. auto port = svr.bind_to_any_port(HOST);
  18368. thread t = thread([&]() { svr.listen_after_bind(); });
  18369. auto se = detail::scope_exit([&] {
  18370. svr.stop();
  18371. t.join();
  18372. ASSERT_FALSE(svr.is_running());
  18373. });
  18374. svr.wait_until_ready();
  18375. // Declare nothing, then send far more undeclared trailer fields than the
  18376. // header-count limit. Parsing must stop and reject the request rather than
  18377. // read every line.
  18378. std::string req = "GET / HTTP/1.1\r\n"
  18379. "Transfer-Encoding: chunked\r\n"
  18380. "\r\n"
  18381. "0\r\n";
  18382. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18383. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18384. }
  18385. req += "\r\n";
  18386. std::string res;
  18387. ASSERT_TRUE(send_request(1, req, &res, port));
  18388. // The request is rejected before the handler runs.
  18389. EXPECT_FALSE(handler_called);
  18390. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18391. }
  18392. // The set of declared trailer names is capped so a peer cannot grow it without
  18393. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18394. // declared past the cap is not honored, even if the field is actually sent.
  18395. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18396. Server svr;
  18397. // One name inside the cap and one past it, so the test tracks the cap rather
  18398. // than a fixed count.
  18399. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18400. const std::string within_cap_name = "X-T-0";
  18401. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18402. bool observed_within_cap = false;
  18403. bool observed_past_cap = false;
  18404. svr.Get("/", [&](const Request &req, Response &res) {
  18405. observed_within_cap = req.has_trailer(within_cap_name);
  18406. observed_past_cap = req.has_trailer(past_cap_name);
  18407. res.set_content("ok", "text/plain");
  18408. });
  18409. auto port = svr.bind_to_any_port(HOST);
  18410. thread t = thread([&]() { svr.listen_after_bind(); });
  18411. auto se = detail::scope_exit([&] {
  18412. svr.stop();
  18413. t.join();
  18414. ASSERT_FALSE(svr.is_running());
  18415. });
  18416. svr.wait_until_ready();
  18417. // Declare more trailer names than the cap in a single Trailer field, then
  18418. // actually send the first (within the cap) and the last (past it).
  18419. std::string trailer_decl = "Trailer: ";
  18420. for (int i = 0; i < declared_count; i++) {
  18421. if (i != 0) { trailer_decl += ", "; }
  18422. trailer_decl += "X-T-" + std::to_string(i);
  18423. }
  18424. trailer_decl += "\r\n";
  18425. const std::string req = "GET / HTTP/1.1\r\n"
  18426. "Host: localhost\r\n"
  18427. "Transfer-Encoding: chunked\r\n" +
  18428. trailer_decl +
  18429. "\r\n"
  18430. "0\r\n" +
  18431. within_cap_name + ": a\r\n" + past_cap_name +
  18432. ": b\r\n"
  18433. "\r\n";
  18434. std::string res;
  18435. ASSERT_TRUE(send_request(1, req, &res, port));
  18436. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18437. // A name within the cap is honored; one declared past the cap is dropped.
  18438. EXPECT_TRUE(observed_within_cap);
  18439. EXPECT_FALSE(observed_past_cap);
  18440. }
  18441. // A direct client that is not listed in trusted_proxies must not be able to
  18442. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18443. // the peer address on the actual TCP connection determines whether the
  18444. // header is honored.
  18445. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18446. Server svr;
  18447. // Deliberately does NOT include the loopback address the test client
  18448. // actually connects from, so the direct connection is not a trusted proxy.
  18449. svr.set_trusted_proxies({"203.0.113.66"});
  18450. std::string observed_remote_addr;
  18451. svr.Get("/ip", [&](const Request &req, Response &res) {
  18452. observed_remote_addr = req.remote_addr;
  18453. res.set_content("ok", "text/plain");
  18454. });
  18455. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18456. auto se = detail::scope_exit([&] {
  18457. svr.stop();
  18458. t.join();
  18459. ASSERT_FALSE(svr.is_running());
  18460. });
  18461. svr.wait_until_ready();
  18462. Client cli(HOST, PORT);
  18463. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18465. EXPECT_EQ(StatusCode::OK_200, res->status);
  18466. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18467. // ignored entirely and the real connection-level address retained.
  18468. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18469. observed_remote_addr == "127.0.0.1");
  18470. }
  18471. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18472. Server svr;
  18473. std::string observed_remote_addr;
  18474. std::string observed_xff;
  18475. svr.Get("/ip", [&](const Request &req, Response &res) {
  18476. observed_remote_addr = req.remote_addr;
  18477. observed_xff = req.get_header_value("X-Forwarded-For");
  18478. res.set_content("ok", "text/plain");
  18479. });
  18480. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18481. auto se = detail::scope_exit([&] {
  18482. svr.stop();
  18483. t.join();
  18484. ASSERT_FALSE(svr.is_running());
  18485. });
  18486. svr.wait_until_ready();
  18487. Client cli(HOST, PORT);
  18488. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18490. EXPECT_EQ(StatusCode::OK_200, res->status);
  18491. EXPECT_EQ(observed_xff, "203.0.113.66");
  18492. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18493. observed_remote_addr == "127.0.0.1");
  18494. }
  18495. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18496. Server svr;
  18497. svr.set_trusted_proxies({"203.0.113.66"});
  18498. std::string observed_remote_addr;
  18499. std::string observed_xff;
  18500. svr.Get("/ip", [&](const Request &req, Response &res) {
  18501. observed_remote_addr = req.remote_addr;
  18502. observed_xff = req.get_header_value("X-Forwarded-For");
  18503. res.set_content("ok", "text/plain");
  18504. });
  18505. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18506. auto se = detail::scope_exit([&] {
  18507. svr.stop();
  18508. t.join();
  18509. ASSERT_FALSE(svr.is_running());
  18510. });
  18511. svr.wait_until_ready();
  18512. Client cli(HOST, PORT);
  18513. auto res = cli.Get("/ip");
  18514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18515. EXPECT_EQ(StatusCode::OK_200, res->status);
  18516. EXPECT_EQ(observed_xff, "");
  18517. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18518. observed_remote_addr == "127.0.0.1");
  18519. }
  18520. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18521. Server svr;
  18522. // Include the loopback address the test client actually connects from, so
  18523. // the direct connection itself is recognized as the trusted proxy hop.
  18524. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18525. std::string observed_remote_addr;
  18526. std::string observed_xff;
  18527. svr.Get("/ip", [&](const Request &req, Response &res) {
  18528. observed_remote_addr = req.remote_addr;
  18529. observed_xff = req.get_header_value("X-Forwarded-For");
  18530. res.set_content("ok", "text/plain");
  18531. });
  18532. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18533. auto se = detail::scope_exit([&] {
  18534. svr.stop();
  18535. t.join();
  18536. ASSERT_FALSE(svr.is_running());
  18537. });
  18538. svr.wait_until_ready();
  18539. Client cli(HOST, PORT);
  18540. auto res = cli.Get(
  18541. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18543. EXPECT_EQ(StatusCode::OK_200, res->status);
  18544. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18545. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18546. }
  18547. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18548. Server svr;
  18549. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18550. std::string observed_remote_addr;
  18551. std::string observed_xff;
  18552. svr.Get("/ip", [&](const Request &req, Response &res) {
  18553. observed_remote_addr = req.remote_addr;
  18554. observed_xff = req.get_header_value("X-Forwarded-For");
  18555. res.set_content("ok", "text/plain");
  18556. });
  18557. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18558. auto se = detail::scope_exit([&] {
  18559. svr.stop();
  18560. t.join();
  18561. ASSERT_FALSE(svr.is_running());
  18562. });
  18563. svr.wait_until_ready();
  18564. Client cli(HOST, PORT);
  18565. auto res = cli.Get(
  18566. "/ip",
  18567. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18569. EXPECT_EQ(StatusCode::OK_200, res->status);
  18570. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18571. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18572. }
  18573. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18574. Server svr;
  18575. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18576. std::string observed_remote_addr;
  18577. std::string observed_xff;
  18578. svr.Get("/ip", [&](const Request &req, Response &res) {
  18579. observed_remote_addr = req.remote_addr;
  18580. observed_xff = req.get_header_value("X-Forwarded-For");
  18581. res.set_content("ok", "text/plain");
  18582. });
  18583. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18584. auto se = detail::scope_exit([&] {
  18585. svr.stop();
  18586. t.join();
  18587. ASSERT_FALSE(svr.is_running());
  18588. });
  18589. svr.wait_until_ready();
  18590. Client cli(HOST, PORT);
  18591. auto res = cli.Get(
  18592. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18594. EXPECT_EQ(StatusCode::OK_200, res->status);
  18595. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18596. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18597. // and must not be selected.
  18598. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18599. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18600. }
  18601. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18602. Server svr;
  18603. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18604. std::string observed_remote_addr;
  18605. svr.Get("/ip", [&](const Request &req, Response &res) {
  18606. observed_remote_addr = req.remote_addr;
  18607. res.set_content("ok", "text/plain");
  18608. });
  18609. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18610. auto se = detail::scope_exit([&] {
  18611. svr.stop();
  18612. t.join();
  18613. ASSERT_FALSE(svr.is_running());
  18614. });
  18615. svr.wait_until_ready();
  18616. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18617. // a forged address and the trusted proxy's own address; the forged value must
  18618. // not win over the address the trusted proxy actually recorded.
  18619. Client cli(HOST, PORT);
  18620. auto res = cli.Get(
  18621. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18623. EXPECT_EQ(StatusCode::OK_200, res->status);
  18624. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18625. }
  18626. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18627. Server svr;
  18628. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18629. std::string observed_remote_addr;
  18630. std::string observed_xff;
  18631. svr.Get("/ip", [&](const Request &req, Response &res) {
  18632. observed_remote_addr = req.remote_addr;
  18633. observed_xff = req.get_header_value("X-Forwarded-For");
  18634. res.set_content("ok", "text/plain");
  18635. });
  18636. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18637. auto se = detail::scope_exit([&] {
  18638. svr.stop();
  18639. t.join();
  18640. ASSERT_FALSE(svr.is_running());
  18641. });
  18642. svr.wait_until_ready();
  18643. Client cli(HOST, PORT);
  18644. auto res = cli.Get(
  18645. "/ip",
  18646. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18648. EXPECT_EQ(StatusCode::OK_200, res->status);
  18649. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18650. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18651. }
  18652. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18653. Server svr;
  18654. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18655. std::string observed_remote_addr;
  18656. std::string observed_xff;
  18657. svr.Get("/ip", [&](const Request &req, Response &res) {
  18658. observed_remote_addr = req.remote_addr;
  18659. observed_xff = req.get_header_value("X-Forwarded-For");
  18660. res.set_content("ok", "text/plain");
  18661. });
  18662. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18663. auto se = detail::scope_exit([&] {
  18664. svr.stop();
  18665. t.join();
  18666. ASSERT_FALSE(svr.is_running());
  18667. });
  18668. svr.wait_until_ready();
  18669. std::string raw_req =
  18670. "GET /ip HTTP/1.1\r\n"
  18671. "Host: localhost\r\n"
  18672. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18673. "Connection: close\r\n"
  18674. "\r\n";
  18675. std::string out;
  18676. ASSERT_TRUE(send_request(5, raw_req, &out));
  18677. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18678. // Header parser trims surrounding whitespace of the header value
  18679. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18680. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18681. }
  18682. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18683. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18684. // their own X-Forwarded-For as a separate field line rather than extending the
  18685. // one the client sent, so every occurrence has to be taken into account.
  18686. // Reading only the first one hands back the address the client chose.
  18687. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18688. Server svr;
  18689. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18690. std::string observed_remote_addr;
  18691. size_t observed_xff_count = 0;
  18692. svr.Get("/ip", [&](const Request &req, Response &res) {
  18693. observed_remote_addr = req.remote_addr;
  18694. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18695. res.set_content("ok", "text/plain");
  18696. });
  18697. auto port = svr.bind_to_any_port(HOST);
  18698. thread t = thread([&]() { svr.listen_after_bind(); });
  18699. auto se = detail::scope_exit([&] {
  18700. svr.stop();
  18701. t.join();
  18702. ASSERT_FALSE(svr.is_running());
  18703. });
  18704. svr.wait_until_ready();
  18705. // The client supplies the first field line; the trusted proxy appends the
  18706. // address it observed as a second one.
  18707. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18708. "Host: localhost\r\n"
  18709. "X-Forwarded-For: 1.2.3.4\r\n"
  18710. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18711. "Connection: close\r\n"
  18712. "\r\n";
  18713. std::string out;
  18714. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18715. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18716. EXPECT_EQ(observed_xff_count, 2U);
  18717. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18718. // The same chain spread over one field line per hop derives the same client
  18719. // address, i.e. the split and the comma-joined representations agree.
  18720. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18721. "Host: localhost\r\n"
  18722. "X-Forwarded-For: 1.2.3.4\r\n"
  18723. "X-Forwarded-For: 198.51.100.23\r\n"
  18724. "X-Forwarded-For: 192.0.2.45\r\n"
  18725. "Connection: close\r\n"
  18726. "\r\n";
  18727. out.clear();
  18728. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18729. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18730. EXPECT_EQ(observed_xff_count, 3U);
  18731. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18732. }
  18733. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18734. // crash the server (it used to call front() on an empty vector inside
  18735. // get_client_ip). The connection-level remote address must be retained instead.
  18736. static void run_malformed_xff_test(const std::string &xff_value) {
  18737. Server svr;
  18738. svr.set_trusted_proxies({"192.0.2.45"});
  18739. std::string observed_remote_addr;
  18740. svr.Get("/ip", [&](const Request &req, Response &res) {
  18741. observed_remote_addr = req.remote_addr;
  18742. res.set_content("ok", "text/plain");
  18743. });
  18744. int port = 0;
  18745. thread t = thread([&]() {
  18746. port = svr.bind_to_any_port(HOST);
  18747. svr.listen_after_bind();
  18748. });
  18749. auto se = detail::scope_exit([&] {
  18750. svr.stop();
  18751. t.join();
  18752. ASSERT_FALSE(svr.is_running());
  18753. });
  18754. svr.wait_until_ready();
  18755. Client cli(HOST, port);
  18756. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18758. EXPECT_EQ(StatusCode::OK_200, res->status);
  18759. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18760. observed_remote_addr == "127.0.0.1");
  18761. }
  18762. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18763. run_malformed_xff_test("");
  18764. }
  18765. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18766. run_malformed_xff_test(",");
  18767. }
  18768. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18769. run_malformed_xff_test(", , ,");
  18770. }
  18771. // The same rule applies to Accept: a request whose acceptable types are spread
  18772. // over several field lines must be negotiated against all of them.
  18773. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18774. // case-insensitive connection options. Comparing the whole field value against
  18775. // one option misses a client that sends several of them, and misses every
  18776. // casing but the one written in the comparison.
  18777. //
  18778. // Sends req, reads the response, then reuses the same socket for a second
  18779. // request to find out whether the server kept the connection.
  18780. static void probe_connection_reuse(int port, const std::string &req,
  18781. bool *announced_close, bool *reusable) {
  18782. auto error = Error::Success;
  18783. auto sock = detail::create_client_socket(
  18784. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18785. /*connection_timeout_sec=*/5, 0,
  18786. /*read_timeout_sec=*/1, 0,
  18787. /*write_timeout_sec=*/5, 0, std::string(), error);
  18788. ASSERT_NE(sock, INVALID_SOCKET);
  18789. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18790. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18791. "Host: localhost\r\n"
  18792. "Connection: close\r\n"
  18793. "\r\n";
  18794. std::string first_response;
  18795. std::string second_response;
  18796. detail::process_client_socket(
  18797. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18798. [&](Stream &strm) {
  18799. if (strm.write(req.data(), req.size()) !=
  18800. static_cast<ssize_t>(req.size())) {
  18801. return false;
  18802. }
  18803. char buf[512];
  18804. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18805. // Headers plus the two-byte body of the handler below
  18806. while (reader.getline()) {
  18807. first_response += reader.ptr();
  18808. if (first_response.find("ok") != std::string::npos) { break; }
  18809. }
  18810. if (strm.write(second.data(), second.size()) !=
  18811. static_cast<ssize_t>(second.size())) {
  18812. return true;
  18813. }
  18814. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18815. while (reader2.getline()) {
  18816. second_response += reader2.ptr();
  18817. if (second_response.find("ok") != std::string::npos) { break; }
  18818. }
  18819. return true;
  18820. });
  18821. *announced_close =
  18822. first_response.find("Connection: close") != std::string::npos;
  18823. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18824. }
  18825. class ConnectionTokenTest : public ::testing::Test {
  18826. protected:
  18827. void SetUp() override {
  18828. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18829. res.set_content("ok", "text/plain");
  18830. });
  18831. port_ = svr_.bind_to_any_port(HOST);
  18832. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18833. svr_.wait_until_ready();
  18834. }
  18835. void TearDown() override {
  18836. svr_.stop();
  18837. if (thread_.joinable()) { thread_.join(); }
  18838. }
  18839. Server svr_;
  18840. int port_ = 0;
  18841. thread thread_;
  18842. };
  18843. // "close" alongside another option still closes the connection, and the
  18844. // response says so rather than leaving the peer to discover it.
  18845. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18846. bool announced_close = false;
  18847. bool reusable = true;
  18848. probe_connection_reuse(port_,
  18849. "GET /keepalive HTTP/1.1\r\n"
  18850. "Host: localhost\r\n"
  18851. "Connection: keep-alive, close\r\n"
  18852. "\r\n",
  18853. &announced_close, &reusable);
  18854. EXPECT_TRUE(announced_close);
  18855. EXPECT_FALSE(reusable);
  18856. }
  18857. // "close" split over two field lines is the same list, so it is honored too.
  18858. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18859. bool announced_close = false;
  18860. bool reusable = true;
  18861. probe_connection_reuse(port_,
  18862. "GET /keepalive HTTP/1.1\r\n"
  18863. "Host: localhost\r\n"
  18864. "Connection: keep-alive\r\n"
  18865. "Connection: close\r\n"
  18866. "\r\n",
  18867. &announced_close, &reusable);
  18868. EXPECT_TRUE(announced_close);
  18869. EXPECT_FALSE(reusable);
  18870. }
  18871. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18872. // keep-alive in the spelling everyone actually sends keeps its connection.
  18873. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18874. bool announced_close = false;
  18875. bool reusable = false;
  18876. probe_connection_reuse(port_,
  18877. "GET /keepalive HTTP/1.0\r\n"
  18878. "Host: localhost\r\n"
  18879. "Connection: keep-alive\r\n"
  18880. "\r\n",
  18881. &announced_close, &reusable);
  18882. EXPECT_FALSE(announced_close);
  18883. EXPECT_TRUE(reusable);
  18884. }
  18885. // A token the value merely contains is not the token itself.
  18886. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18887. bool announced_close = false;
  18888. bool reusable = false;
  18889. probe_connection_reuse(port_,
  18890. "GET /keepalive HTTP/1.1\r\n"
  18891. "Host: localhost\r\n"
  18892. "Connection: notclose\r\n"
  18893. "\r\n",
  18894. &announced_close, &reusable);
  18895. EXPECT_FALSE(announced_close);
  18896. EXPECT_TRUE(reusable);
  18897. }
  18898. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18899. Server svr;
  18900. std::vector<std::string> observed_types;
  18901. svr.Get("/", [&](const Request &req, Response &res) {
  18902. observed_types = req.accept_content_types;
  18903. res.set_content("ok", "text/plain");
  18904. });
  18905. auto port = svr.bind_to_any_port(HOST);
  18906. thread t = thread([&]() { svr.listen_after_bind(); });
  18907. auto se = detail::scope_exit([&] {
  18908. svr.stop();
  18909. t.join();
  18910. ASSERT_FALSE(svr.is_running());
  18911. });
  18912. svr.wait_until_ready();
  18913. Client cli(HOST, port);
  18914. Headers headers;
  18915. headers.emplace("Accept", "text/plain;q=0.5");
  18916. headers.emplace("Accept", "application/json");
  18917. auto res = cli.Get("/", headers);
  18918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18919. EXPECT_EQ(StatusCode::OK_200, res->status);
  18920. // Sorted by q-value, so the second field line's type comes first
  18921. ASSERT_EQ(2U, observed_types.size());
  18922. EXPECT_EQ("application/json", observed_types[0]);
  18923. EXPECT_EQ("text/plain", observed_types[1]);
  18924. }
  18925. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18926. // empty field line must not contribute a bare comma to the combined value.
  18927. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18928. Server svr;
  18929. std::vector<std::string> observed_types;
  18930. svr.Get("/", [&](const Request &req, Response &res) {
  18931. observed_types = req.accept_content_types;
  18932. res.set_content("ok", "text/plain");
  18933. });
  18934. auto port = svr.bind_to_any_port(HOST);
  18935. thread t = thread([&]() { svr.listen_after_bind(); });
  18936. auto se = detail::scope_exit([&] {
  18937. svr.stop();
  18938. t.join();
  18939. ASSERT_FALSE(svr.is_running());
  18940. });
  18941. svr.wait_until_ready();
  18942. // Empty first field line, then a real one
  18943. std::string raw_req = "GET / HTTP/1.1\r\n"
  18944. "Host: localhost\r\n"
  18945. "Accept:\r\n"
  18946. "Accept: application/json\r\n"
  18947. "Connection: close\r\n"
  18948. "\r\n";
  18949. std::string out;
  18950. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18951. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18952. ASSERT_EQ(1U, observed_types.size());
  18953. EXPECT_EQ("application/json", observed_types[0]);
  18954. }
  18955. // The skip in get_combined_header_value() is what keeps an empty field line
  18956. // from contributing a bare comma. Only a trailing empty field line exercises
  18957. // it: a leading one is already covered by the "combined is still empty" check,
  18958. // and parse_accept_header() now ignores the empty element either way, so the
  18959. // request-level test above can no longer tell the two apart.
  18960. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18961. Headers headers;
  18962. headers.emplace("Accept", "text/html");
  18963. headers.emplace("Accept", "");
  18964. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18965. headers.clear();
  18966. headers.emplace("Accept", "");
  18967. headers.emplace("Accept", "application/json");
  18968. EXPECT_EQ("application/json",
  18969. detail::get_combined_header_value(headers, "Accept"));
  18970. }
  18971. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18972. // An encoding offered on a later Accept-Encoding field line is still offered.
  18973. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18974. Server svr;
  18975. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18976. res.set_content(std::string(1024, 'x'), "text/plain");
  18977. });
  18978. auto port = svr.bind_to_any_port(HOST);
  18979. thread t = thread([&]() { svr.listen_after_bind(); });
  18980. auto se = detail::scope_exit([&] {
  18981. svr.stop();
  18982. t.join();
  18983. ASSERT_FALSE(svr.is_running());
  18984. });
  18985. svr.wait_until_ready();
  18986. Client cli(HOST, port);
  18987. cli.set_decompress(false);
  18988. Headers headers;
  18989. headers.emplace("Accept-Encoding", "identity");
  18990. headers.emplace("Accept-Encoding", "gzip");
  18991. auto res = cli.Get("/", headers);
  18992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18993. EXPECT_EQ(StatusCode::OK_200, res->status);
  18994. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18995. }
  18996. #endif
  18997. #ifndef _WIN32
  18998. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18999. Server svr;
  19000. svr.Post("/post", [&](const Request &req, Response &res) {
  19001. res.set_content(req.body, "text/plain");
  19002. });
  19003. svr.Put("/put", [&](const Request &req, Response &res) {
  19004. res.set_content(req.body, "text/plain");
  19005. });
  19006. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19007. res.set_content(req.body, "text/plain");
  19008. });
  19009. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19010. res.set_content(req.body, "text/plain");
  19011. });
  19012. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19013. auto se = detail::scope_exit([&] {
  19014. svr.stop();
  19015. t.join();
  19016. ASSERT_FALSE(svr.is_running());
  19017. });
  19018. svr.wait_until_ready();
  19019. std::string resp;
  19020. // POST without Content-Length
  19021. ASSERT_TRUE(send_request(5,
  19022. "POST /post HTTP/1.1\r\n"
  19023. "Host: localhost\r\n"
  19024. "Connection: close\r\n"
  19025. "\r\n",
  19026. &resp));
  19027. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19028. // PUT without Content-Length
  19029. resp.clear();
  19030. ASSERT_TRUE(send_request(5,
  19031. "PUT /put HTTP/1.1\r\n"
  19032. "Host: localhost\r\n"
  19033. "Connection: close\r\n"
  19034. "\r\n",
  19035. &resp));
  19036. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19037. // PATCH without Content-Length
  19038. resp.clear();
  19039. ASSERT_TRUE(send_request(5,
  19040. "PATCH /patch HTTP/1.1\r\n"
  19041. "Host: localhost\r\n"
  19042. "Connection: close\r\n"
  19043. "\r\n",
  19044. &resp));
  19045. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19046. // DELETE without Content-Length
  19047. resp.clear();
  19048. ASSERT_TRUE(send_request(5,
  19049. "DELETE /delete HTTP/1.1\r\n"
  19050. "Host: localhost\r\n"
  19051. "Connection: close\r\n"
  19052. "\r\n",
  19053. &resp));
  19054. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19055. }
  19056. #endif
  19057. //==============================================================================
  19058. // open_stream() Tests
  19059. //==============================================================================
  19060. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19061. std::string result;
  19062. char buf[8192];
  19063. ssize_t n;
  19064. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19065. result.append(buf, static_cast<size_t>(n));
  19066. }
  19067. return result;
  19068. }
  19069. // Mock stream for unit tests
  19070. class MockStream : public Stream {
  19071. public:
  19072. std::string data;
  19073. size_t pos = 0;
  19074. ssize_t error_after = -1; // -1 = no error
  19075. explicit MockStream(const std::string &d, ssize_t err = -1)
  19076. : data(d), error_after(err) {}
  19077. bool is_readable() const override { return true; }
  19078. bool wait_readable() const override { return true; }
  19079. bool wait_writable() const override { return true; }
  19080. ssize_t read(char *ptr, size_t size) override {
  19081. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19082. if (pos >= data.size()) return 0;
  19083. size_t limit =
  19084. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19085. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19086. std::memcpy(ptr, data.data() + pos, to_read);
  19087. pos += to_read;
  19088. return static_cast<ssize_t>(to_read);
  19089. }
  19090. ssize_t write(const char *, size_t) override { return -1; }
  19091. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19092. ip = "127.0.0.1";
  19093. port = 0;
  19094. }
  19095. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19096. ip = "127.0.0.1";
  19097. port = 0;
  19098. }
  19099. socket_t socket() const override { return INVALID_SOCKET; }
  19100. time_t duration() const override { return 0; }
  19101. };
  19102. TEST(StreamHandleTest, Basic) {
  19103. ClientImpl::StreamHandle handle;
  19104. EXPECT_FALSE(handle.is_valid());
  19105. handle.response = detail::make_unique<Response>();
  19106. handle.error = Error::Connection;
  19107. EXPECT_FALSE(handle.is_valid());
  19108. handle.error = Error::Success;
  19109. EXPECT_TRUE(handle.is_valid());
  19110. }
  19111. TEST(BodyReaderTest, Basic) {
  19112. MockStream stream("Hello, World!");
  19113. detail::BodyReader reader;
  19114. reader.stream = &stream;
  19115. reader.content_length = 13;
  19116. char buf[32];
  19117. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19118. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19119. EXPECT_TRUE(reader.eof);
  19120. }
  19121. TEST(BodyReaderTest, NoStream) {
  19122. detail::BodyReader reader;
  19123. char buf[32];
  19124. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19125. EXPECT_EQ(Error::Connection, reader.last_error);
  19126. }
  19127. TEST(BodyReaderTest, Error) {
  19128. MockStream stream("Hello, World!", 5);
  19129. detail::BodyReader reader;
  19130. reader.stream = &stream;
  19131. reader.content_length = 13;
  19132. char buf[32];
  19133. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19134. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19135. EXPECT_EQ(Error::Read, reader.last_error);
  19136. }
  19137. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19138. // Mock-based StreamHandle tests relying on private internals are removed.
  19139. class OpenStreamTest : public ::testing::Test {
  19140. protected:
  19141. void SetUp() override {
  19142. svr_.Get("/hello", [](const Request &, Response &res) {
  19143. res.set_content("Hello World!", "text/plain");
  19144. });
  19145. svr_.Get("/large", [](const Request &, Response &res) {
  19146. res.set_content(std::string(10000, 'X'), "text/plain");
  19147. });
  19148. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19149. res.set_content("Hello World!", "image/jpeg");
  19150. res.set_header("Content-Encoding", "UTF-8");
  19151. });
  19152. svr_.Get("/chunked", [](const Request &, Response &res) {
  19153. res.set_chunked_content_provider("text/plain",
  19154. [](size_t offset, DataSink &sink) {
  19155. if (offset < 15) {
  19156. sink.write("chunk", 5);
  19157. return true;
  19158. }
  19159. sink.done();
  19160. return true;
  19161. });
  19162. });
  19163. svr_.Get("/compressible", [](const Request &, Response &res) {
  19164. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19165. DataSink &sink) {
  19166. if (offset < 100 * 1024) {
  19167. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19168. sink.write(chunk.data(), chunk.size());
  19169. return true;
  19170. }
  19171. sink.done();
  19172. return true;
  19173. });
  19174. });
  19175. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19176. [](const Request & /*req*/, Response &res) {
  19177. auto i = new int(0);
  19178. res.set_header("Trailer", "Content-Length, X-Allowed");
  19179. res.set_chunked_content_provider(
  19180. "text/plain",
  19181. [i](size_t /*offset*/, DataSink &sink) {
  19182. switch (*i) {
  19183. case 0: sink.os << "123"; break;
  19184. case 1: sink.os << "456"; break;
  19185. case 2: sink.os << "789"; break;
  19186. case 3: {
  19187. sink.done_with_trailer(
  19188. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19189. } break;
  19190. }
  19191. (*i)++;
  19192. return true;
  19193. },
  19194. [i](bool success) {
  19195. EXPECT_TRUE(success);
  19196. delete i;
  19197. });
  19198. });
  19199. // Echo headers endpoint for header-related tests
  19200. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19201. std::string body;
  19202. for (const auto &h : req.headers) {
  19203. body.append(h.first);
  19204. body.push_back(':');
  19205. body.append(h.second);
  19206. body.push_back('\n');
  19207. }
  19208. res.set_content(body, "text/plain");
  19209. });
  19210. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19211. std::string body;
  19212. for (const auto &h : req.headers) {
  19213. body.append(h.first);
  19214. body.push_back(':');
  19215. body.append(h.second);
  19216. body.push_back('\n');
  19217. }
  19218. res.set_content(body, "text/plain");
  19219. });
  19220. port_ = svr_.bind_to_any_port("127.0.0.1");
  19221. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19222. svr_.wait_until_ready();
  19223. }
  19224. void TearDown() override {
  19225. svr_.stop();
  19226. if (thread_.joinable()) thread_.join();
  19227. }
  19228. Server svr_;
  19229. std::thread thread_;
  19230. int port_ = 0;
  19231. };
  19232. TEST_F(OpenStreamTest, Basic) {
  19233. Client cli("127.0.0.1", port_);
  19234. auto handle = cli.open_stream("GET", "/hello");
  19235. EXPECT_TRUE(handle.is_valid());
  19236. EXPECT_EQ("Hello World!", read_all(handle));
  19237. }
  19238. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19239. Client cli("127.0.0.1", port_);
  19240. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19241. ASSERT_TRUE(handle.is_valid());
  19242. EXPECT_EQ("Hello World!", read_all(handle));
  19243. }
  19244. TEST_F(OpenStreamTest, SmallBuffer) {
  19245. Client cli("127.0.0.1", port_);
  19246. auto handle = cli.open_stream("GET", "/hello");
  19247. std::string result;
  19248. char buf[4];
  19249. ssize_t n;
  19250. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19251. result.append(buf, static_cast<size_t>(n));
  19252. EXPECT_EQ("Hello World!", result);
  19253. }
  19254. TEST_F(OpenStreamTest, DefaultHeaders) {
  19255. Client cli("127.0.0.1", port_);
  19256. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19257. {
  19258. auto handle = cli.open_stream("GET", "/echo-headers");
  19259. ASSERT_TRUE(handle.is_valid());
  19260. auto body = read_all(handle);
  19261. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19262. std::string::npos);
  19263. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19264. std::string::npos);
  19265. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19266. }
  19267. // open_stream POST with body and no explicit content_type should NOT add
  19268. // text/plain Content-Type (behavior differs from non-streaming path), but
  19269. // should include Content-Length
  19270. {
  19271. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19272. ASSERT_TRUE(handle.is_valid());
  19273. auto body = read_all(handle);
  19274. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19275. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19276. }
  19277. // open_stream POST with explicit Content-Type should preserve it
  19278. {
  19279. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19280. {{"Content-Type", "application/custom"}},
  19281. "{}", "application/custom");
  19282. ASSERT_TRUE(handle.is_valid());
  19283. auto body = read_all(handle);
  19284. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19285. }
  19286. // User-specified User-Agent must not be overwritten for stream API
  19287. {
  19288. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19289. {{"User-Agent", "MyAgent/1.2"}});
  19290. ASSERT_TRUE(handle.is_valid());
  19291. auto body = read_all(handle);
  19292. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19293. }
  19294. }
  19295. TEST_F(OpenStreamTest, Large) {
  19296. Client cli("127.0.0.1", port_);
  19297. auto handle = cli.open_stream("GET", "/large");
  19298. EXPECT_EQ(10000u, read_all(handle).size());
  19299. }
  19300. TEST_F(OpenStreamTest, ConnectionError) {
  19301. Client cli("127.0.0.1", 9999);
  19302. auto handle = cli.open_stream("GET", "/hello");
  19303. EXPECT_FALSE(handle.is_valid());
  19304. }
  19305. TEST_F(OpenStreamTest, Chunked) {
  19306. Client cli("127.0.0.1", port_);
  19307. auto handle = cli.open_stream("GET", "/chunked");
  19308. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19309. "Transfer-Encoding") == "chunked");
  19310. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19311. }
  19312. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19313. Client cli("127.0.0.1", port_);
  19314. auto handle =
  19315. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19316. ASSERT_TRUE(handle.is_valid());
  19317. // Consume body to allow trailers to be received/parsed
  19318. auto body = read_all(handle);
  19319. // Explicitly parse trailers (ensure trailers are available for assertion)
  19320. handle.parse_trailers_if_needed();
  19321. EXPECT_EQ(std::string("123456789"), body);
  19322. // The response should include a Trailer header declaring both names
  19323. ASSERT_TRUE(handle.response);
  19324. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19325. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19326. handle.response->get_header_value("Trailer"));
  19327. // Prohibited trailer must not be present
  19328. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19329. // Allowed trailer should be present
  19330. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19331. EXPECT_EQ(std::string("yes"),
  19332. handle.response->get_trailer_value("X-Allowed"));
  19333. // Verify trailers are NOT present as regular headers
  19334. EXPECT_EQ(std::string(""),
  19335. handle.response->get_header_value("Content-Length"));
  19336. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19337. }
  19338. // Accepts one connection on an OS-assigned port, which it hands over through
  19339. // port_promise, reads the request head and sends back response. after_send,
  19340. // if given, runs on the connection before it is closed.
  19341. static std::thread
  19342. serve_single_response(std::promise<int> &port_promise,
  19343. const std::string &response,
  19344. std::function<void(socket_t)> after_send = nullptr) {
  19345. return std::thread([&port_promise, response, after_send] {
  19346. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19347. default_socket_options(srv);
  19348. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19349. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19350. sockaddr_in addr{};
  19351. addr.sin_family = AF_INET;
  19352. addr.sin_port = htons(0); // Let OS assign a free port
  19353. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19354. int opt = 1;
  19355. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19356. #ifdef _WIN32
  19357. reinterpret_cast<const char *>(&opt),
  19358. #else
  19359. &opt,
  19360. #endif
  19361. sizeof(opt));
  19362. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19363. ::listen(srv, 1) != 0) {
  19364. port_promise.set_value(-1);
  19365. detail::close_socket(srv);
  19366. return;
  19367. }
  19368. socklen_t addr_len = sizeof(addr);
  19369. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19370. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19371. sockaddr_in cli_addr{};
  19372. socklen_t cli_len = sizeof(cli_addr);
  19373. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19374. if (cli != INVALID_SOCKET) {
  19375. // Read the complete HTTP request (until the blank line that terminates
  19376. // headers) before sending the response. If the server closes the socket
  19377. // while the client's request data is still unread in the kernel receive
  19378. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19379. // connection on both sides: it discards the client's receive buffer
  19380. // (which already holds our response) and causes any in-progress write on
  19381. // the client to fail with ECONNRESET. Reading all request data first
  19382. // ensures close() emits a graceful FIN.
  19383. {
  19384. char rbuf[256];
  19385. std::string req;
  19386. while (req.find("\r\n\r\n") == std::string::npos) {
  19387. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19388. if (n <= 0) { break; }
  19389. req.append(rbuf, static_cast<size_t>(n));
  19390. }
  19391. }
  19392. ::send(cli,
  19393. #ifdef _WIN32
  19394. static_cast<const char *>(response.c_str()),
  19395. static_cast<int>(response.size()),
  19396. #else
  19397. response.c_str(), response.size(),
  19398. #endif
  19399. 0);
  19400. if (after_send) { after_send(cli); }
  19401. detail::close_socket(cli);
  19402. }
  19403. detail::close_socket(srv);
  19404. });
  19405. }
  19406. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19407. #ifndef _WIN32
  19408. signal(SIGPIPE, SIG_IGN);
  19409. #endif
  19410. std::promise<int> port_promise;
  19411. auto port_future = port_promise.get_future();
  19412. auto server_thread =
  19413. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19414. "Content-Type: text/plain\r\n"
  19415. "Content-Length: not-a-number\r\n"
  19416. "Connection: close\r\n"
  19417. "\r\n"
  19418. "hello");
  19419. auto port = port_future.get();
  19420. ASSERT_GT(port, 0);
  19421. Client cli("127.0.0.1", port);
  19422. auto handle = cli.open_stream("GET", "/");
  19423. EXPECT_FALSE(handle.is_valid());
  19424. server_thread.join();
  19425. }
  19426. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19427. #ifndef _WIN32
  19428. signal(SIGPIPE, SIG_IGN);
  19429. #endif
  19430. std::promise<int> port_promise;
  19431. auto port_future = port_promise.get_future();
  19432. auto server_thread = serve_single_response(
  19433. port_promise, "HTTP/1.1 200 OK\r\n"
  19434. "Content-Type: text/plain\r\n"
  19435. "Content-Length: 99999999999999999999999999\r\n"
  19436. "Connection: close\r\n"
  19437. "\r\n"
  19438. "hello");
  19439. auto port = port_future.get();
  19440. ASSERT_GT(port, 0);
  19441. // Historically std::stoull would throw std::out_of_range here and crash
  19442. // the process, then parsing silently clamped to a bogus framing length and
  19443. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19444. // so the stream fails to open, matching the not-a-number case above. The
  19445. // process still must NOT terminate.
  19446. Client cli("127.0.0.1", port);
  19447. auto handle = cli.open_stream("GET", "/");
  19448. EXPECT_FALSE(handle.is_valid());
  19449. server_thread.join();
  19450. }
  19451. // Serves `response` to the single request `fn` makes with a fresh client.
  19452. template <typename Fn>
  19453. static void with_single_response(const std::string &response, Fn fn) {
  19454. #ifndef _WIN32
  19455. signal(SIGPIPE, SIG_IGN);
  19456. #endif
  19457. std::promise<int> port_promise;
  19458. auto port_future = port_promise.get_future();
  19459. auto server_thread = serve_single_response(port_promise, response);
  19460. auto se = detail::scope_exit([&] { server_thread.join(); });
  19461. auto port = port_future.get();
  19462. ASSERT_GT(port, 0);
  19463. Client cli("127.0.0.1", port);
  19464. fn(cli);
  19465. }
  19466. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19467. const char *responses[] = {
  19468. "HTTP/1.1 103 Early Hints\r\n"
  19469. "Link: </style.css>; rel=preload\r\n"
  19470. "\r\n"
  19471. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19472. "HTTP/1.1 100 Continue\r\n"
  19473. "X-Note: interim\r\n"
  19474. "\r\n"
  19475. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19476. };
  19477. for (auto response : responses) {
  19478. with_single_response(response, [](Client &cli) {
  19479. auto res = cli.Get("/");
  19480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19481. EXPECT_EQ(StatusCode::OK_200, res->status);
  19482. EXPECT_EQ("ok", res->body);
  19483. });
  19484. }
  19485. }
  19486. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19487. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19488. const std::string final_response =
  19489. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19490. std::string interims;
  19491. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19492. interims += interim;
  19493. }
  19494. with_single_response(interims + final_response, [](Client &cli) {
  19495. auto res = cli.Get("/");
  19496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19497. EXPECT_EQ("ok", res->body);
  19498. });
  19499. with_single_response(interims + interim + final_response, [](Client &cli) {
  19500. auto res = cli.Get("/");
  19501. ASSERT_FALSE(res);
  19502. EXPECT_EQ(Error::Read, res.error());
  19503. });
  19504. }
  19505. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19506. #ifndef _WIN32
  19507. signal(SIGPIPE, SIG_IGN);
  19508. #endif
  19509. // The server answers the head without asking for the body. Bytes it then
  19510. // reads on the connection would be taken for the body the request declared.
  19511. auto closed_by_client = false;
  19512. std::promise<int> port_promise;
  19513. auto server_thread = serve_single_response(
  19514. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19515. [&](socket_t sock) {
  19516. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19517. char buf[256];
  19518. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19519. });
  19520. Client cli("127.0.0.1", port_promise.get_future().get());
  19521. cli.set_keep_alive(true);
  19522. cli.set_read_timeout(1, 0);
  19523. // Long enough for the client to send Expect: 100-continue.
  19524. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19526. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19527. cli.Get("/second");
  19528. server_thread.join();
  19529. EXPECT_TRUE(closed_by_client);
  19530. }
  19531. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19532. // Long enough for the client to send Expect: 100-continue
  19533. with_single_response(
  19534. "HTTP/1.1 103 Early Hints\r\n"
  19535. "Link: </style.css>; rel=preload\r\n"
  19536. "\r\n"
  19537. "HTTP/1.1 401 Unauthorized\r\n"
  19538. "Content-Length: 0\r\n\r\n",
  19539. [](Client &cli) {
  19540. cli.set_read_timeout(2, 0);
  19541. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19543. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19544. });
  19545. }
  19546. #ifdef CPPHTTPLIB_SSL_ENABLED
  19547. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19548. #ifndef _WIN32
  19549. signal(SIGPIPE, SIG_IGN);
  19550. #endif
  19551. auto reused = false;
  19552. std::promise<int> port_promise;
  19553. auto server_thread = serve_single_response(
  19554. port_promise,
  19555. "HTTP/1.1 401 Unauthorized\r\n"
  19556. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19557. "Content-Length: 0\r\n\r\n",
  19558. [&](socket_t sock) {
  19559. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19560. char buf[256];
  19561. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19562. });
  19563. Client cli("127.0.0.1", port_promise.get_future().get());
  19564. cli.set_keep_alive(true);
  19565. cli.set_digest_auth("user", "pass");
  19566. cli.set_read_timeout(1, 0);
  19567. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19568. server_thread.join();
  19569. EXPECT_FALSE(reused);
  19570. }
  19571. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19572. // Any other answer to CONNECT would read as the origin's response.
  19573. struct {
  19574. const char *response;
  19575. bool passed_on;
  19576. } cases[] = {
  19577. {"HTTP/1.1 201 Created\r\n"
  19578. "Set-Cookie: session=from-proxy\r\n"
  19579. "Content-Length: 0\r\n\r\n",
  19580. false},
  19581. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19582. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19583. "Content-Length: 0\r\n\r\n",
  19584. true},
  19585. };
  19586. for (const auto &c : cases) {
  19587. std::promise<int> port_promise;
  19588. auto server_thread = serve_single_response(port_promise, c.response);
  19589. SSLClient cli("example.com", 443);
  19590. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19591. auto res = cli.Get("/");
  19592. server_thread.join();
  19593. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19594. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19595. if (res) {
  19596. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19597. }
  19598. }
  19599. }
  19600. #endif
  19601. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19602. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19603. // the chunked coding and drop Content-Length, so a front-end that trusts
  19604. // Content-Length would disagree about where the body ends (response
  19605. // smuggling). The client must reject such a response.
  19606. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19607. for (const char *te : {"chunked", "gzip, chunked"}) {
  19608. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19609. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19610. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19611. "5\r\nhello\r\n0\r\n\r\n";
  19612. with_single_response(response, [&](Client &cli) {
  19613. auto res = cli.Get("/");
  19614. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19615. EXPECT_EQ(Error::Read, res.error()) << te;
  19616. });
  19617. with_single_response(response, [&](Client &cli) {
  19618. auto handle = cli.open_stream("GET", "/");
  19619. EXPECT_FALSE(handle.is_valid()) << te;
  19620. EXPECT_EQ(Error::Read, handle.error) << te;
  19621. });
  19622. }
  19623. }
  19624. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19625. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19626. // closing the connection (unlike a request, which must be rejected).
  19627. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19628. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19629. "Transfer-Encoding: chunked\r\n"
  19630. "Connection: close\r\n"
  19631. "\r\n"
  19632. "5\r\nhello\r\n0\r\n\r\n",
  19633. "HTTP/1.1 200 OK\r\n"
  19634. "Transfer-Encoding: gzip\r\n"
  19635. "Connection: close\r\n"
  19636. "\r\n"
  19637. "hello"}) {
  19638. with_single_response(response, [&](Client &cli) {
  19639. auto res = cli.Get("/");
  19640. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19641. EXPECT_EQ("hello", res->body);
  19642. });
  19643. with_single_response(response, [&](Client &cli) {
  19644. auto handle = cli.open_stream("GET", "/");
  19645. ASSERT_TRUE(handle.is_valid()) << response;
  19646. EXPECT_EQ("hello", read_all(handle));
  19647. });
  19648. }
  19649. }
  19650. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19651. // framing headers describe nothing to read and must not be rejected.
  19652. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19653. const std::string framing = "Content-Length: 5\r\n"
  19654. "Transfer-Encoding: chunked\r\n"
  19655. "Connection: close\r\n"
  19656. "\r\n";
  19657. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19658. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19659. });
  19660. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19661. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19662. });
  19663. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19664. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19665. with_single_response(response, [&](Client &cli) {
  19666. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19667. });
  19668. with_single_response(response, [&](Client &cli) {
  19669. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19670. });
  19671. }
  19672. }
  19673. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19674. // response, is faulty framing, so the connection is not reused after it.
  19675. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19676. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19677. "Content-Length: 0\r\n"
  19678. "Transfer-Encoding: chunked\r\n"
  19679. "\r\n"
  19680. "5\r\nhello\r\n0\r\n\r\n",
  19681. "HTTP/1.0 200 Connection established\r\n"
  19682. "Connection: keep-alive\r\n"
  19683. "Transfer-Encoding: chunked\r\n"
  19684. "\r\n"
  19685. "5\r\nhello\r\n0\r\n\r\n"}) {
  19686. with_single_response(response, [&](Client &cli) {
  19687. cli.set_keep_alive(true);
  19688. auto res = cli.Get("/");
  19689. ASSERT_TRUE(res) << response;
  19690. EXPECT_EQ("hello", res->body);
  19691. EXPECT_FALSE(cli.is_socket_open()) << response;
  19692. });
  19693. }
  19694. }
  19695. // A payload max length of 0 means no limit, however the body is framed.
  19696. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19697. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19698. "Transfer-Encoding: chunked\r\n"
  19699. "\r\n"
  19700. "5\r\nhello\r\n0\r\n\r\n",
  19701. "HTTP/1.1 200 OK\r\n"
  19702. "Connection: close\r\n"
  19703. "\r\n"
  19704. "hello"}) {
  19705. with_single_response(response, [&](Client &cli) {
  19706. cli.set_payload_max_length(0);
  19707. auto res = cli.Get("/");
  19708. ASSERT_TRUE(res) << response;
  19709. EXPECT_EQ("hello", res->body) << response;
  19710. });
  19711. }
  19712. }
  19713. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19714. Server svr;
  19715. svr.set_payload_max_length(0);
  19716. svr.Post("/echo", [](const Request &req, Response &res) {
  19717. res.set_content(req.body, "text/plain");
  19718. });
  19719. auto port = svr.bind_to_any_port(HOST);
  19720. thread t = thread([&] { svr.listen_after_bind(); });
  19721. auto se = detail::scope_exit([&] {
  19722. svr.stop();
  19723. t.join();
  19724. ASSERT_FALSE(svr.is_running());
  19725. });
  19726. svr.wait_until_ready();
  19727. Client cli(HOST, port);
  19728. auto res = cli.Post(
  19729. "/echo",
  19730. [](size_t /*offset*/, DataSink &sink) {
  19731. sink.write("hello", 5);
  19732. sink.done();
  19733. return true;
  19734. },
  19735. "text/plain");
  19736. ASSERT_TRUE(res);
  19737. EXPECT_EQ(StatusCode::OK_200, res->status);
  19738. EXPECT_EQ("hello", res->body);
  19739. }
  19740. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19741. TEST_F(OpenStreamTest, Gzip) {
  19742. Client cli("127.0.0.1", port_);
  19743. auto handle = cli.open_stream("GET", "/compressible", {},
  19744. {{"Accept-Encoding", "gzip"}});
  19745. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19746. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19747. }
  19748. #endif
  19749. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19750. TEST_F(OpenStreamTest, Brotli) {
  19751. Client cli("127.0.0.1", port_);
  19752. auto handle =
  19753. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19754. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19755. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19756. }
  19757. #endif
  19758. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19759. TEST_F(OpenStreamTest, Zstd) {
  19760. Client cli("127.0.0.1", port_);
  19761. auto handle = cli.open_stream("GET", "/compressible", {},
  19762. {{"Accept-Encoding", "zstd"}});
  19763. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19764. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19765. }
  19766. #endif
  19767. #ifdef CPPHTTPLIB_SSL_ENABLED
  19768. class SSLOpenStreamTest : public ::testing::Test {
  19769. protected:
  19770. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19771. void SetUp() override {
  19772. svr_.Get("/hello", [](const Request &, Response &res) {
  19773. res.set_content("Hello SSL World!", "text/plain");
  19774. });
  19775. svr_.Get("/chunked", [](const Request &, Response &res) {
  19776. res.set_chunked_content_provider("text/plain",
  19777. [](size_t offset, DataSink &sink) {
  19778. if (offset < 15) {
  19779. sink.write("chunk", 5);
  19780. return true;
  19781. }
  19782. sink.done();
  19783. return true;
  19784. });
  19785. });
  19786. svr_.Post("/echo", [](const Request &req, Response &res) {
  19787. res.set_content(req.body, req.get_header_value("Content-Type"));
  19788. });
  19789. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19790. std::string body = req.body;
  19791. res.set_chunked_content_provider(
  19792. "text/plain", [body](size_t offset, DataSink &sink) {
  19793. if (offset < body.size()) {
  19794. sink.write(body.data() + offset, body.size() - offset);
  19795. }
  19796. sink.done();
  19797. return true;
  19798. });
  19799. });
  19800. port_ = svr_.bind_to_any_port("127.0.0.1");
  19801. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19802. svr_.wait_until_ready();
  19803. }
  19804. void TearDown() override {
  19805. svr_.stop();
  19806. if (thread_.joinable()) thread_.join();
  19807. }
  19808. SSLServer svr_;
  19809. std::thread thread_;
  19810. int port_ = 0;
  19811. };
  19812. TEST_F(SSLOpenStreamTest, Basic) {
  19813. SSLClient cli("127.0.0.1", port_);
  19814. cli.enable_server_certificate_verification(false);
  19815. auto handle = cli.open_stream("GET", "/hello");
  19816. ASSERT_TRUE(handle.is_valid());
  19817. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19818. }
  19819. TEST_F(SSLOpenStreamTest, Chunked) {
  19820. SSLClient cli("127.0.0.1", port_);
  19821. cli.enable_server_certificate_verification(false);
  19822. auto handle = cli.open_stream("GET", "/chunked");
  19823. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19824. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19825. "Transfer-Encoding") == "chunked");
  19826. auto body = read_all(handle);
  19827. EXPECT_EQ("chunkchunkchunk", body);
  19828. }
  19829. TEST_F(SSLOpenStreamTest, Post) {
  19830. SSLClient cli("127.0.0.1", port_);
  19831. cli.enable_server_certificate_verification(false);
  19832. auto handle =
  19833. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19834. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19835. EXPECT_EQ(200, handle.response->status);
  19836. auto body = read_all(handle);
  19837. EXPECT_EQ("Hello SSL POST", body);
  19838. }
  19839. TEST_F(SSLOpenStreamTest, PostChunked) {
  19840. SSLClient cli("127.0.0.1", port_);
  19841. cli.enable_server_certificate_verification(false);
  19842. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19843. "Chunked SSL Data", "text/plain");
  19844. ASSERT_TRUE(handle.is_valid());
  19845. EXPECT_EQ(200, handle.response->status);
  19846. auto body = read_all(handle);
  19847. EXPECT_EQ("Chunked SSL Data", body);
  19848. }
  19849. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19850. // Content-Length is terminated by the server closing the connection. When the
  19851. // SSL peer sends a close_notify after the body, the client must treat it as a
  19852. // clean EOF and return a successful response rather than an error.
  19853. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19854. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19855. ASSERT_TRUE(svr.is_valid());
  19856. svr.set_keep_alive_max_count(1);
  19857. const std::string expected_body = "Hello from connection-close response!";
  19858. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19859. res.set_content_provider("text/plain",
  19860. [&](size_t offset, DataSink &sink) -> bool {
  19861. if (offset < expected_body.size()) {
  19862. sink.write(expected_body.data() + offset,
  19863. expected_body.size() - offset);
  19864. }
  19865. sink.done();
  19866. return true;
  19867. });
  19868. });
  19869. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19870. auto se = detail::scope_exit([&] {
  19871. svr.stop();
  19872. listen_thread.join();
  19873. ASSERT_FALSE(svr.is_running());
  19874. });
  19875. svr.wait_until_ready();
  19876. SSLClient cli(HOST, PORT);
  19877. cli.enable_server_certificate_verification(false);
  19878. auto res = cli.Get("/no-content-length");
  19879. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19880. EXPECT_EQ(StatusCode::OK_200, res->status);
  19881. EXPECT_EQ(expected_body, res->body);
  19882. }
  19883. #endif // CPPHTTPLIB_SSL_ENABLED
  19884. //==============================================================================
  19885. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19886. // results for various scenarios.
  19887. //==============================================================================
  19888. TEST(ParityTest, GetVsOpenStream) {
  19889. Server svr;
  19890. const std::string path = "/parity";
  19891. const std::string content = "Parity test content: hello world";
  19892. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19893. res.set_content(content, "text/plain");
  19894. });
  19895. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19896. auto se = detail::scope_exit([&] {
  19897. svr.stop();
  19898. t.join();
  19899. ASSERT_FALSE(svr.is_running());
  19900. });
  19901. svr.wait_until_ready();
  19902. Client cli(HOST, PORT);
  19903. // Non-stream path
  19904. auto r1 = cli.Get(path);
  19905. ASSERT_TRUE(r1);
  19906. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19907. // Stream path
  19908. auto h = cli.open_stream("GET", path);
  19909. ASSERT_TRUE(h.is_valid());
  19910. EXPECT_EQ(r1->body, read_all(h));
  19911. }
  19912. // Helper to compress data with provided compressor type T
  19913. template <typename Compressor>
  19914. static std::string compress_payload_for_parity(const std::string &in) {
  19915. std::string out;
  19916. Compressor compressor;
  19917. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19918. [&](const char *data, size_t n) {
  19919. out.append(data, n);
  19920. return true;
  19921. });
  19922. EXPECT_TRUE(ok);
  19923. return out;
  19924. }
  19925. // Helper function for compression parity tests
  19926. template <typename Compressor>
  19927. static void test_compression_parity(const std::string &original,
  19928. const std::string &path,
  19929. const std::string &encoding) {
  19930. const std::string compressed =
  19931. compress_payload_for_parity<Compressor>(original);
  19932. Server svr;
  19933. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19934. res.set_content(compressed, "application/octet-stream");
  19935. res.set_header("Content-Encoding", encoding);
  19936. });
  19937. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19938. auto se = detail::scope_exit([&] {
  19939. svr.stop();
  19940. t.join();
  19941. ASSERT_FALSE(svr.is_running());
  19942. });
  19943. svr.wait_until_ready();
  19944. Client cli(HOST, PORT);
  19945. // Non-streaming
  19946. {
  19947. auto res = cli.Get(path);
  19948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19949. EXPECT_EQ(StatusCode::OK_200, res->status);
  19950. EXPECT_EQ(original, res->body);
  19951. }
  19952. // Streaming
  19953. {
  19954. auto h = cli.open_stream("GET", path);
  19955. ASSERT_TRUE(h.is_valid());
  19956. EXPECT_EQ(original, read_all(h));
  19957. }
  19958. }
  19959. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19960. TEST(ParityTest, Gzip) {
  19961. test_compression_parity<detail::gzip_compressor>(
  19962. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19963. }
  19964. #endif
  19965. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19966. TEST(ParityTest, Brotli) {
  19967. test_compression_parity<detail::brotli_compressor>(
  19968. "Hello, brotli parity test payload", "/parity-br", "br");
  19969. }
  19970. #endif
  19971. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19972. TEST(ParityTest, Zstd) {
  19973. test_compression_parity<detail::zstd_compressor>(
  19974. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19975. }
  19976. #endif
  19977. //==============================================================================
  19978. // New Stream API Tests
  19979. //==============================================================================
  19980. inline std::string read_body(httplib::stream::Result &result) {
  19981. std::string body;
  19982. while (result.next()) {
  19983. body.append(result.data(), result.size());
  19984. }
  19985. return body;
  19986. }
  19987. TEST(ClientConnectionTest, Basic) {
  19988. httplib::ClientConnection conn;
  19989. EXPECT_FALSE(conn.is_open());
  19990. conn.sock = 1;
  19991. EXPECT_TRUE(conn.is_open());
  19992. httplib::ClientConnection conn2(std::move(conn));
  19993. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19994. conn2.sock = INVALID_SOCKET;
  19995. }
  19996. // Unified test server for all stream::* tests
  19997. class StreamApiTest : public ::testing::Test {
  19998. protected:
  19999. void SetUp() override {
  20000. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20001. res.set_content("Hello World!", "text/plain");
  20002. });
  20003. svr_.Get("/echo-params",
  20004. [](const httplib::Request &req, httplib::Response &res) {
  20005. std::string r;
  20006. for (const auto &p : req.params) {
  20007. if (!r.empty()) r += "&";
  20008. r += p.first + "=" + p.second;
  20009. }
  20010. res.set_content(r, "text/plain");
  20011. });
  20012. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20013. res.set_content(req.body, req.get_header_value("Content-Type"));
  20014. });
  20015. svr_.Post("/echo-headers",
  20016. [](const httplib::Request &req, httplib::Response &res) {
  20017. std::string r;
  20018. for (const auto &h : req.headers)
  20019. r += h.first + ": " + h.second + "\n";
  20020. res.set_content(r, "text/plain");
  20021. });
  20022. svr_.Post("/echo-params",
  20023. [](const httplib::Request &req, httplib::Response &res) {
  20024. std::string r = "params:";
  20025. for (const auto &p : req.params)
  20026. r += p.first + "=" + p.second + ";";
  20027. res.set_content(r + " body:" + req.body, "text/plain");
  20028. });
  20029. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20030. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20031. });
  20032. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20033. res.set_content("PUT:" + req.body, "text/plain");
  20034. });
  20035. svr_.Patch("/echo",
  20036. [](const httplib::Request &req, httplib::Response &res) {
  20037. res.set_content("PATCH:" + req.body, "text/plain");
  20038. });
  20039. svr_.Delete(
  20040. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20041. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20042. "text/plain");
  20043. });
  20044. svr_.Get("/head-test",
  20045. [](const httplib::Request &, httplib::Response &res) {
  20046. res.set_content("body for HEAD", "text/plain");
  20047. });
  20048. svr_.Options("/options",
  20049. [](const httplib::Request &, httplib::Response &res) {
  20050. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20051. });
  20052. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20053. svr_.wait_until_ready();
  20054. }
  20055. void TearDown() override {
  20056. svr_.stop();
  20057. if (thread_.joinable()) thread_.join();
  20058. }
  20059. httplib::Server svr_;
  20060. std::thread thread_;
  20061. };
  20062. // stream::Get tests
  20063. TEST_F(StreamApiTest, GetBasic) {
  20064. httplib::Client cli(HOST, PORT);
  20065. auto result = httplib::stream::Get(cli, "/hello");
  20066. ASSERT_TRUE(result.is_valid());
  20067. EXPECT_EQ(200, result.status());
  20068. EXPECT_EQ("Hello World!", read_body(result));
  20069. }
  20070. TEST_F(StreamApiTest, GetWithParams) {
  20071. httplib::Client cli(HOST, PORT);
  20072. httplib::Params params{{"foo", "bar"}};
  20073. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20074. ASSERT_TRUE(result.is_valid());
  20075. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20076. }
  20077. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20078. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20079. httplib::Client cli(HOST, PORT);
  20080. cli.set_payload_max_length(0);
  20081. auto result = httplib::stream::Get(cli, "/hello");
  20082. ASSERT_TRUE(result.is_valid());
  20083. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20084. EXPECT_EQ("Hello World!", read_body(result));
  20085. }
  20086. #endif
  20087. TEST_F(StreamApiTest, GetConnectionError) {
  20088. httplib::Client cli(HOST, 9999);
  20089. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20090. }
  20091. TEST_F(StreamApiTest, Get404) {
  20092. httplib::Client cli(HOST, PORT);
  20093. auto result = httplib::stream::Get(cli, "/nonexistent");
  20094. EXPECT_TRUE(result.is_valid());
  20095. EXPECT_EQ(404, result.status());
  20096. }
  20097. // stream::Post tests
  20098. TEST_F(StreamApiTest, PostBasic) {
  20099. httplib::Client cli(HOST, PORT);
  20100. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20101. "application/json");
  20102. ASSERT_TRUE(result.is_valid());
  20103. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20104. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20105. }
  20106. TEST_F(StreamApiTest, PostWithHeaders) {
  20107. httplib::Client cli(HOST, PORT);
  20108. httplib::Headers headers{{"X-Custom", "value"}};
  20109. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20110. "text/plain");
  20111. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20112. }
  20113. TEST_F(StreamApiTest, PostWithParams) {
  20114. httplib::Client cli(HOST, PORT);
  20115. httplib::Params params{{"k", "v"}};
  20116. auto result =
  20117. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20118. auto body = read_body(result);
  20119. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20120. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20121. }
  20122. TEST_F(StreamApiTest, PostLarge) {
  20123. httplib::Client cli(HOST, PORT);
  20124. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20125. size_t total = 0;
  20126. while (result.next()) {
  20127. total += result.size();
  20128. }
  20129. EXPECT_EQ(100u * 1024u, total);
  20130. }
  20131. // stream::Put/Patch tests
  20132. TEST_F(StreamApiTest, PutAndPatch) {
  20133. httplib::Client cli(HOST, PORT);
  20134. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20135. EXPECT_EQ("PUT:test", read_body(put));
  20136. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20137. EXPECT_EQ("PATCH:test", read_body(patch));
  20138. }
  20139. // stream::Delete tests
  20140. TEST_F(StreamApiTest, Delete) {
  20141. httplib::Client cli(HOST, PORT);
  20142. auto del1 = httplib::stream::Delete(cli, "/resource");
  20143. EXPECT_EQ("Deleted", read_body(del1));
  20144. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20145. EXPECT_EQ("Deleted:data", read_body(del2));
  20146. }
  20147. // stream::Head/Options tests
  20148. TEST_F(StreamApiTest, HeadAndOptions) {
  20149. httplib::Client cli(HOST, PORT);
  20150. auto head = httplib::stream::Head(cli, "/head-test");
  20151. EXPECT_TRUE(head.is_valid());
  20152. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20153. auto opts = httplib::stream::Options(cli, "/options");
  20154. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20155. }
  20156. // SSL stream::* tests
  20157. #ifdef CPPHTTPLIB_SSL_ENABLED
  20158. class SSLStreamApiTest : public ::testing::Test {
  20159. protected:
  20160. void SetUp() override {
  20161. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20162. res.set_content("Hello SSL!", "text/plain");
  20163. });
  20164. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20165. res.set_content(req.body, "text/plain");
  20166. });
  20167. port_ = svr_.bind_to_any_port("127.0.0.1");
  20168. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20169. svr_.wait_until_ready();
  20170. }
  20171. void TearDown() override {
  20172. svr_.stop();
  20173. if (thread_.joinable()) thread_.join();
  20174. }
  20175. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20176. std::thread thread_;
  20177. int port_ = 0;
  20178. };
  20179. TEST_F(SSLStreamApiTest, GetAndPost) {
  20180. httplib::SSLClient cli("127.0.0.1", port_);
  20181. cli.enable_server_certificate_verification(false);
  20182. auto get = httplib::stream::Get(cli, "/hello");
  20183. EXPECT_EQ("Hello SSL!", read_body(get));
  20184. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20185. EXPECT_EQ("test", read_body(post));
  20186. }
  20187. #endif
  20188. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20189. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20190. // BodyReader
  20191. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20192. // Test that read timeout during streaming is detected
  20193. // Use a large content-length response where server delays mid-stream
  20194. Server svr;
  20195. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20196. // Send a large response with delay in the middle
  20197. res.set_content_provider(
  20198. 1000, // content_length
  20199. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20200. if (offset < 100) {
  20201. // Send first 100 bytes immediately
  20202. std::string data(100, 'A');
  20203. sink.write(data.c_str(), data.size());
  20204. return true;
  20205. }
  20206. // Then delay longer than client timeout
  20207. std::this_thread::sleep_for(std::chrono::seconds(3));
  20208. std::string data(900, 'B');
  20209. sink.write(data.c_str(), data.size());
  20210. return true;
  20211. });
  20212. });
  20213. auto port = 8091;
  20214. std::thread t([&]() { svr.listen("localhost", port); });
  20215. svr.wait_until_ready();
  20216. Client cli("localhost", port);
  20217. cli.set_read_timeout(1, 0); // 1 second timeout
  20218. auto handle = cli.open_stream("GET", "/slow-stream");
  20219. ASSERT_TRUE(handle.is_valid());
  20220. char buf[256];
  20221. ssize_t total = 0;
  20222. ssize_t n;
  20223. bool got_error = false;
  20224. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20225. total += n;
  20226. }
  20227. if (n < 0) {
  20228. got_error = true;
  20229. // Should be timeout or read error
  20230. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20231. handle.get_read_error() == Error::Read)
  20232. << "Actual error: " << to_string(handle.get_read_error());
  20233. }
  20234. // Either we got an error, or we got less data than expected
  20235. EXPECT_TRUE(got_error || total < 1000)
  20236. << "Expected timeout but got all " << total << " bytes";
  20237. svr.stop();
  20238. t.join();
  20239. }
  20240. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20241. // Test connection closed detection via BodyReader
  20242. Server svr;
  20243. std::atomic<bool> close_now{false};
  20244. svr.Get("/will-close", [&](const Request &, Response &res) {
  20245. res.set_content_provider(
  20246. 10000, // Large content_length that we won't fully send
  20247. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20248. if (offset < 100) {
  20249. std::string data(100, 'X');
  20250. sink.write(data.c_str(), data.size());
  20251. return true;
  20252. }
  20253. // Wait for signal then abort
  20254. while (!close_now) {
  20255. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20256. }
  20257. return false; // Abort - server will close connection
  20258. });
  20259. });
  20260. auto port = 8092;
  20261. std::thread t([&]() { svr.listen("localhost", port); });
  20262. svr.wait_until_ready();
  20263. Client cli("localhost", port);
  20264. auto handle = cli.open_stream("GET", "/will-close");
  20265. ASSERT_TRUE(handle.is_valid());
  20266. char buf[256];
  20267. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20268. EXPECT_GT(n, 0) << "First read should succeed";
  20269. // Signal server to close
  20270. close_now = true;
  20271. // Keep reading until error or EOF
  20272. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20273. // Keep reading
  20274. }
  20275. // Should get an error since content_length wasn't satisfied
  20276. if (n < 0) {
  20277. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20278. handle.get_read_error() == Error::Read)
  20279. << "Actual error: " << to_string(handle.get_read_error());
  20280. }
  20281. svr.stop();
  20282. t.join();
  20283. }
  20284. #ifdef CPPHTTPLIB_SSL_ENABLED
  20285. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20286. // Test that read timeout during SSL streaming is detected
  20287. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20288. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20289. res.set_content_provider(
  20290. 1000, "text/plain",
  20291. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20292. if (offset < 100) {
  20293. std::string data(100, 'A');
  20294. sink.write(data.c_str(), data.size());
  20295. return true;
  20296. }
  20297. std::this_thread::sleep_for(std::chrono::seconds(3));
  20298. std::string data(900, 'B');
  20299. sink.write(data.c_str(), data.size());
  20300. return true;
  20301. });
  20302. });
  20303. auto port = 8093;
  20304. std::thread t([&]() { svr.listen("localhost", port); });
  20305. svr.wait_until_ready();
  20306. SSLClient cli("localhost", port);
  20307. cli.enable_server_certificate_verification(false);
  20308. cli.set_read_timeout(1, 0); // 1 second timeout
  20309. auto handle = cli.open_stream("GET", "/slow-stream");
  20310. ASSERT_TRUE(handle.is_valid());
  20311. char buf[256];
  20312. ssize_t total = 0;
  20313. ssize_t n;
  20314. bool got_error = false;
  20315. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20316. total += n;
  20317. }
  20318. if (n < 0) {
  20319. got_error = true;
  20320. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20321. handle.get_read_error() == Error::Read)
  20322. << "Actual error: " << to_string(handle.get_read_error());
  20323. }
  20324. EXPECT_TRUE(got_error || total < 1000)
  20325. << "Expected timeout but got all " << total << " bytes";
  20326. svr.stop();
  20327. t.join();
  20328. }
  20329. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20330. // Test SSL connection closed detection
  20331. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20332. std::atomic<bool> close_now{false};
  20333. svr.Get("/will-close", [&](const Request &, Response &res) {
  20334. res.set_content_provider(
  20335. 10000, "text/plain",
  20336. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20337. if (offset < 100) {
  20338. std::string data(100, 'X');
  20339. sink.write(data.c_str(), data.size());
  20340. return true;
  20341. }
  20342. while (!close_now) {
  20343. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20344. }
  20345. return false;
  20346. });
  20347. });
  20348. auto port = 8094;
  20349. std::thread t([&]() { svr.listen("localhost", port); });
  20350. svr.wait_until_ready();
  20351. SSLClient cli("localhost", port);
  20352. cli.enable_server_certificate_verification(false);
  20353. auto handle = cli.open_stream("GET", "/will-close");
  20354. ASSERT_TRUE(handle.is_valid());
  20355. char buf[256];
  20356. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20357. EXPECT_GT(n, 0);
  20358. // Signal server to close
  20359. close_now = true;
  20360. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20361. // Keep reading
  20362. }
  20363. if (n < 0) {
  20364. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20365. handle.get_read_error() == Error::Read)
  20366. << "Actual error: " << to_string(handle.get_read_error());
  20367. }
  20368. svr.stop();
  20369. t.join();
  20370. }
  20371. #endif
  20372. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20373. using namespace httplib;
  20374. // Create a test file
  20375. const char *fname = "etag_testfile.txt";
  20376. const char *content = "etag-content";
  20377. {
  20378. std::ofstream ofs(fname);
  20379. ofs << content;
  20380. ASSERT_TRUE(ofs.good());
  20381. }
  20382. Server svr;
  20383. svr.set_mount_point("/static", ".");
  20384. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20385. svr.wait_until_ready();
  20386. Client cli(HOST, PORT);
  20387. // First request: should get 200 with ETag header
  20388. auto res1 = cli.Get("/static/etag_testfile.txt");
  20389. ASSERT_TRUE(res1);
  20390. ASSERT_EQ(200, res1->status);
  20391. ASSERT_TRUE(res1->has_header("ETag"));
  20392. std::string etag = res1->get_header_value("ETag");
  20393. EXPECT_FALSE(etag.empty());
  20394. // Verify ETag format: W/"hex-hex"
  20395. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20396. EXPECT_EQ('W', etag[0]);
  20397. EXPECT_EQ('/', etag[1]);
  20398. EXPECT_EQ('"', etag[2]);
  20399. EXPECT_EQ('"', etag.back());
  20400. // Exact match: expect 304 Not Modified
  20401. Headers h2 = {{"If-None-Match", etag}};
  20402. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20403. ASSERT_TRUE(res2);
  20404. EXPECT_EQ(304, res2->status);
  20405. // Wildcard match: expect 304 Not Modified
  20406. Headers h3 = {{"If-None-Match", "*"}};
  20407. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20408. ASSERT_TRUE(res3);
  20409. EXPECT_EQ(304, res3->status);
  20410. // Non-matching ETag: expect 200
  20411. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20412. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20413. ASSERT_TRUE(res4);
  20414. EXPECT_EQ(200, res4->status);
  20415. // Multiple ETags with one matching: expect 304
  20416. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20417. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20418. ASSERT_TRUE(res5);
  20419. EXPECT_EQ(304, res5->status);
  20420. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20421. // that equivalent to the single comma-separated list above, so the match on
  20422. // the second line must still be found.
  20423. Headers h6;
  20424. h6.emplace("If-None-Match", "W/\"other\"");
  20425. h6.emplace("If-None-Match", etag);
  20426. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20427. ASSERT_TRUE(res6);
  20428. EXPECT_EQ(304, res6->status);
  20429. svr.stop();
  20430. t.join();
  20431. std::remove(fname);
  20432. }
  20433. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20434. using namespace httplib;
  20435. Server svr;
  20436. svr.set_mount_point("/static", ".");
  20437. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20438. svr.wait_until_ready();
  20439. Client cli(HOST, PORT);
  20440. // Send If-None-Match: * to a non-existent file
  20441. Headers h = {{"If-None-Match", "*"}};
  20442. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20444. EXPECT_EQ(404, res->status);
  20445. svr.stop();
  20446. t.join();
  20447. }
  20448. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20449. using namespace httplib;
  20450. // Create a test file
  20451. const char *fname = "etag_boundary_testfile.txt";
  20452. const char *content = "boundary-test";
  20453. {
  20454. std::ofstream ofs(fname);
  20455. ofs << content;
  20456. ASSERT_TRUE(ofs.good());
  20457. }
  20458. Server svr;
  20459. svr.set_mount_point("/static", ".");
  20460. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20461. svr.wait_until_ready();
  20462. Client cli(HOST, PORT);
  20463. // Get the actual ETag
  20464. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20465. ASSERT_TRUE(res1);
  20466. ASSERT_EQ(200, res1->status);
  20467. ASSERT_TRUE(res1->has_header("ETag"));
  20468. std::string etag = res1->get_header_value("ETag");
  20469. // Test 1: Very long ETag value (longer than actual ETag)
  20470. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20471. Headers h1 = {{"If-None-Match", "W/"
  20472. "\"very-long-etag-value-that-is-much-longer-"
  20473. "than-the-actual-etag-value\""}};
  20474. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20475. ASSERT_TRUE(res2);
  20476. EXPECT_EQ(200, res2->status); // Should not match
  20477. // Test 2: Long string followed by wildcard
  20478. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20479. // string)
  20480. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20481. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20482. ASSERT_TRUE(res3);
  20483. EXPECT_EQ(304, res3->status); // Should match on "*"
  20484. // Test 3: Wildcard followed by long string
  20485. // Should match on "*" immediately and return 304
  20486. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20487. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20488. ASSERT_TRUE(res4);
  20489. EXPECT_EQ(304, res4->status); // Should match on "*"
  20490. // Test 4: Multiple long non-matching values
  20491. // Should NOT match and return 200 (test that all comparisons are safe)
  20492. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20493. "W/\"second-long-non-matching-value\", "
  20494. "W/\"third-long-non-matching-value\""}};
  20495. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20496. ASSERT_TRUE(res5);
  20497. EXPECT_EQ(200, res5->status); // Should not match
  20498. // Test 5: Single character that is not "*" (edge case)
  20499. Headers h5 = {{"If-None-Match", "X"}};
  20500. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20501. ASSERT_TRUE(res6);
  20502. EXPECT_EQ(200, res6->status); // Should not match
  20503. svr.stop();
  20504. t.join();
  20505. std::remove(fname);
  20506. }
  20507. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20508. using namespace httplib;
  20509. // Create a test file
  20510. const char *fname = "ims_testfile.txt";
  20511. const char *content = "if-modified-since-test";
  20512. {
  20513. std::ofstream ofs(fname);
  20514. ofs << content;
  20515. ASSERT_TRUE(ofs.good());
  20516. }
  20517. Server svr;
  20518. svr.set_mount_point("/static", ".");
  20519. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20520. svr.wait_until_ready();
  20521. Client cli(HOST, PORT);
  20522. // First request: should get 200 with Last-Modified header
  20523. auto res1 = cli.Get("/static/ims_testfile.txt");
  20524. ASSERT_TRUE(res1);
  20525. ASSERT_EQ(200, res1->status);
  20526. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20527. std::string last_modified = res1->get_header_value("Last-Modified");
  20528. EXPECT_FALSE(last_modified.empty());
  20529. // If-Modified-Since with same time: expect 304
  20530. Headers h2 = {{"If-Modified-Since", last_modified}};
  20531. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20532. ASSERT_TRUE(res2);
  20533. EXPECT_EQ(304, res2->status);
  20534. // If-Modified-Since with future time: expect 304
  20535. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20536. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20537. ASSERT_TRUE(res3);
  20538. EXPECT_EQ(304, res3->status);
  20539. // If-Modified-Since with past time: expect 200
  20540. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20541. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20542. ASSERT_TRUE(res4);
  20543. EXPECT_EQ(200, res4->status);
  20544. // If-None-Match takes precedence over If-Modified-Since
  20545. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20546. ASSERT_TRUE(res1->has_header("ETag"));
  20547. std::string etag = res1->get_header_value("ETag");
  20548. Headers h5 = {{"If-None-Match", etag},
  20549. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20550. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20551. ASSERT_TRUE(res5);
  20552. EXPECT_EQ(304, res5->status);
  20553. svr.stop();
  20554. t.join();
  20555. std::remove(fname);
  20556. }
  20557. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20558. using namespace httplib;
  20559. Server svr;
  20560. // Endpoint that returns compressible content
  20561. svr.Get("/compressible", [](const Request &, Response &res) {
  20562. // Return a large enough body to trigger compression
  20563. std::string body(1000, 'a');
  20564. res.set_content(body, "text/plain");
  20565. });
  20566. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20567. svr.wait_until_ready();
  20568. Client cli(HOST, PORT);
  20569. // Request with gzip support: should get Vary header when compressed
  20570. cli.set_compress(true);
  20571. auto res1 = cli.Get("/compressible");
  20572. ASSERT_TRUE(res1);
  20573. EXPECT_EQ(200, res1->status);
  20574. // If Content-Encoding is set, Vary should also be set
  20575. if (res1->has_header("Content-Encoding")) {
  20576. EXPECT_TRUE(res1->has_header("Vary"));
  20577. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20578. }
  20579. // Request without Accept-Encoding header: should not have compression
  20580. Headers h_no_compress;
  20581. auto res2 = cli.Get("/compressible", h_no_compress);
  20582. ASSERT_TRUE(res2);
  20583. EXPECT_EQ(200, res2->status);
  20584. // Verify Vary header is present when compression is applied
  20585. // (the exact behavior depends on server configuration)
  20586. svr.stop();
  20587. t.join();
  20588. }
  20589. TEST(ETagTest, IfRangeWithETag) {
  20590. using namespace httplib;
  20591. // Create a test file with known content
  20592. const char *fname = "if_range_testfile.txt";
  20593. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20594. {
  20595. std::ofstream ofs(fname);
  20596. ofs << content;
  20597. ASSERT_TRUE(ofs.good());
  20598. }
  20599. Server svr;
  20600. svr.set_mount_point("/static", ".");
  20601. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20602. svr.wait_until_ready();
  20603. Client cli(HOST, PORT);
  20604. // First request: get ETag
  20605. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20606. ASSERT_TRUE(res1);
  20607. ASSERT_EQ(200, res1->status);
  20608. ASSERT_TRUE(res1->has_header("ETag"));
  20609. std::string etag = res1->get_header_value("ETag");
  20610. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20611. // Since our server generates weak ETags (W/"..."), If-Range with our
  20612. // ETag should NOT result in partial content - it should return full content.
  20613. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20614. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20615. ASSERT_TRUE(res2);
  20616. // Weak ETag in If-Range -> full content (200), not partial (206)
  20617. EXPECT_EQ(200, res2->status);
  20618. EXPECT_EQ(content, res2->body);
  20619. EXPECT_FALSE(res2->has_header("Content-Range"));
  20620. // Range request with non-matching If-Range (ETag): should get 200 (full
  20621. // content)
  20622. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20623. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20624. ASSERT_TRUE(res3);
  20625. EXPECT_EQ(200, res3->status);
  20626. EXPECT_EQ(content, res3->body);
  20627. EXPECT_FALSE(res3->has_header("Content-Range"));
  20628. // Range request with strong ETag (hypothetical - our server doesn't generate
  20629. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20630. // should return full content)
  20631. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20632. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20633. ASSERT_TRUE(res4);
  20634. EXPECT_EQ(200, res4->status);
  20635. EXPECT_EQ(content, res4->body);
  20636. EXPECT_FALSE(res4->has_header("Content-Range"));
  20637. svr.stop();
  20638. t.join();
  20639. std::remove(fname);
  20640. }
  20641. TEST(ETagTest, IfRangeWithDate) {
  20642. using namespace httplib;
  20643. // Create a test file
  20644. const char *fname = "if_range_date_testfile.txt";
  20645. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20646. {
  20647. std::ofstream ofs(fname);
  20648. ofs << content;
  20649. ASSERT_TRUE(ofs.good());
  20650. }
  20651. Server svr;
  20652. svr.set_mount_point("/static", ".");
  20653. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20654. svr.wait_until_ready();
  20655. Client cli(HOST, PORT);
  20656. // First request: get Last-Modified
  20657. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20658. ASSERT_TRUE(res1);
  20659. ASSERT_EQ(200, res1->status);
  20660. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20661. std::string last_modified = res1->get_header_value("Last-Modified");
  20662. // Range request with matching If-Range (date): should get 206
  20663. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20664. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20665. ASSERT_TRUE(res2);
  20666. EXPECT_EQ(206, res2->status);
  20667. EXPECT_EQ("FGHIJ", res2->body);
  20668. // Range request with old If-Range date: should get 200 (full content)
  20669. Headers h3 = {{"Range", "bytes=5-9"},
  20670. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20671. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20672. ASSERT_TRUE(res3);
  20673. EXPECT_EQ(200, res3->status);
  20674. EXPECT_EQ(content, res3->body);
  20675. // Range request with future If-Range date: should get 206
  20676. Headers h4 = {{"Range", "bytes=0-4"},
  20677. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20678. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20679. ASSERT_TRUE(res4);
  20680. EXPECT_EQ(206, res4->status);
  20681. EXPECT_EQ("ABCDE", res4->body);
  20682. svr.stop();
  20683. t.join();
  20684. std::remove(fname);
  20685. }
  20686. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20687. using namespace httplib;
  20688. const char *fname = "etag_malformed.txt";
  20689. const char *content = "malformed-etag";
  20690. {
  20691. std::ofstream ofs(fname);
  20692. ofs << content;
  20693. ASSERT_TRUE(ofs.good());
  20694. }
  20695. Server svr;
  20696. svr.set_mount_point("/static", ".");
  20697. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20698. svr.wait_until_ready();
  20699. Client cli(HOST, PORT);
  20700. // baseline: should get 200 and an ETag
  20701. auto res1 = cli.Get("/static/etag_malformed.txt");
  20702. ASSERT_TRUE(res1);
  20703. ASSERT_EQ(200, res1->status);
  20704. ASSERT_TRUE(res1->has_header("ETag"));
  20705. // Malformed ETag value (missing quotes) should be treated as non-matching
  20706. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20707. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20708. ASSERT_TRUE(res_bad);
  20709. EXPECT_EQ(200, res_bad->status);
  20710. // Whitespace-only header value should be considered invalid / non-matching
  20711. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20712. "Host: localhost\r\n"
  20713. "If-None-Match: \r\n"
  20714. "Connection: close\r\n"
  20715. "\r\n";
  20716. std::string out;
  20717. ASSERT_TRUE(send_request(5, raw_req, &out));
  20718. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20719. svr.stop();
  20720. t.join();
  20721. std::remove(fname);
  20722. }
  20723. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20724. using namespace httplib;
  20725. const char *fname = "ims_invalid_format.txt";
  20726. const char *content = "ims-bad-format";
  20727. {
  20728. std::ofstream ofs(fname);
  20729. ofs << content;
  20730. ASSERT_TRUE(ofs.good());
  20731. }
  20732. Server svr;
  20733. svr.set_mount_point("/static", ".");
  20734. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20735. svr.wait_until_ready();
  20736. Client cli(HOST, PORT);
  20737. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20738. ASSERT_TRUE(res1);
  20739. ASSERT_EQ(200, res1->status);
  20740. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20741. // If-Modified-Since with invalid format should not result in 304
  20742. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20743. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20744. ASSERT_TRUE(res_bad);
  20745. EXPECT_EQ(200, res_bad->status);
  20746. // If-Range with invalid date format should be treated as mismatch -> full
  20747. // content (200)
  20748. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20749. {"If-Range", "invalid-date"}};
  20750. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20751. ASSERT_TRUE(res_ifrange);
  20752. EXPECT_EQ(200, res_ifrange->status);
  20753. svr.stop();
  20754. t.join();
  20755. std::remove(fname);
  20756. }
  20757. TEST(ETagTest, IfRangeWithMalformedETag) {
  20758. using namespace httplib;
  20759. const char *fname = "ifrange_malformed.txt";
  20760. const std::string content = "0123456789";
  20761. {
  20762. std::ofstream ofs(fname);
  20763. ofs << content;
  20764. ASSERT_TRUE(ofs.good());
  20765. }
  20766. Server svr;
  20767. svr.set_mount_point("/static", ".");
  20768. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20769. svr.wait_until_ready();
  20770. Client cli(HOST, PORT);
  20771. // First request: get ETag
  20772. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20773. ASSERT_TRUE(res1);
  20774. ASSERT_EQ(200, res1->status);
  20775. ASSERT_TRUE(res1->has_header("ETag"));
  20776. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20777. // full content (200)
  20778. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20779. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20780. ASSERT_TRUE(res2);
  20781. EXPECT_EQ(200, res2->status);
  20782. EXPECT_EQ(content, res2->body);
  20783. svr.stop();
  20784. t.join();
  20785. std::remove(fname);
  20786. }
  20787. TEST(ETagTest, ExtremeLargeDateValues) {
  20788. using namespace httplib;
  20789. const char *fname = "ims_extreme_date.txt";
  20790. const char *content = "ims-extreme-date";
  20791. {
  20792. std::ofstream ofs(fname);
  20793. ofs << content;
  20794. ASSERT_TRUE(ofs.good());
  20795. }
  20796. Server svr;
  20797. svr.set_mount_point("/static", ".");
  20798. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20799. svr.wait_until_ready();
  20800. Client cli(HOST, PORT);
  20801. auto res1 = cli.Get(std::string("/static/") + fname);
  20802. ASSERT_TRUE(res1);
  20803. ASSERT_EQ(200, res1->status);
  20804. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20805. // Extremely large year that may overflow date parsing routines.
  20806. Headers h_large_date = {
  20807. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20808. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20809. ASSERT_TRUE(res_bad);
  20810. // Expect server to treat this as invalid/mismatch and return full content
  20811. EXPECT_EQ(200, res_bad->status);
  20812. // If-Range with extremely large date should be treated as mismatch -> full
  20813. // content (200)
  20814. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20815. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20816. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20817. ASSERT_TRUE(res_ifrange);
  20818. EXPECT_EQ(200, res_ifrange->status);
  20819. svr.stop();
  20820. t.join();
  20821. std::remove(fname);
  20822. }
  20823. TEST(ETagTest, NegativeFileModificationTime) {
  20824. using namespace httplib;
  20825. const char *fname = "ims_negative_mtime.txt";
  20826. const std::string content = "negative-mtime";
  20827. {
  20828. std::ofstream ofs(fname);
  20829. ofs << content;
  20830. ASSERT_TRUE(ofs.good());
  20831. }
  20832. // Try to set file mtime to a negative value. This may fail on some
  20833. // platforms/filesystems; if it fails, the test will still verify server
  20834. // behaves safely by performing a regular conditional request.
  20835. #if defined(__APPLE__) || defined(__linux__)
  20836. bool set_negative = false;
  20837. do {
  20838. struct timeval times[2];
  20839. // access time: now
  20840. times[0].tv_sec = time(nullptr);
  20841. times[0].tv_usec = 0;
  20842. // modification time: negative (e.g., -1)
  20843. times[1].tv_sec = -1;
  20844. times[1].tv_usec = 0;
  20845. if (utimes(fname, times) == 0) { set_negative = true; }
  20846. } while (0);
  20847. #else
  20848. bool set_negative = false;
  20849. #endif
  20850. Server svr;
  20851. svr.set_mount_point("/static", ".");
  20852. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20853. svr.wait_until_ready();
  20854. Client cli(HOST, PORT);
  20855. auto res1 = cli.Get(std::string("/static/") + fname);
  20856. ASSERT_TRUE(res1);
  20857. ASSERT_EQ(200, res1->status);
  20858. bool has_last_modified = res1->has_header("Last-Modified");
  20859. std::string last_modified;
  20860. if (has_last_modified) {
  20861. last_modified = res1->get_header_value("Last-Modified");
  20862. }
  20863. if (set_negative) {
  20864. // If we successfully set a negative mtime, ensure server returns a
  20865. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20866. // with an old date and ensure server handles it without crash.
  20867. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20868. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20869. ASSERT_TRUE(res2);
  20870. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20871. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20872. } else {
  20873. // Could not set negative mtime on this platform; fall back to verifying
  20874. // that normal invalid/malformed dates are treated safely (non-304).
  20875. Headers h_bad_date = {
  20876. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20877. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20878. ASSERT_TRUE(res_bad);
  20879. EXPECT_EQ(200, res_bad->status);
  20880. }
  20881. svr.stop();
  20882. t.join();
  20883. std::remove(fname);
  20884. }
  20885. //==============================================================================
  20886. // Integration Tests with Server
  20887. //==============================================================================
  20888. class SSEIntegrationTest : public ::testing::Test {
  20889. protected:
  20890. void SetUp() override {
  20891. stop_server_.store(false);
  20892. events_.clear();
  20893. server_ = httplib::detail::make_unique<Server>();
  20894. setup_server();
  20895. start_server();
  20896. }
  20897. void TearDown() override {
  20898. stop_server_.store(true);
  20899. event_cv_.notify_all();
  20900. server_->stop();
  20901. if (server_thread_.joinable()) { server_thread_.join(); }
  20902. }
  20903. void setup_server() {
  20904. // Simple SSE endpoint
  20905. server_->Get("/events", [this](const Request &req, Response &res) {
  20906. auto last_id = req.get_header_value("Last-Event-ID");
  20907. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20908. res.set_chunked_content_provider(
  20909. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20910. std::unique_lock<std::mutex> lock(event_mutex_);
  20911. if (event_cv_.wait_for(
  20912. lock, std::chrono::milliseconds(200), [this] {
  20913. return !events_.empty() || stop_server_.load();
  20914. })) {
  20915. if (stop_server_.load()) { return false; }
  20916. if (!events_.empty()) {
  20917. std::string event = events_.front();
  20918. events_.erase(events_.begin());
  20919. sink.write(event.data(), event.size());
  20920. return true;
  20921. }
  20922. }
  20923. return !stop_server_.load();
  20924. });
  20925. });
  20926. // Endpoint that returns error
  20927. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20928. res.status = 500;
  20929. res.set_content("Internal Server Error", "text/plain");
  20930. });
  20931. // Endpoint for custom event types
  20932. server_->Get("/custom-events", [](const Request &, Response &res) {
  20933. res.set_chunked_content_provider(
  20934. "text/event-stream", [](size_t offset, DataSink &sink) {
  20935. if (offset == 0) {
  20936. std::string event = "event: update\ndata: updated\n\n"
  20937. "event: delete\ndata: deleted\n\n";
  20938. sink.write(event.data(), event.size());
  20939. }
  20940. return false; // End stream after sending
  20941. });
  20942. });
  20943. }
  20944. void start_server() {
  20945. port_ = server_->bind_to_any_port(HOST);
  20946. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20947. // Wait for server to start
  20948. while (!server_->is_running()) {
  20949. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20950. }
  20951. }
  20952. int get_port() const { return port_; }
  20953. void send_event(const std::string &event) {
  20954. std::lock_guard<std::mutex> lock(event_mutex_);
  20955. events_.push_back(event);
  20956. event_cv_.notify_all();
  20957. }
  20958. std::unique_ptr<Server> server_;
  20959. std::thread server_thread_;
  20960. std::mutex event_mutex_;
  20961. std::condition_variable event_cv_;
  20962. std::vector<std::string> events_;
  20963. std::atomic<bool> stop_server_{false};
  20964. std::string last_received_event_id_;
  20965. int port_ = 0;
  20966. };
  20967. //==============================================================================
  20968. // SSE Parsing Tests
  20969. //==============================================================================
  20970. class SSEParsingTest : public SSEIntegrationTest {
  20971. protected:
  20972. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20973. // A trailing sentinel event tells when the whole stream has been parsed.
  20974. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20975. auto body = stream + "event: end\ndata: end\n\n";
  20976. server_->Get("/parse", [body](const Request &, Response &res) {
  20977. res.set_content(body, "text/event-stream");
  20978. });
  20979. return collect("/parse");
  20980. }
  20981. // Runs SSEClient against path until an "end" event arrives and returns the
  20982. // messages dispatched before it
  20983. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20984. Client client(HOST, get_port());
  20985. sse::SSEClient sse(client, path);
  20986. std::mutex mutex;
  20987. std::condition_variable cv;
  20988. std::vector<sse::SSEMessage> messages;
  20989. auto done = false;
  20990. sse.on_message([&](const sse::SSEMessage &msg) {
  20991. std::lock_guard<std::mutex> lock(mutex);
  20992. // Ignore a replay from a reconnect that races with stop()
  20993. if (!done) { messages.push_back(msg); }
  20994. });
  20995. sse.on_event("end", [&](const sse::SSEMessage &) {
  20996. std::lock_guard<std::mutex> lock(mutex);
  20997. done = true;
  20998. cv.notify_all();
  20999. });
  21000. sse.set_reconnect_interval(100);
  21001. sse.start_async();
  21002. {
  21003. std::unique_lock<std::mutex> lock(mutex);
  21004. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21005. }
  21006. sse.stop();
  21007. EXPECT_TRUE(done);
  21008. return messages;
  21009. }
  21010. };
  21011. TEST_F(SSEParsingTest, SingleLineData) {
  21012. auto msgs = parse("data: hello\n\n");
  21013. ASSERT_EQ(msgs.size(), 1u);
  21014. EXPECT_EQ(msgs[0].data, "hello");
  21015. EXPECT_EQ(msgs[0].event, "message");
  21016. }
  21017. TEST_F(SSEParsingTest, MultiLineData) {
  21018. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21019. ASSERT_EQ(msgs.size(), 1u);
  21020. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21021. }
  21022. TEST_F(SSEParsingTest, CustomEventType) {
  21023. auto msgs = parse("event: update\ndata: payload\n\n");
  21024. ASSERT_EQ(msgs.size(), 1u);
  21025. EXPECT_EQ(msgs[0].event, "update");
  21026. EXPECT_EQ(msgs[0].data, "payload");
  21027. }
  21028. TEST_F(SSEParsingTest, EventIdHandling) {
  21029. auto msgs = parse("id: 12345\ndata: test\n\n");
  21030. ASSERT_EQ(msgs.size(), 1u);
  21031. EXPECT_EQ(msgs[0].id, "12345");
  21032. }
  21033. TEST_F(SSEParsingTest, EmptyEventId) {
  21034. auto msgs = parse("id:\ndata: test\n\n");
  21035. ASSERT_EQ(msgs.size(), 1u);
  21036. EXPECT_EQ(msgs[0].id, "");
  21037. }
  21038. TEST_F(SSEParsingTest, CommentsIgnored) {
  21039. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21040. ASSERT_EQ(msgs.size(), 1u);
  21041. EXPECT_EQ(msgs[0].data, "hello");
  21042. EXPECT_EQ(msgs[0].event, "message");
  21043. }
  21044. TEST_F(SSEParsingTest, ColonInValue) {
  21045. auto msgs = parse("data: hello:world:test\n\n");
  21046. ASSERT_EQ(msgs.size(), 1u);
  21047. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21048. }
  21049. TEST_F(SSEParsingTest, FieldNameOnly) {
  21050. // A line without a colon is a field name with an empty value
  21051. auto msgs = parse("data\n\n");
  21052. ASSERT_EQ(msgs.size(), 1u);
  21053. EXPECT_EQ(msgs[0].data, "");
  21054. }
  21055. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21056. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21057. ASSERT_EQ(msgs.size(), 1u);
  21058. EXPECT_EQ(msgs[0].event, "update");
  21059. EXPECT_EQ(msgs[0].data, "hello");
  21060. }
  21061. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21062. auto msgs = parse("data\r\n\r\n");
  21063. ASSERT_EQ(msgs.size(), 1u);
  21064. EXPECT_EQ(msgs[0].data, "");
  21065. }
  21066. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21067. auto msgs = parse("event: update\rdata: hello\r\r");
  21068. ASSERT_EQ(msgs.size(), 1u);
  21069. EXPECT_EQ(msgs[0].event, "update");
  21070. EXPECT_EQ(msgs[0].data, "hello");
  21071. }
  21072. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21073. // Chunk boundaries fall inside every \r\n and right before the first one
  21074. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21075. "\n\r", "\nevent: end\ndata: end\n\n"};
  21076. server_->Get("/split", [chunks](const Request &, Response &res) {
  21077. auto i = std::make_shared<size_t>(0);
  21078. res.set_chunked_content_provider(
  21079. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21080. if (*i == chunks.size()) {
  21081. sink.done();
  21082. } else {
  21083. sink.write(chunks[*i].data(), chunks[*i].size());
  21084. (*i)++;
  21085. }
  21086. return true;
  21087. });
  21088. });
  21089. auto msgs = collect("/split");
  21090. ASSERT_EQ(msgs.size(), 1u);
  21091. EXPECT_EQ(msgs[0].event, "update");
  21092. EXPECT_EQ(msgs[0].data, "hello");
  21093. }
  21094. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21095. // Only a BOM at the start of the stream is ignored
  21096. auto msgs = parse("\xEF\xBB\xBF"
  21097. "data: first\n\n"
  21098. "\xEF\xBB\xBF"
  21099. "data: second\n\n");
  21100. ASSERT_EQ(msgs.size(), 1u);
  21101. EXPECT_EQ(msgs[0].data, "first");
  21102. }
  21103. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21104. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21105. ASSERT_EQ(msgs.size(), 1u);
  21106. EXPECT_EQ(msgs[0].data, "hello");
  21107. EXPECT_EQ(msgs[0].event, "message");
  21108. }
  21109. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21110. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21111. ASSERT_EQ(msgs.size(), 2u);
  21112. EXPECT_EQ(msgs[0].data, "hello");
  21113. EXPECT_EQ(msgs[1].data, "hello");
  21114. }
  21115. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21116. // An event without data is not dispatched, and its type must not leak
  21117. // into the next event
  21118. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21119. ASSERT_EQ(msgs.size(), 1u);
  21120. EXPECT_EQ(msgs[0].event, "message");
  21121. EXPECT_EQ(msgs[0].data, "hello");
  21122. }
  21123. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21124. // The first connection sends only an id; the second echoes back the
  21125. // Last-Event-ID it was reconnected with
  21126. std::atomic<int> connection_count{0};
  21127. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21128. if (connection_count++ == 0) {
  21129. res.set_content("id: 42\n\n", "text/event-stream");
  21130. } else {
  21131. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21132. "\n\nevent: end\ndata: end\n\n",
  21133. "text/event-stream");
  21134. }
  21135. });
  21136. auto msgs = collect("/id-only");
  21137. ASSERT_EQ(msgs.size(), 1u);
  21138. EXPECT_EQ(msgs[0].data, "42");
  21139. }
  21140. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21141. // The first connection sets an id and then clears it with an empty one; the
  21142. // second reports whether it was reconnected with a Last-Event-ID
  21143. std::atomic<int> connection_count{0};
  21144. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21145. if (connection_count++ == 0) {
  21146. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21147. "text/event-stream");
  21148. } else {
  21149. res.set_content(
  21150. std::string("data: ") +
  21151. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21152. "\n\nevent: end\ndata: end\n\n",
  21153. "text/event-stream");
  21154. }
  21155. });
  21156. auto msgs = collect("/id-clear");
  21157. ASSERT_EQ(msgs.size(), 3u);
  21158. EXPECT_EQ(msgs[0].id, "1");
  21159. EXPECT_EQ(msgs[1].id, "");
  21160. EXPECT_EQ(msgs[2].data, "not sent");
  21161. }
  21162. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21163. // The first connection sets an id and then sends ids that cannot be carried
  21164. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21165. // with
  21166. std::atomic<int> connection_count{0};
  21167. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21168. if (connection_count++ == 0) {
  21169. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21170. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21171. "text/event-stream");
  21172. } else {
  21173. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21174. "\n\nevent: end\ndata: end\n\n",
  21175. "text/event-stream");
  21176. }
  21177. });
  21178. auto msgs = collect("/id-unsendable");
  21179. ASSERT_EQ(msgs.size(), 1u);
  21180. EXPECT_EQ(msgs[0].data, "42");
  21181. }
  21182. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21183. auto msgs = parse("event: notification\nid: evt-42\n"
  21184. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21185. ASSERT_EQ(msgs.size(), 1u);
  21186. EXPECT_EQ(msgs[0].event, "notification");
  21187. EXPECT_EQ(msgs[0].id, "evt-42");
  21188. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21189. }
  21190. TEST(SSEMessageTest, Clear) {
  21191. sse::SSEMessage msg;
  21192. msg.event = "custom";
  21193. msg.data = "some data";
  21194. msg.id = "123";
  21195. msg.clear();
  21196. EXPECT_EQ(msg.event, "message");
  21197. EXPECT_EQ(msg.data, "");
  21198. EXPECT_EQ(msg.id, "");
  21199. }
  21200. //==============================================================================
  21201. // SSE Integration Tests
  21202. //==============================================================================
  21203. // Test: Successful connection and on_open callback
  21204. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21205. // Add a simple endpoint that sends one event and closes
  21206. server_->Get("/simple-event", [](const Request &, Response &res) {
  21207. res.set_chunked_content_provider(
  21208. "text/event-stream", [](size_t offset, DataSink &sink) {
  21209. if (offset == 0) {
  21210. std::string event = "data: hello\n\n";
  21211. sink.write(event.data(), event.size());
  21212. }
  21213. return false; // Close stream after sending
  21214. });
  21215. });
  21216. Client client("localhost", get_port());
  21217. sse::SSEClient sse(client, "/simple-event");
  21218. std::atomic<bool> open_called{false};
  21219. std::atomic<bool> message_received{false};
  21220. sse.on_open([&open_called]() { open_called.store(true); });
  21221. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21222. if (msg.data == "hello") { message_received.store(true); }
  21223. });
  21224. sse.set_reconnect_interval(100);
  21225. sse.set_max_reconnect_attempts(1);
  21226. // Start async
  21227. sse.start_async();
  21228. // Wait for message to be processed
  21229. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21230. sse.stop();
  21231. EXPECT_TRUE(open_called.load());
  21232. EXPECT_TRUE(message_received.load());
  21233. }
  21234. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21235. // A data line that never ends.
  21236. server_->Get("/endless-line", [](const Request &, Response &res) {
  21237. res.set_chunked_content_provider(
  21238. "text/event-stream", [](size_t offset, DataSink &sink) {
  21239. if (offset == 0) { sink.write("data: ", 6); }
  21240. std::string chunk(64 * 1024, 'A');
  21241. return sink.write(chunk.data(), chunk.size());
  21242. });
  21243. });
  21244. Client client("localhost", get_port());
  21245. sse::SSEClient sse(client, "/endless-line");
  21246. std::atomic<bool> too_long{false};
  21247. sse.on_error([&](Error err) {
  21248. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21249. });
  21250. sse.set_max_reconnect_attempts(1);
  21251. sse.start_async();
  21252. for (int i = 0; i < 500 && !too_long; i++) {
  21253. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21254. }
  21255. sse.stop();
  21256. EXPECT_TRUE(too_long);
  21257. }
  21258. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21259. // Far more in all than the client's payload limit below.
  21260. server_->Get("/many-events", [](const Request &, Response &res) {
  21261. res.set_chunked_content_provider(
  21262. "text/event-stream", [](size_t offset, DataSink &sink) {
  21263. if (offset == 0) {
  21264. std::string events;
  21265. for (int i = 0; i < 1000; i++) {
  21266. events += "data: message\n\n";
  21267. }
  21268. sink.write(events.data(), events.size());
  21269. }
  21270. return false;
  21271. });
  21272. });
  21273. Client client("localhost", get_port());
  21274. client.set_payload_max_length(1024);
  21275. sse::SSEClient sse(client, "/many-events");
  21276. std::atomic<int> messages{0};
  21277. std::atomic<bool> too_large{false};
  21278. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21279. sse.on_error([&](Error err) {
  21280. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21281. });
  21282. sse.set_max_reconnect_attempts(1);
  21283. sse.start_async();
  21284. for (int i = 0; i < 500 && messages < 1000; i++) {
  21285. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21286. }
  21287. sse.stop();
  21288. EXPECT_GE(messages.load(), 1000);
  21289. EXPECT_FALSE(too_large);
  21290. }
  21291. // Test: on_message callback
  21292. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21293. // Endpoint that sends multiple events then closes
  21294. server_->Get("/multi-event", [](const Request &, Response &res) {
  21295. res.set_chunked_content_provider(
  21296. "text/event-stream", [](size_t offset, DataSink &sink) {
  21297. if (offset == 0) {
  21298. std::string events = "data: message1\n\ndata: message2\n\n";
  21299. sink.write(events.data(), events.size());
  21300. }
  21301. return false;
  21302. });
  21303. });
  21304. Client client("localhost", get_port());
  21305. sse::SSEClient sse(client, "/multi-event");
  21306. std::vector<std::string> received_messages;
  21307. std::mutex messages_mutex;
  21308. sse.on_message([&](const sse::SSEMessage &msg) {
  21309. std::lock_guard<std::mutex> lock(messages_mutex);
  21310. received_messages.push_back(msg.data);
  21311. });
  21312. sse.set_reconnect_interval(100);
  21313. sse.set_max_reconnect_attempts(1);
  21314. sse.start_async();
  21315. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21316. sse.stop();
  21317. std::lock_guard<std::mutex> lock(messages_mutex);
  21318. EXPECT_GE(received_messages.size(), 2u);
  21319. if (received_messages.size() >= 2) {
  21320. EXPECT_EQ(received_messages[0], "message1");
  21321. EXPECT_EQ(received_messages[1], "message2");
  21322. }
  21323. }
  21324. // Test: on_event for specific types
  21325. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21326. Client client("localhost", get_port());
  21327. sse::SSEClient sse(client, "/custom-events");
  21328. std::atomic<bool> update_received{false};
  21329. std::atomic<bool> delete_received{false};
  21330. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21331. if (msg.data == "updated") { update_received.store(true); }
  21332. });
  21333. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21334. if (msg.data == "deleted") { delete_received.store(true); }
  21335. });
  21336. sse.set_max_reconnect_attempts(1);
  21337. sse.start_async();
  21338. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21339. sse.stop();
  21340. EXPECT_TRUE(update_received.load());
  21341. EXPECT_TRUE(delete_received.load());
  21342. }
  21343. // Test: on_error callback on connection failure
  21344. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21345. // Connect to a non-existent port
  21346. Client client("localhost", 59999);
  21347. sse::SSEClient sse(client, "/events");
  21348. std::atomic<bool> error_called{false};
  21349. Error received_error = Error::Success;
  21350. sse.on_error([&](Error err) {
  21351. error_called.store(true);
  21352. received_error = err;
  21353. });
  21354. sse.set_reconnect_interval(50);
  21355. sse.set_max_reconnect_attempts(1);
  21356. sse.start_async();
  21357. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21358. sse.stop();
  21359. EXPECT_TRUE(error_called.load());
  21360. EXPECT_NE(received_error, Error::Success);
  21361. }
  21362. // Test: Last-Event-ID header sent on reconnect
  21363. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21364. // Endpoint that sends event with ID
  21365. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21366. res.set_chunked_content_provider(
  21367. "text/event-stream", [](size_t offset, DataSink &sink) {
  21368. if (offset == 0) {
  21369. std::string event = "id: evt-123\ndata: test\n\n";
  21370. sink.write(event.data(), event.size());
  21371. }
  21372. return false;
  21373. });
  21374. });
  21375. Client client("localhost", get_port());
  21376. sse::SSEClient sse(client, "/event-with-id");
  21377. std::atomic<bool> id_received{false};
  21378. sse.on_message([&](const sse::SSEMessage &msg) {
  21379. if (!msg.id.empty()) { id_received.store(true); }
  21380. });
  21381. sse.set_reconnect_interval(100);
  21382. sse.set_max_reconnect_attempts(1);
  21383. sse.start_async();
  21384. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21385. sse.stop();
  21386. EXPECT_TRUE(id_received.load());
  21387. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21388. }
  21389. // Test: Manual stop
  21390. TEST_F(SSEIntegrationTest, ManualStop) {
  21391. // Endpoint that sends one event and stays open briefly
  21392. std::atomic<bool> handler_running{true};
  21393. server_->Get("/stay-open", [&handler_running](const Request &,
  21394. Response &res) {
  21395. res.set_chunked_content_provider(
  21396. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  21397. if (offset == 0) {
  21398. std::string event = "data: connected\n\n";
  21399. sink.write(event.data(), event.size());
  21400. }
  21401. // Keep connection open while handler_running is true
  21402. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  21403. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21404. }
  21405. return false;
  21406. });
  21407. });
  21408. Client client("localhost", get_port());
  21409. sse::SSEClient sse(client, "/stay-open");
  21410. std::atomic<bool> connected{false};
  21411. sse.on_open([&connected]() { connected.store(true); });
  21412. sse.set_reconnect_interval(100);
  21413. sse.set_max_reconnect_attempts(1);
  21414. sse.start_async();
  21415. // Wait for connection to establish
  21416. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21417. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21418. }
  21419. EXPECT_TRUE(connected.load());
  21420. EXPECT_TRUE(sse.is_connected());
  21421. // Signal handler to stop
  21422. handler_running.store(false);
  21423. // Stop SSE client
  21424. sse.stop();
  21425. EXPECT_FALSE(sse.is_connected());
  21426. }
  21427. // Test: SSEClient with custom headers
  21428. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21429. // Setup a server endpoint that checks for custom header
  21430. std::atomic<bool> header_received{false};
  21431. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21432. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21433. header_received.store(true);
  21434. }
  21435. res.set_chunked_content_provider("text/event-stream",
  21436. [](size_t, DataSink &) { return false; });
  21437. });
  21438. Client client("localhost", get_port());
  21439. Headers headers = {{"X-Custom-Header", "custom-value"}};
  21440. sse::SSEClient sse(client, "/header-check", headers);
  21441. sse.set_max_reconnect_attempts(1);
  21442. sse.start_async();
  21443. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21444. sse.stop();
  21445. EXPECT_TRUE(header_received.load());
  21446. }
  21447. // Test: Reconnect interval configuration
  21448. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21449. Client client("localhost", get_port());
  21450. sse::SSEClient sse(client, "/events");
  21451. auto &result = sse.set_reconnect_interval(500);
  21452. // Builder pattern should return reference to self
  21453. EXPECT_EQ(&result, &sse);
  21454. }
  21455. // Test: Max reconnect attempts
  21456. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21457. // Connect to non-existent port to force reconnects
  21458. Client client("localhost", 59998);
  21459. sse::SSEClient sse(client, "/events");
  21460. std::atomic<int> error_count{0};
  21461. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21462. sse.set_reconnect_interval(50);
  21463. sse.set_max_reconnect_attempts(2);
  21464. auto start = std::chrono::steady_clock::now();
  21465. sse.start(); // Blocking call
  21466. auto end = std::chrono::steady_clock::now();
  21467. // Should have stopped after 2 failed attempts
  21468. EXPECT_GE(error_count.load(), 2);
  21469. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21470. auto duration =
  21471. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21472. #ifdef _WIN32
  21473. // Windows is much slower for socket connection failures
  21474. EXPECT_LT(duration.count(), 7000);
  21475. #else
  21476. EXPECT_LT(duration.count(), 1000);
  21477. #endif
  21478. }
  21479. // Test: Multi-line data in integration
  21480. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  21481. // Endpoint with multi-line data
  21482. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21483. res.set_chunked_content_provider(
  21484. "text/event-stream", [](size_t offset, DataSink &sink) {
  21485. if (offset == 0) {
  21486. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21487. sink.write(event.data(), event.size());
  21488. }
  21489. return false;
  21490. });
  21491. });
  21492. Client client("localhost", get_port());
  21493. sse::SSEClient sse(client, "/multiline-data");
  21494. std::string received_data;
  21495. std::mutex data_mutex;
  21496. sse.on_message([&](const sse::SSEMessage &msg) {
  21497. std::lock_guard<std::mutex> lock(data_mutex);
  21498. received_data = msg.data;
  21499. });
  21500. sse.set_reconnect_interval(100);
  21501. sse.set_max_reconnect_attempts(1);
  21502. sse.start_async();
  21503. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21504. sse.stop();
  21505. std::lock_guard<std::mutex> lock(data_mutex);
  21506. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21507. }
  21508. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21509. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21510. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21511. DataSink &sink) {
  21512. if (offset == 0) {
  21513. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21514. sink.write(events.data(), events.size());
  21515. }
  21516. return false;
  21517. });
  21518. });
  21519. Client client("localhost", get_port());
  21520. sse::SSEClient sse(client, "/empty-data-lines");
  21521. std::mutex mutex;
  21522. std::condition_variable cv;
  21523. std::vector<std::string> received;
  21524. sse.on_message([&](const sse::SSEMessage &msg) {
  21525. std::lock_guard<std::mutex> lock(mutex);
  21526. received.push_back(msg.data);
  21527. cv.notify_all();
  21528. });
  21529. sse.set_max_reconnect_attempts(1);
  21530. sse.start_async();
  21531. {
  21532. std::unique_lock<std::mutex> lock(mutex);
  21533. cv.wait_for(lock, std::chrono::seconds(2),
  21534. [&] { return received.size() >= 3; });
  21535. }
  21536. sse.stop();
  21537. ASSERT_GE(received.size(), 3u);
  21538. EXPECT_EQ(received[0], "");
  21539. EXPECT_EQ(received[1], "\nhello");
  21540. EXPECT_EQ(received[2], "");
  21541. }
  21542. // Test: Auto-reconnect after server disconnection
  21543. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21544. std::atomic<int> connection_count{0};
  21545. std::atomic<int> message_count{0};
  21546. // Endpoint that sends one event and closes, forcing reconnect
  21547. server_->Get("/reconnect-test",
  21548. [&connection_count](const Request &, Response &res) {
  21549. connection_count.fetch_add(1);
  21550. res.set_chunked_content_provider(
  21551. "text/event-stream", [](size_t offset, DataSink &sink) {
  21552. if (offset == 0) {
  21553. std::string event = "data: hello\n\n";
  21554. sink.write(event.data(), event.size());
  21555. }
  21556. return false; // Close connection after sending
  21557. });
  21558. });
  21559. Client client("localhost", get_port());
  21560. sse::SSEClient sse(client, "/reconnect-test");
  21561. sse.on_message([&message_count](const sse::SSEMessage &) {
  21562. message_count.fetch_add(1);
  21563. });
  21564. sse.set_reconnect_interval(100);
  21565. sse.set_max_reconnect_attempts(3);
  21566. sse.start_async();
  21567. // Wait long enough for multiple reconnects
  21568. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21569. sse.stop();
  21570. // Should have connected multiple times (initial + reconnects)
  21571. EXPECT_GE(connection_count.load(), 2);
  21572. // Should have received messages from multiple connections
  21573. EXPECT_GE(message_count.load(), 2);
  21574. }
  21575. // Test: A retry field that is not all ASCII digits is ignored
  21576. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21577. std::atomic<int> connection_count{0};
  21578. server_->Get("/bad-retry",
  21579. [&connection_count](const Request &, Response &res) {
  21580. connection_count.fetch_add(1);
  21581. res.set_chunked_content_provider(
  21582. "text/event-stream", [](size_t offset, DataSink &sink) {
  21583. if (offset == 0) {
  21584. std::string event = "retry: -1\ndata: hello\n\n";
  21585. sink.write(event.data(), event.size());
  21586. }
  21587. return false;
  21588. });
  21589. });
  21590. Client client("localhost", get_port());
  21591. sse::SSEClient sse(client, "/bad-retry");
  21592. sse.set_reconnect_interval(10000);
  21593. sse.start_async();
  21594. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21595. sse.stop();
  21596. EXPECT_EQ(connection_count.load(), 1);
  21597. }
  21598. // Test: A retry field of all ASCII digits sets the reconnection time
  21599. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21600. std::mutex mutex;
  21601. std::condition_variable cv;
  21602. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21603. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21604. {
  21605. std::lock_guard<std::mutex> lock(mutex);
  21606. connected_at.push_back(std::chrono::steady_clock::now());
  21607. cv.notify_all();
  21608. }
  21609. res.set_chunked_content_provider(
  21610. "text/event-stream", [](size_t offset, DataSink &sink) {
  21611. if (offset == 0) {
  21612. std::string event = "retry: 0\ndata: hello\n\n";
  21613. sink.write(event.data(), event.size());
  21614. }
  21615. return false;
  21616. });
  21617. });
  21618. Client client("localhost", get_port());
  21619. sse::SSEClient sse(client, "/zero-retry");
  21620. sse.set_reconnect_interval(10000);
  21621. sse.start_async();
  21622. {
  21623. std::unique_lock<std::mutex> lock(mutex);
  21624. cv.wait_for(lock, std::chrono::seconds(5),
  21625. [&] { return connected_at.size() >= 2; });
  21626. }
  21627. sse.stop();
  21628. // The server-supplied interval is applied, but never below 100ms, so
  21629. // "retry: 0" does not cause a busy reconnect loop
  21630. std::lock_guard<std::mutex> lock(mutex);
  21631. ASSERT_GE(connected_at.size(), 2u);
  21632. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21633. connected_at[1] - connected_at[0])
  21634. .count();
  21635. EXPECT_GE(interval_ms, 100);
  21636. }
  21637. // Test: Last-Event-ID sent on reconnect
  21638. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21639. std::atomic<int> connection_count{0};
  21640. std::vector<std::string> received_last_event_ids;
  21641. std::mutex id_mutex;
  21642. // Endpoint that checks Last-Event-ID header and sends event with ID
  21643. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21644. int conn = connection_count.fetch_add(1);
  21645. // Capture the Last-Event-ID header from each connection
  21646. {
  21647. std::lock_guard<std::mutex> lock(id_mutex);
  21648. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21649. }
  21650. res.set_chunked_content_provider(
  21651. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21652. if (offset == 0) {
  21653. std::string event =
  21654. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21655. sink.write(event.data(), event.size());
  21656. }
  21657. return false;
  21658. });
  21659. });
  21660. Client client("localhost", get_port());
  21661. sse::SSEClient sse(client, "/reconnect-with-id");
  21662. sse.set_reconnect_interval(100);
  21663. sse.set_max_reconnect_attempts(3);
  21664. sse.start_async();
  21665. // Wait for at least 2 connections
  21666. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21667. sse.stop();
  21668. // Verify behavior
  21669. std::lock_guard<std::mutex> lock(id_mutex);
  21670. EXPECT_GE(received_last_event_ids.size(), 2u);
  21671. // First connection should have no Last-Event-ID
  21672. if (!received_last_event_ids.empty()) {
  21673. EXPECT_EQ(received_last_event_ids[0], "");
  21674. }
  21675. // Second connection should have Last-Event-ID from first connection
  21676. if (received_last_event_ids.size() >= 2) {
  21677. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21678. }
  21679. }
  21680. // Test: set_headers updates headers used on reconnect
  21681. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21682. std::vector<std::string> received_tokens;
  21683. std::mutex token_mutex;
  21684. // Endpoint that captures Authorization header
  21685. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21686. {
  21687. std::lock_guard<std::mutex> lock(token_mutex);
  21688. received_tokens.push_back(req.get_header_value("Authorization"));
  21689. }
  21690. res.set_chunked_content_provider(
  21691. "text/event-stream", [](size_t offset, DataSink &sink) {
  21692. if (offset == 0) {
  21693. std::string event = "data: hello\n\n";
  21694. sink.write(event.data(), event.size());
  21695. }
  21696. return false; // Close connection to trigger reconnect
  21697. });
  21698. });
  21699. Client client("localhost", get_port());
  21700. Headers headers = {{"Authorization", "Bearer old-token"}};
  21701. sse::SSEClient sse(client, "/auth-check", headers);
  21702. // Update headers on each successful connection
  21703. sse.on_open(
  21704. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21705. sse.set_reconnect_interval(100);
  21706. sse.set_max_reconnect_attempts(3);
  21707. sse.start_async();
  21708. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21709. sse.stop();
  21710. std::lock_guard<std::mutex> lock(token_mutex);
  21711. ASSERT_GE(received_tokens.size(), 2u);
  21712. // First connection uses original header
  21713. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21714. // Second connection uses updated header from set_headers
  21715. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21716. }
  21717. // Test: 401 allows reconnection (so on_error can refresh headers)
  21718. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21719. std::atomic<int> connection_count{0};
  21720. // Endpoint: returns 401 on first attempt, 200 on second
  21721. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21722. int conn = connection_count.fetch_add(1);
  21723. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21724. res.status = StatusCode::Unauthorized_401;
  21725. res.set_content("Unauthorized", "text/plain");
  21726. return;
  21727. }
  21728. res.set_chunked_content_provider(
  21729. "text/event-stream", [](size_t offset, DataSink &sink) {
  21730. if (offset == 0) {
  21731. std::string event = "data: authenticated\n\n";
  21732. sink.write(event.data(), event.size());
  21733. }
  21734. return false;
  21735. });
  21736. });
  21737. Client client("localhost", get_port());
  21738. Headers headers = {{"Authorization", "Bearer expired"}};
  21739. sse::SSEClient sse(client, "/auth-retry", headers);
  21740. std::atomic<bool> message_received{false};
  21741. // Refresh token on error
  21742. sse.on_error(
  21743. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21744. sse.on_message([&](const sse::SSEMessage &msg) {
  21745. if (msg.data == "authenticated") { message_received.store(true); }
  21746. });
  21747. sse.set_reconnect_interval(100);
  21748. sse.set_max_reconnect_attempts(3);
  21749. sse.start_async();
  21750. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21751. sse.stop();
  21752. // Should have reconnected after 401 and succeeded with new token
  21753. EXPECT_GE(connection_count.load(), 2);
  21754. EXPECT_TRUE(message_received.load());
  21755. }
  21756. TEST(Issue2318Test, EmptyHostString) {
  21757. {
  21758. httplib::Client cli_empty("", PORT);
  21759. auto res = cli_empty.Get("/");
  21760. ASSERT_FALSE(res);
  21761. EXPECT_EQ(httplib::Error::Connection, res.error());
  21762. }
  21763. {
  21764. httplib::Client cli(" ", PORT);
  21765. auto res = cli.Get("/");
  21766. ASSERT_FALSE(res);
  21767. EXPECT_EQ(httplib::Error::Connection, res.error());
  21768. }
  21769. }
  21770. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21771. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21772. Server svr;
  21773. // Set a small payload limit (1KB)
  21774. svr.set_payload_max_length(1024);
  21775. svr.Post("/test", [&](const Request &req, Response &res) {
  21776. res.set_content("Body size: " + std::to_string(req.body.size()),
  21777. "text/plain");
  21778. });
  21779. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21780. auto se = detail::scope_exit([&] {
  21781. svr.stop();
  21782. listen_thread.join();
  21783. });
  21784. svr.wait_until_ready();
  21785. // Create data that compresses well but exceeds limit when decompressed
  21786. // 8KB of repeated null bytes compresses to a very small size
  21787. std::string original_data(8 * 1024, '\0');
  21788. // Compress the data using gzip
  21789. std::string compressed_data;
  21790. detail::gzip_compressor compressor;
  21791. compressor.compress(original_data.data(), original_data.size(), true,
  21792. [&](const char *data, size_t size) {
  21793. compressed_data.append(data, size);
  21794. return true;
  21795. });
  21796. // Verify compression worked (compressed should be much smaller)
  21797. ASSERT_LT(compressed_data.size(), original_data.size());
  21798. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21799. // Send compressed data with Content-Encoding: gzip
  21800. Client cli(HOST, PORT);
  21801. Headers headers = {{"Content-Encoding", "gzip"}};
  21802. auto res =
  21803. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21804. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21806. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21807. }
  21808. #endif
  21809. // ============================================================================
  21810. // OpenSSL-Specific Tests
  21811. // ============================================================================
  21812. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21813. X509 *readCertificate(const std::string &strFileName) {
  21814. std::ifstream inStream(strFileName);
  21815. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21816. std::istreambuf_iterator<char>());
  21817. if (strCertPEM.empty()) return (nullptr);
  21818. BIO *pbCert = BIO_new(BIO_s_mem());
  21819. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21820. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21821. BIO_free(pbCert);
  21822. return (pCert);
  21823. }
  21824. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21825. std::ifstream inStream(strFileName);
  21826. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21827. std::istreambuf_iterator<char>());
  21828. if (strPrivateKeyPEM.empty()) return (nullptr);
  21829. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21830. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21831. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21832. BIO_free(pbPrivKey);
  21833. return (pPrivateKey);
  21834. }
  21835. TEST(BindServerTest, UpdateCerts) {
  21836. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21837. int port = svr.bind_to_any_port("0.0.0.0");
  21838. ASSERT_TRUE(svr.is_valid());
  21839. ASSERT_TRUE(port > 0);
  21840. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21841. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21842. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21843. ASSERT_TRUE(cert != nullptr);
  21844. ASSERT_TRUE(ca_cert != nullptr);
  21845. ASSERT_TRUE(key != nullptr);
  21846. X509_STORE *cert_store = X509_STORE_new();
  21847. X509_STORE_add_cert(cert_store, ca_cert);
  21848. // svr.update_certs(cert, key, cert_store); // deprecated
  21849. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21850. CLIENT_CA_CERT_FILE);
  21851. ASSERT_TRUE(svr.is_valid());
  21852. svr.stop();
  21853. X509_STORE_free(cert_store);
  21854. X509_free(cert);
  21855. X509_free(ca_cert);
  21856. EVP_PKEY_free(key);
  21857. }
  21858. // Test that update_certs() updates client CA list correctly
  21859. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21860. // Start with file-based constructor
  21861. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21862. ASSERT_TRUE(svr.is_valid());
  21863. // Initially no client CA list should be set
  21864. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21865. ASSERT_TRUE(ssl_ctx != nullptr);
  21866. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21867. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21868. EXPECT_EQ(0, count_before);
  21869. // Now update with client CA (PEM string)
  21870. std::string cert_pem, key_pem, ca_pem;
  21871. read_file(SERVER_CERT_FILE, cert_pem);
  21872. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21873. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21874. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21875. ASSERT_TRUE(svr.is_valid());
  21876. // Now client CA list should be set
  21877. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21878. ASSERT_TRUE(ca_list_after != nullptr);
  21879. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21880. }
  21881. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21882. // Test that the file-path SSLServer constructor properly sets the client CA
  21883. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21884. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21885. ASSERT_TRUE(svr.is_valid());
  21886. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21887. ASSERT_TRUE(ssl_ctx != nullptr);
  21888. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21889. ASSERT_TRUE(ca_list != nullptr);
  21890. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21891. }
  21892. #endif
  21893. // ============================================================================
  21894. // MbedTLS-Specific Tests
  21895. // ============================================================================
  21896. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21897. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21898. using namespace httplib::tls;
  21899. // Track if callback was invoked
  21900. bool callback_invoked = false;
  21901. // The callback receives void* ctx which is actually MbedTlsContext*
  21902. // We can access the mbedtls_ssl_config via the context
  21903. auto setup_callback = [&callback_invoked](void *ctx) {
  21904. callback_invoked = true;
  21905. // Cast to MbedTlsContext* to access the ssl config
  21906. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21907. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21908. // Use static variables to hold certificate data (simplified for test)
  21909. static mbedtls_x509_crt own_cert;
  21910. static mbedtls_pk_context own_key;
  21911. static mbedtls_x509_crt ca_chain;
  21912. static bool initialized = false;
  21913. if (!initialized) {
  21914. mbedtls_x509_crt_init(&own_cert);
  21915. mbedtls_pk_init(&own_key);
  21916. mbedtls_x509_crt_init(&ca_chain);
  21917. // Load server certificate
  21918. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21919. return false;
  21920. }
  21921. // Load server private key.
  21922. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21923. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21924. #if MBEDTLS_VERSION_MAJOR == 3
  21925. ,
  21926. mbedtls_ctr_drbg_random, nullptr
  21927. #endif
  21928. ) != 0) {
  21929. return false;
  21930. }
  21931. // Load CA chain for client verification
  21932. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21933. return false;
  21934. }
  21935. initialized = true;
  21936. }
  21937. // Configure the SSL config
  21938. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21939. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21940. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21941. // Set minimum TLS version using mbedTLS native API
  21942. #if MBEDTLS_VERSION_MAJOR >= 3
  21943. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21944. #else
  21945. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21946. MBEDTLS_SSL_MINOR_VERSION_3);
  21947. #endif
  21948. return true;
  21949. };
  21950. SSLServer svr(setup_callback);
  21951. ASSERT_TRUE(svr.is_valid());
  21952. ASSERT_TRUE(callback_invoked);
  21953. svr.Get("/test", [&](const Request &req, Response &res) {
  21954. res.set_content("test", "text/plain");
  21955. auto cert = req.peer_cert();
  21956. ASSERT_TRUE(static_cast<bool>(cert));
  21957. auto common_name = cert.subject_cn();
  21958. EXPECT_EQ("Common Name", common_name);
  21959. });
  21960. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21961. auto se = detail::scope_exit([&] {
  21962. svr.stop();
  21963. t.join();
  21964. ASSERT_FALSE(svr.is_running());
  21965. });
  21966. svr.wait_until_ready();
  21967. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21968. cli.enable_server_certificate_verification(false);
  21969. cli.set_connection_timeout(30);
  21970. auto res = cli.Get("/test");
  21971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21972. ASSERT_EQ(StatusCode::OK_200, res->status);
  21973. }
  21974. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21975. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21976. // keep-alive SSL session, which reads through that config in
  21977. // mbedtls_ssl_close_notify.
  21978. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21979. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21980. ASSERT_TRUE(svr.is_valid());
  21981. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21982. res.set_content("test", "text/plain");
  21983. });
  21984. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21985. auto se = detail::scope_exit([&] {
  21986. svr.stop();
  21987. t.join();
  21988. ASSERT_FALSE(svr.is_running());
  21989. });
  21990. svr.wait_until_ready();
  21991. {
  21992. SSLClient cli(HOST, PORT);
  21993. cli.enable_server_certificate_verification(false);
  21994. cli.set_keep_alive(true);
  21995. auto res = cli.Get("/test");
  21996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21997. ASSERT_EQ(StatusCode::OK_200, res->status);
  21998. // cli is destructed here with the keep-alive SSL session still open.
  21999. }
  22000. }
  22001. #endif
  22002. // WebSocket Tests
  22003. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22004. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22005. // defining the meaning of these bits has been negotiated.
  22006. auto make_frame = [](uint8_t first_byte) {
  22007. std::string frame;
  22008. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22009. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22010. frame += "Hello";
  22011. return frame;
  22012. };
  22013. // RSV1 set (0x40)
  22014. {
  22015. detail::BufferStream strm;
  22016. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22017. ws::Opcode opcode;
  22018. std::string payload;
  22019. bool fin;
  22020. EXPECT_EQ(
  22021. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22022. ws::impl::FrameRead::Fail);
  22023. }
  22024. // RSV2 set (0x20)
  22025. {
  22026. detail::BufferStream strm;
  22027. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22028. ws::Opcode opcode;
  22029. std::string payload;
  22030. bool fin;
  22031. EXPECT_EQ(
  22032. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22033. ws::impl::FrameRead::Fail);
  22034. }
  22035. // RSV3 set (0x10)
  22036. {
  22037. detail::BufferStream strm;
  22038. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22039. ws::Opcode opcode;
  22040. std::string payload;
  22041. bool fin;
  22042. EXPECT_EQ(
  22043. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22044. ws::impl::FrameRead::Fail);
  22045. }
  22046. // No RSV bits set - should succeed
  22047. {
  22048. detail::BufferStream strm;
  22049. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22050. ws::Opcode opcode;
  22051. std::string payload;
  22052. bool fin;
  22053. EXPECT_EQ(
  22054. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22055. ws::impl::FrameRead::Ok);
  22056. EXPECT_EQ(ws::Opcode::Text, opcode);
  22057. EXPECT_EQ("Hello", payload);
  22058. EXPECT_TRUE(fin);
  22059. }
  22060. }
  22061. TEST(WebSocketTest, ControlFrameValidation) {
  22062. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22063. // payload length <= 125.
  22064. // Ping with FIN=0 - must be rejected
  22065. {
  22066. detail::BufferStream strm;
  22067. std::string frame;
  22068. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22069. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22070. strm.write(frame.data(), frame.size());
  22071. ws::Opcode opcode;
  22072. std::string payload;
  22073. bool fin;
  22074. EXPECT_EQ(
  22075. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22076. ws::impl::FrameRead::Fail);
  22077. }
  22078. // Close with FIN=0 - must be rejected
  22079. {
  22080. detail::BufferStream strm;
  22081. std::string frame;
  22082. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22083. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22084. strm.write(frame.data(), frame.size());
  22085. ws::Opcode opcode;
  22086. std::string payload;
  22087. bool fin;
  22088. EXPECT_EQ(
  22089. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22090. ws::impl::FrameRead::Fail);
  22091. }
  22092. // Ping with payload_len=126 (extended length) - must be rejected
  22093. {
  22094. detail::BufferStream strm;
  22095. std::string frame;
  22096. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22097. frame += static_cast<char>(126); // payload_len=126 (>125)
  22098. frame += static_cast<char>(0x00); // extended length high byte
  22099. frame += static_cast<char>(126); // extended length low byte
  22100. frame += std::string(126, 'x');
  22101. strm.write(frame.data(), frame.size());
  22102. ws::Opcode opcode;
  22103. std::string payload;
  22104. bool fin;
  22105. EXPECT_EQ(
  22106. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22107. ws::impl::FrameRead::Fail);
  22108. }
  22109. // Ping with FIN=1 and payload_len=125 - should succeed
  22110. {
  22111. detail::BufferStream strm;
  22112. std::string frame;
  22113. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22114. frame += static_cast<char>(125); // payload_len=125
  22115. frame += std::string(125, 'x');
  22116. strm.write(frame.data(), frame.size());
  22117. ws::Opcode opcode;
  22118. std::string payload;
  22119. bool fin;
  22120. EXPECT_EQ(
  22121. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22122. ws::impl::FrameRead::Ok);
  22123. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22124. EXPECT_EQ(125u, payload.size());
  22125. EXPECT_TRUE(fin);
  22126. }
  22127. }
  22128. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22129. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22130. // length MUST be 0.
  22131. // MSB set - must be rejected
  22132. {
  22133. detail::BufferStream strm;
  22134. std::string frame;
  22135. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22136. frame += static_cast<char>(127); // 64-bit extended length
  22137. frame += static_cast<char>(0x80); // MSB set (invalid)
  22138. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22139. strm.write(frame.data(), frame.size());
  22140. ws::Opcode opcode;
  22141. std::string payload;
  22142. bool fin;
  22143. EXPECT_EQ(
  22144. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22145. ws::impl::FrameRead::Fail);
  22146. }
  22147. // MSB clear - should pass length parsing (will be rejected by max_len,
  22148. // but that's a different check; use a small length to verify)
  22149. {
  22150. detail::BufferStream strm;
  22151. std::string frame;
  22152. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22153. frame += static_cast<char>(127); // 64-bit extended length
  22154. frame += std::string(7, '\0'); // high bytes = 0
  22155. frame += static_cast<char>(0x03); // length = 3
  22156. frame += "abc";
  22157. strm.write(frame.data(), frame.size());
  22158. ws::Opcode opcode;
  22159. std::string payload;
  22160. bool fin;
  22161. EXPECT_EQ(
  22162. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22163. ws::impl::FrameRead::Ok);
  22164. EXPECT_EQ(ws::Opcode::Text, opcode);
  22165. EXPECT_EQ("abc", payload);
  22166. }
  22167. }
  22168. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22169. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22170. // Valid UTF-8
  22171. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22172. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22173. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22174. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22175. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22176. // Invalid UTF-8
  22177. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22178. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22179. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22180. EXPECT_FALSE(
  22181. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22182. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22183. }
  22184. TEST(WebSocketTest, ConnectAndDisconnect) {
  22185. Server svr;
  22186. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22187. std::string msg;
  22188. while (ws.read(msg)) {}
  22189. });
  22190. auto port = svr.bind_to_any_port(HOST);
  22191. std::thread t([&]() { svr.listen_after_bind(); });
  22192. svr.wait_until_ready();
  22193. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22194. auto res = client.connect();
  22195. ASSERT_TRUE(res);
  22196. EXPECT_EQ(Error::Success, res.error());
  22197. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22198. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22199. EXPECT_TRUE(client.is_open());
  22200. client.close();
  22201. EXPECT_FALSE(client.is_open());
  22202. svr.stop();
  22203. t.join();
  22204. }
  22205. TEST(WebSocketTest, ValidURL) {
  22206. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22207. EXPECT_TRUE(ws1.is_valid());
  22208. ws::WebSocketClient ws2("ws://example.com/path");
  22209. EXPECT_TRUE(ws2.is_valid());
  22210. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22211. EXPECT_TRUE(ws3.is_valid());
  22212. #ifdef CPPHTTPLIB_SSL_ENABLED
  22213. ws::WebSocketClient wss1("wss://example.com/path");
  22214. EXPECT_TRUE(wss1.is_valid());
  22215. ws::WebSocketClient wss2("wss://example.com:443/path");
  22216. EXPECT_TRUE(wss2.is_valid());
  22217. #endif
  22218. }
  22219. TEST(WebSocketTest, InvalidURL) {
  22220. // No scheme
  22221. ws::WebSocketClient ws1("localhost:8080/path");
  22222. EXPECT_FALSE(ws1.is_valid());
  22223. // No path
  22224. ws::WebSocketClient ws2("ws://localhost:8080");
  22225. EXPECT_FALSE(ws2.is_valid());
  22226. // Empty string
  22227. ws::WebSocketClient ws3("");
  22228. EXPECT_FALSE(ws3.is_valid());
  22229. // Missing host
  22230. ws::WebSocketClient ws4("ws://:8080/path");
  22231. EXPECT_FALSE(ws4.is_valid());
  22232. // Port number overflow — should not crash
  22233. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22234. EXPECT_FALSE(ws5.is_valid());
  22235. // Port out of range
  22236. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22237. EXPECT_FALSE(ws6.is_valid());
  22238. }
  22239. TEST(WebSocketTest, UnsupportedScheme) {
  22240. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22241. ws::WebSocketClient ws1("http://localhost:8080/path");
  22242. EXPECT_FALSE(ws1.is_valid());
  22243. ws::WebSocketClient ws2("https://localhost:8080/path");
  22244. EXPECT_FALSE(ws2.is_valid());
  22245. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22246. EXPECT_FALSE(ws3.is_valid());
  22247. #else
  22248. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22249. std::invalid_argument);
  22250. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22251. std::invalid_argument);
  22252. #endif
  22253. }
  22254. TEST(WebSocketTest, ConnectWhenInvalid) {
  22255. ws::WebSocketClient ws("not a valid url");
  22256. EXPECT_FALSE(ws.is_valid());
  22257. auto res = ws.connect();
  22258. EXPECT_FALSE(res);
  22259. EXPECT_EQ(Error::Connection, res.error());
  22260. EXPECT_EQ(-1, res.status());
  22261. }
  22262. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22263. // Grab a port that is free, then close it again so nothing listens there
  22264. Server svr;
  22265. auto port = svr.bind_to_any_port(HOST);
  22266. svr.stop();
  22267. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22268. auto res = client.connect();
  22269. ASSERT_FALSE(res);
  22270. EXPECT_EQ(Error::Connection, res.error());
  22271. EXPECT_EQ(-1, res.status());
  22272. }
  22273. TEST(WebSocketTest, DefaultPort) {
  22274. ws::WebSocketClient ws1("ws://example.com/path");
  22275. EXPECT_TRUE(ws1.is_valid());
  22276. // ws:// defaults to port 80 (verified by successful parse)
  22277. #ifdef CPPHTTPLIB_SSL_ENABLED
  22278. ws::WebSocketClient ws2("wss://example.com/path");
  22279. EXPECT_TRUE(ws2.is_valid());
  22280. // wss:// defaults to port 443 (verified by successful parse)
  22281. #endif
  22282. }
  22283. TEST(WebSocketTest, IPv6LiteralAddress) {
  22284. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22285. EXPECT_TRUE(ws1.is_valid());
  22286. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22287. EXPECT_TRUE(ws2.is_valid());
  22288. }
  22289. TEST(WebSocketTest, ComplexPath) {
  22290. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22291. EXPECT_TRUE(ws1.is_valid());
  22292. ws::WebSocketClient ws2("ws://localhost:8080/");
  22293. EXPECT_TRUE(ws2.is_valid());
  22294. }
  22295. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22296. Server svr;
  22297. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22298. std::string msg;
  22299. while (ws.read(msg)) {}
  22300. });
  22301. auto port = svr.bind_to_any_port(HOST);
  22302. std::thread t([&]() { svr.listen_after_bind(); });
  22303. svr.wait_until_ready();
  22304. auto another_host = "example.com";
  22305. auto wrong_ip = "192.0.2.1";
  22306. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22307. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22308. ASSERT_TRUE(client.connect());
  22309. EXPECT_TRUE(client.is_open());
  22310. client.close();
  22311. svr.stop();
  22312. t.join();
  22313. }
  22314. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22315. Server svr;
  22316. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22317. std::string msg;
  22318. while (ws.read(msg)) {}
  22319. });
  22320. auto port = svr.bind_to_any_port(HOST);
  22321. std::thread t([&]() { svr.listen_after_bind(); });
  22322. svr.wait_until_ready();
  22323. auto wrong_ip = "192.0.2.1";
  22324. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22325. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22326. client.set_connection_timeout(1);
  22327. client.set_read_timeout(1);
  22328. client.set_write_timeout(1);
  22329. EXPECT_FALSE(client.connect());
  22330. EXPECT_FALSE(client.is_open());
  22331. svr.stop();
  22332. t.join();
  22333. }
  22334. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22335. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22336. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22337. // (RFC 6761) is only a map key and the Host header value.
  22338. auto host = "target.invalid";
  22339. Server svr;
  22340. std::string received_host;
  22341. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22342. received_host = req.get_header_value("Host");
  22343. std::string msg;
  22344. while (ws.read(msg)) {}
  22345. });
  22346. auto port = svr.bind_to_any_port(HOST);
  22347. std::thread t([&]() { svr.listen_after_bind(); });
  22348. // ASSERT_* below returns from the test body, which would leave t joinable
  22349. // and make ~thread call std::terminate.
  22350. auto se = detail::scope_exit([&] {
  22351. svr.stop();
  22352. if (t.joinable()) { t.join(); }
  22353. });
  22354. svr.wait_until_ready();
  22355. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22356. std::to_string(port) + "/ws");
  22357. client.set_hostname_addr_map({{host, HOST}});
  22358. ASSERT_TRUE(client.connect());
  22359. EXPECT_TRUE(client.is_open());
  22360. client.close();
  22361. svr.stop();
  22362. t.join();
  22363. // The mapping only redirects the connection; the identity stays host_.
  22364. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  22365. }
  22366. class WebSocketIntegrationTest : public ::testing::Test {
  22367. protected:
  22368. void SetUp() override {
  22369. server_ = httplib::detail::make_unique<Server>();
  22370. setup_server();
  22371. start_server();
  22372. }
  22373. void TearDown() override {
  22374. server_->stop();
  22375. if (server_thread_.joinable()) { server_thread_.join(); }
  22376. }
  22377. void setup_server() {
  22378. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22379. std::string msg;
  22380. ws::ReadResult ret;
  22381. while ((ret = ws.read(msg))) {
  22382. if (ret == ws::Binary) {
  22383. ws.send(msg.data(), msg.size());
  22384. } else {
  22385. ws.send(msg);
  22386. }
  22387. }
  22388. });
  22389. server_->WebSocket("/ws-echo-string",
  22390. [](const Request &, ws::WebSocket &ws) {
  22391. std::string msg;
  22392. while (ws.read(msg)) {
  22393. ws.send("echo: " + msg);
  22394. }
  22395. });
  22396. server_->WebSocket(
  22397. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22398. // Echo back request metadata
  22399. ws.send("path:" + req.path);
  22400. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22401. std::string msg;
  22402. while (ws.read(msg)) {}
  22403. });
  22404. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  22405. std::string msg;
  22406. ws.read(msg); // wait for a message
  22407. ws.close();
  22408. });
  22409. server_->WebSocket("/ws-close-status",
  22410. [](const Request &, ws::WebSocket &ws) {
  22411. std::string msg;
  22412. ws.read(msg); // wait for a message
  22413. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  22414. });
  22415. server_->WebSocket(
  22416. "/ws-subprotocol",
  22417. [](const Request &, ws::WebSocket &ws) {
  22418. std::string msg;
  22419. while (ws.read(msg)) {
  22420. ws.send(msg);
  22421. }
  22422. },
  22423. [](const std::vector<std::string> &protocols) -> std::string {
  22424. for (const auto &p : protocols) {
  22425. if (p == "graphql-ws") { return p; }
  22426. }
  22427. return "";
  22428. });
  22429. server_->WebSocket(
  22430. "/ws-subprotocol-unoffered",
  22431. [](const Request &, ws::WebSocket &ws) {
  22432. std::string msg;
  22433. while (ws.read(msg)) {
  22434. ws.send(msg);
  22435. }
  22436. },
  22437. [](const std::vector<std::string> &) -> std::string {
  22438. return "admin";
  22439. });
  22440. }
  22441. void start_server() {
  22442. port_ = server_->bind_to_any_port(HOST);
  22443. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22444. server_->wait_until_ready();
  22445. }
  22446. std::unique_ptr<Server> server_;
  22447. std::thread server_thread_;
  22448. int port_ = 0;
  22449. };
  22450. TEST_F(WebSocketIntegrationTest, TextEcho) {
  22451. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22452. "/ws-echo");
  22453. ASSERT_TRUE(client.connect());
  22454. ASSERT_TRUE(client.is_open());
  22455. ASSERT_TRUE(client.send("Hello WebSocket"));
  22456. std::string msg;
  22457. EXPECT_EQ(ws::Text, client.read(msg));
  22458. EXPECT_EQ("Hello WebSocket", msg);
  22459. client.close();
  22460. }
  22461. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  22462. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22463. "/ws-echo");
  22464. ASSERT_TRUE(client.connect());
  22465. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  22466. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  22467. std::string msg;
  22468. EXPECT_EQ(ws::Binary, client.read(msg));
  22469. EXPECT_EQ(binary_data, msg);
  22470. client.close();
  22471. }
  22472. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  22473. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22474. "/ws-echo");
  22475. ASSERT_TRUE(client.connect());
  22476. for (int i = 0; i < 10; i++) {
  22477. auto text = "message " + std::to_string(i);
  22478. ASSERT_TRUE(client.send(text));
  22479. std::string msg;
  22480. ASSERT_TRUE(client.read(msg));
  22481. EXPECT_EQ(text, msg);
  22482. }
  22483. client.close();
  22484. }
  22485. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22486. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22487. "/ws-close");
  22488. ASSERT_TRUE(client.connect());
  22489. // Send a message to trigger the server to close
  22490. ASSERT_TRUE(client.send("trigger close"));
  22491. // The server will close, so read should return false
  22492. std::string msg;
  22493. EXPECT_FALSE(client.read(msg));
  22494. EXPECT_FALSE(client.is_open());
  22495. }
  22496. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22497. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22498. "/ws-echo");
  22499. ASSERT_TRUE(client.connect());
  22500. // 128KB message
  22501. std::string large_data(128 * 1024, 'X');
  22502. ASSERT_TRUE(client.send(large_data));
  22503. std::string msg;
  22504. ASSERT_TRUE(client.read(msg));
  22505. EXPECT_EQ(large_data, msg);
  22506. client.close();
  22507. }
  22508. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22509. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22510. "/ws-echo");
  22511. ASSERT_TRUE(client.connect());
  22512. const int num_threads = 4;
  22513. std::vector<std::thread> threads;
  22514. std::atomic<int> send_count{0};
  22515. for (int t = 0; t < num_threads; t++) {
  22516. threads.emplace_back([&client, &send_count, t]() {
  22517. for (int i = 0; i < 5; i++) {
  22518. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22519. if (client.send(text)) { send_count++; }
  22520. }
  22521. });
  22522. }
  22523. for (auto &th : threads) {
  22524. th.join();
  22525. }
  22526. int received = 0;
  22527. std::string msg;
  22528. while (received < send_count.load()) {
  22529. if (!client.read(msg)) { break; }
  22530. received++;
  22531. }
  22532. EXPECT_EQ(send_count.load(), received);
  22533. client.close();
  22534. }
  22535. TEST_F(WebSocketIntegrationTest, ReadString) {
  22536. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22537. "/ws-echo-string");
  22538. ASSERT_TRUE(client.connect());
  22539. ASSERT_TRUE(client.send("hello"));
  22540. std::string msg;
  22541. ASSERT_TRUE(client.read(msg));
  22542. EXPECT_EQ("echo: hello", msg);
  22543. ASSERT_TRUE(client.send("world"));
  22544. ASSERT_TRUE(client.read(msg));
  22545. EXPECT_EQ("echo: world", msg);
  22546. client.close();
  22547. }
  22548. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22549. Headers headers = {{"X-Test-Header", "test-value"}};
  22550. ws::WebSocketClient client(
  22551. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22552. ASSERT_TRUE(client.connect());
  22553. std::string msg;
  22554. ASSERT_TRUE(client.read(msg));
  22555. EXPECT_EQ("path:/ws-request-info", msg);
  22556. ASSERT_TRUE(client.read(msg));
  22557. EXPECT_EQ("header:test-value", msg);
  22558. client.close();
  22559. }
  22560. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22561. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22562. "/ws-echo");
  22563. client.set_read_timeout(1, 0); // 1 second
  22564. ASSERT_TRUE(client.connect());
  22565. // Don't send anything — server echo handler waits for a message, so read()
  22566. // should time out. The connection survives it: nothing was consumed.
  22567. std::string msg;
  22568. EXPECT_EQ(client.read(msg), ws::Timeout);
  22569. EXPECT_TRUE(client.is_open());
  22570. // And it is still usable afterwards.
  22571. EXPECT_TRUE(client.send("after timeout"));
  22572. EXPECT_EQ(client.read(msg), ws::Text);
  22573. EXPECT_EQ(msg, "after timeout");
  22574. }
  22575. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22576. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22577. "/ws-echo");
  22578. client.set_read_timeout(1, 0);
  22579. ASSERT_TRUE(client.connect());
  22580. ASSERT_TRUE(client.send("first"));
  22581. std::string msg;
  22582. ASSERT_EQ(client.read(msg), ws::Text);
  22583. ASSERT_EQ(msg, "first");
  22584. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22585. // not be used with a read timeout: it would reprocess the previous message.
  22586. EXPECT_EQ(client.read(msg), ws::Timeout);
  22587. EXPECT_EQ(msg, "first");
  22588. }
  22589. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22590. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22591. "/ws-echo");
  22592. ASSERT_TRUE(client.connect());
  22593. // Setting it once the connection is open reaches the live stream, not just
  22594. // the seed for the next connect().
  22595. client.set_read_timeout(1, 0);
  22596. std::string msg;
  22597. EXPECT_EQ(client.read(msg), ws::Timeout);
  22598. EXPECT_TRUE(client.is_open());
  22599. }
  22600. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22601. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22602. "/ws-echo");
  22603. client.set_read_timeout(5, 0);
  22604. ASSERT_TRUE(client.connect());
  22605. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22606. // The server should reject it and close the connection.
  22607. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22608. client.send(oversized);
  22609. // The server's read() should have failed due to payload limit,
  22610. // so our read() should return false (connection closed).
  22611. std::string msg;
  22612. EXPECT_FALSE(client.read(msg));
  22613. }
  22614. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22615. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22616. "/ws-echo");
  22617. client.set_read_timeout(10, 0);
  22618. ASSERT_TRUE(client.connect());
  22619. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22620. // This should succeed.
  22621. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22622. ASSERT_TRUE(client.send(at_limit));
  22623. std::string msg;
  22624. ASSERT_TRUE(client.read(msg));
  22625. EXPECT_EQ(at_limit.size(), msg.size());
  22626. client.close();
  22627. }
  22628. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22629. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22630. "/nonexistent");
  22631. auto res = client.connect();
  22632. EXPECT_FALSE(res);
  22633. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22634. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22635. EXPECT_FALSE(client.is_open());
  22636. }
  22637. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22638. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22639. "/ws-echo");
  22640. ASSERT_TRUE(client.connect());
  22641. ASSERT_TRUE(client.send(""));
  22642. std::string msg;
  22643. EXPECT_EQ(ws::Text, client.read(msg));
  22644. EXPECT_EQ("", msg);
  22645. client.close();
  22646. }
  22647. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22648. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22649. "/ws-echo");
  22650. // First connection
  22651. ASSERT_TRUE(client.connect());
  22652. ASSERT_TRUE(client.send("first"));
  22653. std::string msg;
  22654. ASSERT_TRUE(client.read(msg));
  22655. EXPECT_EQ("first", msg);
  22656. client.close();
  22657. EXPECT_FALSE(client.is_open());
  22658. // Reconnect using the same client object
  22659. ASSERT_TRUE(client.connect());
  22660. ASSERT_TRUE(client.is_open());
  22661. ASSERT_TRUE(client.send("second"));
  22662. ASSERT_TRUE(client.read(msg));
  22663. EXPECT_EQ("second", msg);
  22664. client.close();
  22665. }
  22666. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22667. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22668. "/ws-close-status");
  22669. ASSERT_TRUE(client.connect());
  22670. // Trigger the server to close with GoingAway status
  22671. ASSERT_TRUE(client.send("trigger"));
  22672. // read() should return false after receiving the close frame
  22673. std::string msg;
  22674. EXPECT_FALSE(client.read(msg));
  22675. EXPECT_FALSE(client.is_open());
  22676. }
  22677. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22678. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22679. "/ws-echo");
  22680. ASSERT_TRUE(client.connect());
  22681. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22682. EXPECT_FALSE(client.is_open());
  22683. }
  22684. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22685. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22686. ws::WebSocketClient client(
  22687. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22688. ASSERT_TRUE(client.connect());
  22689. // Server should have selected graphql-ws
  22690. EXPECT_EQ("graphql-ws", client.subprotocol());
  22691. client.close();
  22692. }
  22693. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22694. Headers headers;
  22695. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22696. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22697. ws::WebSocketClient client(
  22698. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22699. ASSERT_TRUE(client.connect());
  22700. // The offer on the second field line counts too, so graphql-ws is selected
  22701. EXPECT_EQ("graphql-ws", client.subprotocol());
  22702. client.close();
  22703. }
  22704. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22705. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22706. ws::WebSocketClient client(
  22707. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22708. ASSERT_TRUE(client.connect());
  22709. // Server should not have selected any subprotocol
  22710. EXPECT_TRUE(client.subprotocol().empty());
  22711. client.close();
  22712. }
  22713. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22714. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22715. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22716. "/ws-subprotocol-unoffered",
  22717. headers);
  22718. ASSERT_TRUE(client.connect());
  22719. EXPECT_TRUE(client.subprotocol().empty());
  22720. client.close();
  22721. }
  22722. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22723. // Connect without requesting any subprotocol
  22724. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22725. "/ws-subprotocol");
  22726. ASSERT_TRUE(client.connect());
  22727. EXPECT_TRUE(client.subprotocol().empty());
  22728. client.close();
  22729. }
  22730. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22731. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22732. "/ws-echo");
  22733. client.set_tcp_nodelay(true);
  22734. client.set_connection_timeout(3, 0);
  22735. bool socket_options_called = false;
  22736. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22737. ASSERT_TRUE(client.connect());
  22738. ASSERT_TRUE(client.is_open());
  22739. EXPECT_TRUE(socket_options_called);
  22740. ASSERT_TRUE(client.send("hello"));
  22741. std::string msg;
  22742. auto result = client.read(msg);
  22743. EXPECT_EQ(result, ws::ReadResult::Text);
  22744. EXPECT_EQ(msg, "hello");
  22745. client.close();
  22746. }
  22747. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22748. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22749. "/ws-echo");
  22750. client.set_connection_timeout(std::chrono::seconds(3));
  22751. client.set_write_timeout(std::chrono::seconds(3));
  22752. // A sub-second remainder exercises the seconds/microseconds split.
  22753. client.set_read_timeout(std::chrono::milliseconds(1500));
  22754. ASSERT_TRUE(client.connect());
  22755. auto start = std::chrono::steady_clock::now();
  22756. std::string msg;
  22757. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22758. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22759. std::chrono::steady_clock::now() - start)
  22760. .count();
  22761. // Above 1s so that dropping the microseconds half of the split fails here.
  22762. // Ignoring the setter altogether would not reach this line at all: a client
  22763. // waits forever by default.
  22764. EXPECT_GE(elapsed, 1400);
  22765. EXPECT_LT(elapsed, 30000);
  22766. }
  22767. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22768. Server svr;
  22769. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22770. if (!req.has_header("Authorization")) {
  22771. res.status = StatusCode::Unauthorized_401;
  22772. res.set_content("Unauthorized", "text/plain");
  22773. return Server::HandlerResponse::Handled;
  22774. }
  22775. return Server::HandlerResponse::Unhandled;
  22776. });
  22777. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22778. std::string msg;
  22779. while (ws.read(msg)) {
  22780. ws.send(msg);
  22781. }
  22782. });
  22783. auto port = svr.bind_to_any_port("localhost");
  22784. std::thread t([&]() { svr.listen_after_bind(); });
  22785. svr.wait_until_ready();
  22786. // Without Authorization header - should be rejected before upgrade
  22787. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22788. EXPECT_FALSE(client1.connect());
  22789. // The rejection is framed like any other HTTP response
  22790. {
  22791. Client cli("localhost", port);
  22792. Headers headers = {{"Upgrade", "websocket"},
  22793. {"Connection", "Upgrade"},
  22794. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22795. {"Sec-WebSocket-Version", "13"}};
  22796. auto res = cli.Get("/ws", headers);
  22797. ASSERT_TRUE(res);
  22798. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22799. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22800. EXPECT_EQ("Unauthorized", res->body);
  22801. }
  22802. // With Authorization header - should succeed
  22803. Headers headers = {{"Authorization", "Bearer token123"}};
  22804. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22805. headers);
  22806. ASSERT_TRUE(client2.connect());
  22807. ASSERT_TRUE(client2.send("hello"));
  22808. std::string msg;
  22809. ASSERT_TRUE(client2.read(msg));
  22810. EXPECT_EQ("hello", msg);
  22811. client2.close();
  22812. svr.stop();
  22813. t.join();
  22814. }
  22815. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22816. Server svr;
  22817. std::atomic<int> pre_request_calls{0};
  22818. std::atomic<bool> route_matched{false};
  22819. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22820. pre_request_calls++;
  22821. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22822. if (req.get_header_value("Authorization") != "Bearer token123") {
  22823. res.status = StatusCode::Unauthorized_401;
  22824. res.set_content("Unauthorized", "text/plain");
  22825. return Server::HandlerResponse::Handled;
  22826. }
  22827. return Server::HandlerResponse::Unhandled;
  22828. });
  22829. std::atomic<bool> handler_called{false};
  22830. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22831. handler_called = true;
  22832. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22833. });
  22834. auto port = svr.bind_to_any_port("localhost");
  22835. std::thread t([&]() { svr.listen_after_bind(); });
  22836. svr.wait_until_ready();
  22837. // Without Authorization header - should be rejected before upgrade
  22838. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22839. "/ws/1");
  22840. EXPECT_FALSE(client1.connect());
  22841. EXPECT_FALSE(handler_called);
  22842. EXPECT_EQ(1, pre_request_calls);
  22843. EXPECT_TRUE(route_matched);
  22844. // The rejection is an ordinary HTTP response, not a protocol switch
  22845. {
  22846. Client cli("localhost", port);
  22847. Headers headers = {{"Upgrade", "websocket"},
  22848. {"Connection", "Upgrade"},
  22849. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22850. {"Sec-WebSocket-Version", "13"}};
  22851. auto res = cli.Get("/ws/1", headers);
  22852. ASSERT_TRUE(res);
  22853. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22854. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22855. EXPECT_EQ("Unauthorized", res->body);
  22856. }
  22857. EXPECT_FALSE(handler_called);
  22858. // With Authorization header - should succeed
  22859. Headers headers = {{"Authorization", "Bearer token123"}};
  22860. ws::WebSocketClient client2(
  22861. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22862. ASSERT_TRUE(client2.connect());
  22863. std::string msg;
  22864. ASSERT_TRUE(client2.read(msg));
  22865. EXPECT_EQ("/ws/:id 2", msg);
  22866. EXPECT_TRUE(handler_called);
  22867. client2.close();
  22868. svr.stop();
  22869. t.join();
  22870. }
  22871. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22872. Server svr;
  22873. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22874. // A read timeout is how a handler gets control back. Without it, a handler
  22875. // parked in read() can never write on the connection it is reading.
  22876. ws.set_read_timeout(std::chrono::milliseconds(100));
  22877. std::string msg;
  22878. while (ws.is_open()) {
  22879. auto r = ws.read(msg);
  22880. if (r == httplib::ws::Timeout) {
  22881. ws.send("tick");
  22882. continue;
  22883. }
  22884. if (r == httplib::ws::Fail) { break; }
  22885. ws.send(msg);
  22886. }
  22887. });
  22888. auto port = svr.bind_to_any_port("localhost");
  22889. std::thread t([&]() { svr.listen_after_bind(); });
  22890. svr.wait_until_ready();
  22891. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22892. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22893. ASSERT_TRUE(client.connect());
  22894. // The client sends nothing, so anything it receives came out of the
  22895. // handler's timeout path.
  22896. std::string msg;
  22897. ASSERT_EQ(client.read(msg), ws::Text);
  22898. EXPECT_EQ("tick", msg);
  22899. client.close();
  22900. svr.stop();
  22901. t.join();
  22902. }
  22903. // Stream::read may return fewer bytes than asked for. This is that contract at
  22904. // its worst -- one byte per call -- which is what a frame header straddling a
  22905. // read buffer's boundary looks like to the frame parser.
  22906. class WsByteAtATimeStream : public Stream {
  22907. public:
  22908. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22909. bool is_readable() const override { return true; }
  22910. bool wait_readable() const override { return true; }
  22911. bool wait_writable() const override { return true; }
  22912. ssize_t read(char *ptr, size_t size) override {
  22913. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22914. *ptr = data_[pos_++];
  22915. return 1;
  22916. }
  22917. ssize_t write(const char *, size_t size) override {
  22918. return static_cast<ssize_t>(size);
  22919. }
  22920. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22921. ip = "127.0.0.1";
  22922. port = 0;
  22923. }
  22924. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22925. ip = "127.0.0.1";
  22926. port = 0;
  22927. }
  22928. socket_t socket() const override { return INVALID_SOCKET; }
  22929. time_t duration() const override { return 0; }
  22930. private:
  22931. std::string data_;
  22932. size_t pos_ = 0;
  22933. };
  22934. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22935. // The payload uses the 16-bit extended length, so the header, the length
  22936. // and the mask key are all multi-byte fields here. Each used to be read
  22937. // with a single read() call, which fails as soon as one is split. The
  22938. // payload is also a little over one read chunk, so it is read in two.
  22939. std::string body;
  22940. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22941. body += static_cast<char>(i % 251);
  22942. }
  22943. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22944. std::string frame;
  22945. frame += static_cast<char>(0x81); // FIN + Text
  22946. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22947. frame += static_cast<char>(body.size() >> 8);
  22948. frame += static_cast<char>(body.size() & 0xff);
  22949. for (size_t i = 0; i < 4; i++) {
  22950. frame += static_cast<char>(mask[i]);
  22951. }
  22952. for (size_t i = 0; i < body.size(); i++) {
  22953. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22954. }
  22955. WsByteAtATimeStream strm(frame);
  22956. ws::Opcode opcode;
  22957. std::string payload;
  22958. bool fin = false;
  22959. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22960. /*expect_masked=*/true, body.size()),
  22961. ws::impl::FrameRead::Ok);
  22962. EXPECT_TRUE(fin);
  22963. EXPECT_EQ(opcode, ws::Opcode::Text);
  22964. EXPECT_EQ(payload, body);
  22965. }
  22966. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22967. std::string body(2000, 'x');
  22968. std::string frame;
  22969. frame += static_cast<char>(0x82); // FIN + Binary
  22970. frame += static_cast<char>(126); // 16-bit length follows
  22971. frame += static_cast<char>(body.size() >> 8);
  22972. frame += static_cast<char>(body.size() & 0xff);
  22973. frame += body;
  22974. detail::BufferStream strm;
  22975. strm.write(frame.data(), frame.size());
  22976. ws::Opcode opcode;
  22977. std::string payload;
  22978. bool fin;
  22979. EXPECT_EQ(
  22980. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22981. ws::impl::FrameRead::Ok);
  22982. EXPECT_EQ(body, payload);
  22983. }
  22984. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22985. // The header announces the largest payload allowed, and only 3 bytes of it
  22986. // ever arrive.
  22987. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22988. std::string frame;
  22989. frame += static_cast<char>(0x82); // FIN + Binary
  22990. frame += static_cast<char>(127); // 64-bit length follows
  22991. for (int shift = 56; shift >= 0; shift -= 8) {
  22992. frame += static_cast<char>((len >> shift) & 0xff);
  22993. }
  22994. frame += "abc";
  22995. detail::BufferStream strm;
  22996. strm.write(frame.data(), frame.size());
  22997. ws::Opcode opcode;
  22998. std::string payload;
  22999. bool fin;
  23000. EXPECT_EQ(
  23001. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23002. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23003. ws::impl::FrameRead::Fail);
  23004. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23005. }
  23006. TEST(WebSocketTest, QueryStringInHandshake) {
  23007. Server svr;
  23008. std::mutex mtx;
  23009. std::string received_target;
  23010. std::string received_token;
  23011. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23012. {
  23013. std::lock_guard<std::mutex> lock(mtx);
  23014. received_target = req.target;
  23015. if (req.has_param("token")) {
  23016. received_token = req.get_param_value("token");
  23017. }
  23018. }
  23019. std::string msg;
  23020. while (ws.read(msg)) {
  23021. ws.send(msg);
  23022. }
  23023. });
  23024. auto port = svr.bind_to_any_port("localhost");
  23025. std::thread t([&]() { svr.listen_after_bind(); });
  23026. svr.wait_until_ready();
  23027. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23028. "/ws?token=ABC&session=123");
  23029. ASSERT_TRUE(client.connect());
  23030. // Round-trip ensures the handler has run and captured the request.
  23031. ASSERT_TRUE(client.send("hello"));
  23032. std::string msg;
  23033. ASSERT_TRUE(client.read(msg));
  23034. EXPECT_EQ("hello", msg);
  23035. client.close();
  23036. {
  23037. std::lock_guard<std::mutex> lock(mtx);
  23038. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23039. EXPECT_EQ("ABC", received_token);
  23040. }
  23041. svr.stop();
  23042. t.join();
  23043. }
  23044. // Run a handshake against a throwaway server and hand the request the server
  23045. // received back to the caller, so tests can assert on the headers the client
  23046. // actually put on the wire.
  23047. static void capture_websocket_handshake_request(
  23048. const Headers &client_headers,
  23049. std::function<void(const Request &, int port)> verify) {
  23050. Server svr;
  23051. std::mutex mtx;
  23052. Request received;
  23053. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23054. {
  23055. std::lock_guard<std::mutex> lock(mtx);
  23056. received = req;
  23057. }
  23058. std::string msg;
  23059. while (ws.read(msg)) {
  23060. ws.send(msg);
  23061. }
  23062. });
  23063. auto port = svr.bind_to_any_port("localhost");
  23064. std::thread t([&]() { svr.listen_after_bind(); });
  23065. auto se = detail::scope_exit([&] {
  23066. svr.stop();
  23067. t.join();
  23068. });
  23069. svr.wait_until_ready();
  23070. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23071. client_headers);
  23072. ASSERT_TRUE(client.connect());
  23073. ASSERT_TRUE(client.send("hello"));
  23074. std::string msg;
  23075. ASSERT_TRUE(client.read(msg));
  23076. client.close();
  23077. {
  23078. std::lock_guard<std::mutex> lock(mtx);
  23079. verify(received, port);
  23080. }
  23081. }
  23082. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23083. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23084. // Non-default port must be present in the Host header. Default ports
  23085. // (80/443) are omitted; that logic is covered by
  23086. // MakeHostAndPortStringTest.
  23087. EXPECT_EQ("localhost:" + std::to_string(port),
  23088. req.get_header_value("Host"));
  23089. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23090. req.get_header_value("User-Agent"));
  23091. EXPECT_FALSE(req.has_header("Accept"));
  23092. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23093. EXPECT_FALSE(req.has_header("Content-Length"));
  23094. });
  23095. }
  23096. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23097. capture_websocket_handshake_request(
  23098. {{"Host", "example.com"},
  23099. {"User-Agent", "custom-agent"},
  23100. {"X-Custom", "value"}},
  23101. [](const Request &req, int) {
  23102. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23103. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23104. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23105. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23106. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23107. });
  23108. }
  23109. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23110. capture_websocket_handshake_request(
  23111. {{"Upgrade", "bogus"},
  23112. {"Connection", "close"},
  23113. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  23114. {"Sec-WebSocket-Version", "8"}},
  23115. [](const Request &req, int) {
  23116. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  23117. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  23118. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  23119. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  23120. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  23121. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  23122. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  23123. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  23124. req.get_header_value("Sec-WebSocket-Key"));
  23125. });
  23126. }
  23127. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  23128. // A header the client refuses to send must abort the handshake before any
  23129. // part of it reaches the wire; a lone request line would otherwise sit in
  23130. // the peer's buffer as a truncated request.
  23131. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  23132. ASSERT_NE(INVALID_SOCKET, srv);
  23133. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  23134. sockaddr_in addr{};
  23135. addr.sin_family = AF_INET;
  23136. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  23137. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23138. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23139. ASSERT_EQ(0, ::listen(srv, 1));
  23140. sockaddr_in bound{};
  23141. socklen_t bound_len = sizeof(bound);
  23142. ASSERT_EQ(
  23143. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23144. auto port = ntohs(bound.sin_port);
  23145. ssize_t received = -1;
  23146. std::thread t([&] {
  23147. // Bound every blocking call so a regression fails the test with a bad
  23148. // value instead of hanging the suite.
  23149. fd_set rfds;
  23150. FD_ZERO(&rfds);
  23151. FD_SET(srv, &rfds);
  23152. timeval tv{5, 0};
  23153. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23154. 0) {
  23155. return;
  23156. }
  23157. sockaddr_in cli_addr{};
  23158. socklen_t cli_len = sizeof(cli_addr);
  23159. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23160. if (cli == INVALID_SOCKET) { return; }
  23161. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23162. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23163. char buf[4096];
  23164. received = ::recv(cli, buf, sizeof(buf), 0);
  23165. });
  23166. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23167. // connect() has already shut the socket down by the time it returns false,
  23168. // so the peer sees EOF without waiting for the client to be destroyed.
  23169. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23170. {{"X-Bad", "a\r\nInjected: 1"}});
  23171. EXPECT_FALSE(client.connect());
  23172. t.join();
  23173. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23174. EXPECT_EQ(0, received);
  23175. }
  23176. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23177. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23178. // contains "upgrade" as a substring is a different token and must not
  23179. // start a WebSocket handshake.
  23180. auto make_request = [](const std::vector<std::string> &connection_values) {
  23181. Request req;
  23182. req.method = "GET";
  23183. req.headers.emplace("Upgrade", "websocket");
  23184. for (const auto &value : connection_values) {
  23185. req.headers.emplace("Connection", value);
  23186. }
  23187. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23188. req.headers.emplace("Sec-WebSocket-Version", "13");
  23189. return req;
  23190. };
  23191. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23192. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23193. EXPECT_TRUE(
  23194. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23195. EXPECT_TRUE(
  23196. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23197. EXPECT_TRUE(
  23198. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  23199. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  23200. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  23201. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  23202. EXPECT_FALSE(
  23203. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  23204. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  23205. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23206. }
  23207. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  23208. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  23209. // asks recipients to match each protocol-name case-insensitively, and RFC
  23210. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  23211. // client naming websocket alongside another protocol, or on a second field
  23212. // line, is offering websocket; a value that merely contains "websocket" as a
  23213. // substring is a different protocol name and is not.
  23214. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  23215. Request req;
  23216. req.method = "GET";
  23217. for (const auto &value : upgrade_values) {
  23218. req.headers.emplace("Upgrade", value);
  23219. }
  23220. req.headers.emplace("Connection", "Upgrade");
  23221. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23222. req.headers.emplace("Sec-WebSocket-Version", "13");
  23223. return req;
  23224. };
  23225. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  23226. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  23227. EXPECT_TRUE(
  23228. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  23229. EXPECT_TRUE(
  23230. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  23231. EXPECT_TRUE(
  23232. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  23233. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  23234. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  23235. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  23236. EXPECT_FALSE(
  23237. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  23238. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  23239. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23240. }
  23241. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  23242. Server svr;
  23243. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23244. auto port = svr.bind_to_any_port("localhost");
  23245. std::thread t([&]() { svr.listen_after_bind(); });
  23246. auto se = detail::scope_exit([&] {
  23247. svr.stop();
  23248. t.join();
  23249. });
  23250. svr.wait_until_ready();
  23251. Headers headers = {{"Upgrade", "websocket"},
  23252. {"Connection", "notupgrade"},
  23253. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23254. {"Sec-WebSocket-Version", "13"}};
  23255. Client cli("localhost", port);
  23256. auto res = cli.Get("/ws", headers);
  23257. // The route exists only as a WebSocket route, so a request that fails the
  23258. // handshake check falls through to ordinary routing.
  23259. ASSERT_TRUE(res);
  23260. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23261. }
  23262. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  23263. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  23264. // Connection value is the only thing left for the client to reject.
  23265. Server svr;
  23266. svr.Get("/ws", [](const Request &req, Response &res) {
  23267. res.status = StatusCode::SwitchingProtocol_101;
  23268. res.set_header("Upgrade", "websocket");
  23269. res.set_header("Connection", "notupgrade");
  23270. res.set_header("Sec-WebSocket-Accept",
  23271. detail::websocket_accept_key(
  23272. req.get_header_value("Sec-WebSocket-Key")));
  23273. });
  23274. auto port = svr.bind_to_any_port("localhost");
  23275. std::thread t([&]() { svr.listen_after_bind(); });
  23276. auto se = detail::scope_exit([&] {
  23277. svr.stop();
  23278. t.join();
  23279. });
  23280. svr.wait_until_ready();
  23281. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23282. auto res = client.connect();
  23283. EXPECT_FALSE(res);
  23284. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23285. EXPECT_FALSE(client.is_open());
  23286. }
  23287. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  23288. Server svr;
  23289. svr.Get("/ws", [](const Request &req, Response &res) {
  23290. res.status = StatusCode::SwitchingProtocol_101;
  23291. res.set_header("Upgrade", "websocket");
  23292. res.set_header("Connection", "Upgrade");
  23293. res.set_header("Sec-WebSocket-Accept",
  23294. detail::websocket_accept_key(
  23295. req.get_header_value("Sec-WebSocket-Key")));
  23296. res.set_header("Sec-WebSocket-Protocol", "admin");
  23297. });
  23298. auto port = svr.bind_to_any_port("localhost");
  23299. std::thread t([&]() { svr.listen_after_bind(); });
  23300. auto se = detail::scope_exit([&] {
  23301. svr.stop();
  23302. t.join();
  23303. });
  23304. svr.wait_until_ready();
  23305. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  23306. // Server selects a subprotocol the client never offered
  23307. {
  23308. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23309. ws::WebSocketClient client(url, headers);
  23310. auto res = client.connect();
  23311. EXPECT_FALSE(res);
  23312. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23313. EXPECT_FALSE(client.is_open());
  23314. EXPECT_TRUE(client.subprotocol().empty());
  23315. }
  23316. // Client offered none but the server named one anyway
  23317. {
  23318. ws::WebSocketClient client(url);
  23319. auto res = client.connect();
  23320. EXPECT_FALSE(res);
  23321. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23322. EXPECT_FALSE(client.is_open());
  23323. EXPECT_TRUE(client.subprotocol().empty());
  23324. }
  23325. }
  23326. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  23327. // The socket path doubles as the URL host, so it must not contain '/'.
  23328. const char *shard = getenv("GTEST_SHARD_INDEX");
  23329. const std::string sock_path =
  23330. shard ? std::string("httplib-ws-") + shard + ".sock"
  23331. : std::string("httplib-ws.sock");
  23332. std::remove(sock_path.c_str());
  23333. Server svr;
  23334. std::mutex mtx;
  23335. std::string received_host;
  23336. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23337. {
  23338. std::lock_guard<std::mutex> lock(mtx);
  23339. received_host = req.get_header_value("Host");
  23340. }
  23341. std::string msg;
  23342. while (ws.read(msg)) {
  23343. ws.send(msg);
  23344. }
  23345. });
  23346. svr.set_address_family(AF_UNIX);
  23347. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  23348. auto se = detail::scope_exit([&] {
  23349. svr.stop();
  23350. t.join();
  23351. std::remove(sock_path.c_str());
  23352. });
  23353. svr.wait_until_ready();
  23354. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  23355. client.set_address_family(AF_UNIX);
  23356. ASSERT_TRUE(client.connect());
  23357. ASSERT_TRUE(client.send("hello"));
  23358. std::string msg;
  23359. ASSERT_TRUE(client.read(msg));
  23360. client.close();
  23361. {
  23362. std::lock_guard<std::mutex> lock(mtx);
  23363. // There is no host:port for a Unix socket, so the same "localhost"
  23364. // placeholder the HTTP client uses is expected.
  23365. EXPECT_EQ("localhost", received_host);
  23366. }
  23367. }
  23368. // Two threads must never parse WebSocket frames from the same stream.
  23369. // close() used to read the peer's Close reply with its own frame read, so it
  23370. // raced a reader thread that was in the middle of a payload: the payload loop
  23371. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  23372. // so bytes taken by close() were replaced with bytes from further along the
  23373. // stream. The message kept its length and silently changed content.
  23374. //
  23375. // The raw peer below sends a frame header plus part of the payload, waits for
  23376. // the handler to call close(), and only then sends the rest. Whichever thread
  23377. // would win the race for those bytes, the message must arrive intact, because
  23378. // close() must not touch the stream while read() owns it.
  23379. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  23380. #ifndef _WIN32
  23381. signal(SIGPIPE, SIG_IGN);
  23382. #endif
  23383. const size_t payload_len = 120; // fits the 7-bit length field
  23384. const size_t prefix_len = 8;
  23385. const int attempts = 8;
  23386. std::string expected(payload_len, '\0');
  23387. for (size_t i = 0; i < payload_len; i++) {
  23388. expected[i] = static_cast<char>('a' + i % 26);
  23389. }
  23390. std::atomic<bool> peer_stalled{false};
  23391. std::atomic<bool> handler_done{false};
  23392. std::mutex received_mutex;
  23393. std::vector<std::string> received;
  23394. // Bound every wait, so a regression fails the test instead of hanging the
  23395. // suite.
  23396. auto wait_for = [](const std::atomic<bool> &flag) {
  23397. for (int i = 0; i < 500 && !flag; i++) {
  23398. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23399. }
  23400. };
  23401. Server svr;
  23402. svr.set_websocket_ping_interval(0);
  23403. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23404. std::thread reader([&]() {
  23405. std::string msg;
  23406. while (ws.read(msg)) {
  23407. std::lock_guard<std::mutex> guard(received_mutex);
  23408. received.push_back(msg);
  23409. }
  23410. });
  23411. // Wait until the peer stalls mid-payload, so the reader thread is parked
  23412. // inside read_websocket_frame() when close() runs.
  23413. wait_for(peer_stalled);
  23414. ws.close();
  23415. reader.join();
  23416. handler_done = true;
  23417. });
  23418. auto port = svr.bind_to_any_port("127.0.0.1");
  23419. std::thread t([&]() { svr.listen_after_bind(); });
  23420. auto se = detail::scope_exit([&] {
  23421. svr.stop();
  23422. t.join();
  23423. });
  23424. svr.wait_until_ready();
  23425. auto send_bytes = [](socket_t s, const std::string &data) {
  23426. #ifdef _WIN32
  23427. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  23428. #else
  23429. auto n = ::send(s, data.data(), data.size(), 0);
  23430. #endif
  23431. return n == static_cast<decltype(n)>(data.size());
  23432. };
  23433. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  23434. // Every length used here fits the 7-bit length field.
  23435. auto masked_header = [](uint8_t first_byte, size_t len) {
  23436. std::string h;
  23437. h += static_cast<char>(first_byte);
  23438. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  23439. h.append(4, '\0'); // mask key
  23440. return h;
  23441. };
  23442. for (int attempt = 0; attempt < attempts; attempt++) {
  23443. peer_stalled = false;
  23444. handler_done = false;
  23445. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23446. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  23447. auto se_sock = detail::scope_exit([&] {
  23448. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  23449. });
  23450. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23451. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  23452. sockaddr_in addr{};
  23453. addr.sin_family = AF_INET;
  23454. addr.sin_port = htons(static_cast<uint16_t>(port));
  23455. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23456. ASSERT_EQ(
  23457. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  23458. << "attempt " << attempt;
  23459. ASSERT_TRUE(send_bytes(sock,
  23460. "GET /ws HTTP/1.1\r\n"
  23461. "Host: 127.0.0.1\r\n"
  23462. "Upgrade: websocket\r\n"
  23463. "Connection: Upgrade\r\n"
  23464. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23465. "Sec-WebSocket-Version: 13\r\n"
  23466. "\r\n"))
  23467. << "attempt " << attempt;
  23468. std::string response;
  23469. while (response.find("\r\n\r\n") == std::string::npos) {
  23470. char buf[512];
  23471. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  23472. if (n <= 0) { break; }
  23473. response.append(buf, static_cast<size_t>(n));
  23474. }
  23475. ASSERT_NE(std::string::npos, response.find(" 101 "))
  23476. << "attempt " << attempt;
  23477. // Send the header of a Binary message but only the first prefix_len bytes
  23478. // of its payload, leaving the reader thread stalled inside the payload.
  23479. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  23480. expected.substr(0, prefix_len)))
  23481. << "attempt " << attempt;
  23482. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23483. peer_stalled = true;
  23484. // Let close() send its Close frame and park in its own read before the
  23485. // rest of the payload arrives, so both threads are waiting for it.
  23486. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23487. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23488. close_frame += static_cast<char>(0x03); // status 1000
  23489. close_frame += static_cast<char>(0xE8);
  23490. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23491. << "attempt " << attempt;
  23492. // Closing the peer releases the reader thread even on the buggy path,
  23493. // where it waits for bytes another thread already consumed.
  23494. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23495. detail::close_socket(sock);
  23496. sock = INVALID_SOCKET;
  23497. wait_for(handler_done);
  23498. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23499. }
  23500. std::lock_guard<std::mutex> guard(received_mutex);
  23501. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23502. << "a message in flight when close() ran was dropped";
  23503. for (size_t i = 0; i < received.size(); i++) {
  23504. EXPECT_EQ(expected, received[i]) << "message " << i;
  23505. }
  23506. }
  23507. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23508. // returning the socket, or INVALID_SOCKET.
  23509. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23510. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23511. if (sock == INVALID_SOCKET) { return sock; }
  23512. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23513. sockaddr_in addr{};
  23514. addr.sin_family = AF_INET;
  23515. addr.sin_port = htons(static_cast<uint16_t>(port));
  23516. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23517. std::string req = "GET " + path +
  23518. " HTTP/1.1\r\n"
  23519. "Host: 127.0.0.1\r\n"
  23520. "Upgrade: websocket\r\n"
  23521. "Connection: Upgrade\r\n"
  23522. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23523. "Sec-WebSocket-Version: 13\r\n"
  23524. "\r\n";
  23525. std::string res;
  23526. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23527. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  23528. static_cast<int>(req.size())) {
  23529. char c;
  23530. while (res.find("\r\n\r\n") == std::string::npos &&
  23531. ::recv(sock, &c, 1, 0) == 1) {
  23532. res += c;
  23533. }
  23534. }
  23535. if (res.find(" 101 ") == std::string::npos) {
  23536. detail::close_socket(sock);
  23537. return INVALID_SOCKET;
  23538. }
  23539. return sock;
  23540. }
  23541. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23542. // The payload must fit the 7-bit length field.
  23543. static std::string masked_frame(uint8_t first_byte,
  23544. const std::string &payload) {
  23545. std::string f;
  23546. f += static_cast<char>(first_byte);
  23547. f += static_cast<char>(0x80 | payload.size());
  23548. f.append(4, '\0');
  23549. return f + payload;
  23550. }
  23551. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23552. std::atomic<bool> done{false};
  23553. std::string received;
  23554. Server svr;
  23555. svr.set_websocket_ping_interval(0);
  23556. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23557. std::string msg;
  23558. if (ws.read(msg) == ws::Binary) { received = msg; }
  23559. done = true;
  23560. });
  23561. auto port = svr.bind_to_any_port("127.0.0.1");
  23562. std::thread t([&]() { svr.listen_after_bind(); });
  23563. auto se = detail::scope_exit([&] {
  23564. svr.stop();
  23565. t.join();
  23566. });
  23567. svr.wait_until_ready();
  23568. auto sock = connect_raw_websocket(port, "/ws");
  23569. ASSERT_NE(INVALID_SOCKET, sock);
  23570. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23571. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23572. masked_frame(0x89, "p") + // FIN + Ping
  23573. masked_frame(0x80, "lo"); // FIN + Continuation
  23574. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23575. for (int i = 0; i < 500 && !done; i++) {
  23576. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23577. }
  23578. ASSERT_TRUE(done);
  23579. EXPECT_EQ("Hello", received);
  23580. // The Ping between the fragments is answered with a Pong.
  23581. char pong[3];
  23582. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23583. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23584. }
  23585. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23586. Server svr;
  23587. svr.set_websocket_ping_interval(-1);
  23588. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23589. std::string msg;
  23590. while (ws.read(msg)) {}
  23591. });
  23592. auto port = svr.bind_to_any_port("127.0.0.1");
  23593. std::thread t([&]() { svr.listen_after_bind(); });
  23594. auto se = detail::scope_exit([&] {
  23595. svr.stop();
  23596. t.join();
  23597. });
  23598. svr.wait_until_ready();
  23599. auto sock = connect_raw_websocket(port, "/ws");
  23600. ASSERT_NE(INVALID_SOCKET, sock);
  23601. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23602. // Nothing comes while the client stays quiet.
  23603. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23604. char c;
  23605. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23606. }
  23607. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23608. Server svr;
  23609. svr.set_websocket_ping_interval(0);
  23610. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23611. std::string msg;
  23612. while (ws.read(msg)) {}
  23613. });
  23614. auto port = svr.bind_to_any_port("127.0.0.1");
  23615. std::thread t([&]() { svr.listen_after_bind(); });
  23616. auto se = detail::scope_exit([&] {
  23617. svr.stop();
  23618. t.join();
  23619. });
  23620. svr.wait_until_ready();
  23621. // Each Close payload and the reply it should get: an echo when valid, 1002
  23622. // otherwise.
  23623. std::vector<std::pair<std::string, std::string>> cases = {
  23624. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23625. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23626. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23627. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23628. };
  23629. // Also between the fragments of a message.
  23630. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23631. for (const auto &c : cases) {
  23632. auto sock = connect_raw_websocket(port, "/ws");
  23633. ASSERT_NE(INVALID_SOCKET, sock);
  23634. auto frames = prefix + masked_frame(0x88, c.first);
  23635. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23636. std::string reply;
  23637. char buf[256];
  23638. while (reply.size() < 2 + c.second.size()) {
  23639. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23640. if (n <= 0) { break; }
  23641. reply.append(buf, static_cast<size_t>(n));
  23642. }
  23643. detail::close_socket(sock);
  23644. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23645. c.second,
  23646. reply);
  23647. }
  23648. }
  23649. }
  23650. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23651. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23652. protected:
  23653. void SetUp() override {
  23654. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23655. SERVER_PRIVATE_KEY_FILE);
  23656. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23657. std::string msg;
  23658. ws::ReadResult ret;
  23659. while ((ret = ws.read(msg))) {
  23660. if (ret == ws::Binary) {
  23661. ws.send(msg.data(), msg.size());
  23662. } else {
  23663. ws.send(msg);
  23664. }
  23665. }
  23666. });
  23667. port_ = server_->bind_to_any_port(HOST);
  23668. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23669. server_->wait_until_ready();
  23670. }
  23671. void TearDown() override {
  23672. server_->stop();
  23673. if (server_thread_.joinable()) { server_thread_.join(); }
  23674. }
  23675. std::unique_ptr<SSLServer> server_;
  23676. std::thread server_thread_;
  23677. int port_ = 0;
  23678. };
  23679. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23680. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23681. {
  23682. ws::WebSocketClient client(url);
  23683. client.enable_server_certificate_verification(false);
  23684. auto calls = 0;
  23685. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23686. calls++;
  23687. return false;
  23688. });
  23689. EXPECT_FALSE(client.connect());
  23690. EXPECT_GT(calls, 0);
  23691. }
  23692. {
  23693. ws::WebSocketClient client(url);
  23694. client.enable_server_certificate_verification(false);
  23695. client.set_session_verifier([](tls::session_t) {
  23696. return SSLVerifierResponse::CertificateRejected;
  23697. });
  23698. EXPECT_FALSE(client.connect());
  23699. }
  23700. {
  23701. ws::WebSocketClient client(url);
  23702. client.enable_server_certificate_verification(false);
  23703. client.set_session_verifier([](tls::session_t) {
  23704. return SSLVerifierResponse::CertificateAccepted;
  23705. });
  23706. EXPECT_TRUE(client.connect());
  23707. }
  23708. }
  23709. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23710. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23711. "/ws-echo");
  23712. client.enable_server_certificate_verification(false);
  23713. ASSERT_TRUE(client.connect());
  23714. ASSERT_TRUE(client.is_open());
  23715. ASSERT_TRUE(client.send("Hello WSS"));
  23716. std::string msg;
  23717. EXPECT_EQ(ws::Text, client.read(msg));
  23718. EXPECT_EQ("Hello WSS", msg);
  23719. client.close();
  23720. }
  23721. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23722. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23723. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23724. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23725. // client (without calling close() first) is the only path that runs
  23726. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23727. // bug exactly.
  23728. //
  23729. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23730. // when linked against an instrumented libssl; run under Valgrind to catch it
  23731. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23732. // suite (the freed session otherwise stalls on the close handshake) — this test
  23733. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23734. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23735. {
  23736. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23737. "/ws-echo");
  23738. client.enable_server_certificate_verification(false);
  23739. client.set_read_timeout(2, 0);
  23740. client.set_write_timeout(2, 0);
  23741. ASSERT_TRUE(client.connect());
  23742. ASSERT_TRUE(client.is_open());
  23743. ASSERT_TRUE(client.send("still open"));
  23744. // Intentionally do NOT call client.close(): leaving scope runs
  23745. // shutdown_and_close() with the WebSocket still open, which must send the
  23746. // close frame while the TLS session is still alive.
  23747. }
  23748. }
  23749. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23750. // shutdown_and_close() at the start of connect(), reproducing the same
  23751. // use-after-free within the test body rather than at scope exit. The second
  23752. // connect must succeed and echo, proving the close handshake ran over a live
  23753. // session. See the note above about memory-tool requirements.
  23754. TEST_F(WebSocketSSLIntegrationTest,
  23755. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23756. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23757. "/ws-echo");
  23758. client.enable_server_certificate_verification(false);
  23759. client.set_read_timeout(2, 0);
  23760. client.set_write_timeout(2, 0);
  23761. ASSERT_TRUE(client.connect());
  23762. ASSERT_TRUE(client.is_open());
  23763. ASSERT_TRUE(client.send("still open"));
  23764. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23765. // the still-open connection, which must not touch a freed TLS session.
  23766. ASSERT_TRUE(client.connect());
  23767. ASSERT_TRUE(client.is_open());
  23768. ASSERT_TRUE(client.send("after reconnect"));
  23769. std::string msg;
  23770. EXPECT_EQ(ws::Text, client.read(msg));
  23771. EXPECT_EQ("after reconnect", msg);
  23772. client.close();
  23773. }
  23774. #endif
  23775. #ifdef CPPHTTPLIB_SSL_ENABLED
  23776. class WebSocketSSLCATest : public ::testing::Test {
  23777. protected:
  23778. void SetUp() override {
  23779. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23780. SERVER_PRIVATE_KEY_FILE);
  23781. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23782. std::string msg;
  23783. while (ws.read(msg)) {
  23784. ws.send(msg);
  23785. }
  23786. });
  23787. port_ = server_->bind_to_any_port("127.0.0.1");
  23788. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23789. server_->wait_until_ready();
  23790. }
  23791. void TearDown() override {
  23792. server_->stop();
  23793. if (server_thread_.joinable()) { server_thread_.join(); }
  23794. }
  23795. std::string url() const {
  23796. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23797. }
  23798. std::unique_ptr<SSLServer> server_;
  23799. std::thread server_thread_;
  23800. int port_ = 0;
  23801. };
  23802. // A custom CA loaded as PEM verifies the server with full certificate
  23803. // verification enabled
  23804. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23805. ws::WebSocketClient client(url());
  23806. std::string cert;
  23807. read_file(SERVER_CERT2_FILE, cert);
  23808. client.load_ca_cert_store(cert.c_str(), cert.size());
  23809. ASSERT_TRUE(client.connect());
  23810. ASSERT_TRUE(client.send("hello"));
  23811. std::string msg;
  23812. EXPECT_EQ(ws::Text, client.read(msg));
  23813. EXPECT_EQ("hello", msg);
  23814. client.close();
  23815. }
  23816. // A custom CA that does not cover the server must fail verification (the
  23817. // custom CA is exclusive; system certs are not loaded alongside it)
  23818. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23819. ws::WebSocketClient client(url());
  23820. std::string cert;
  23821. read_file(CLIENT_CA_CERT_FILE, cert);
  23822. client.load_ca_cert_store(cert.c_str(), cert.size());
  23823. auto res = client.connect();
  23824. ASSERT_FALSE(res);
  23825. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23826. EXPECT_EQ(-1, res.status());
  23827. EXPECT_NE(0u, res.ssl_backend_error());
  23828. }
  23829. // The same CA as a file path rather than PEM in memory
  23830. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23831. ws::WebSocketClient client(url());
  23832. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23833. ASSERT_TRUE(client.connect());
  23834. ASSERT_TRUE(client.send("hello"));
  23835. std::string msg;
  23836. EXPECT_EQ(ws::Text, client.read(msg));
  23837. EXPECT_EQ("hello", msg);
  23838. client.close();
  23839. }
  23840. // ...and a CA file that does not cover the server still fails, so it is the
  23841. // path above that decides the outcome
  23842. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23843. ws::WebSocketClient client(url());
  23844. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23845. ASSERT_FALSE(client.connect());
  23846. }
  23847. // Regression test: reconnecting with a native custom CA store used to reuse
  23848. // a store handle the previous TLS context had already freed (use-after-free
  23849. // under the OpenSSL backend). The context now lives as long as the client.
  23850. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23851. ws::WebSocketClient client(url());
  23852. std::string cert;
  23853. read_file(SERVER_CERT2_FILE, cert);
  23854. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23855. ASSERT_TRUE(client.connect());
  23856. client.close();
  23857. ASSERT_TRUE(client.connect());
  23858. ASSERT_TRUE(client.send("again"));
  23859. std::string msg;
  23860. EXPECT_EQ(ws::Text, client.read(msg));
  23861. EXPECT_EQ("again", msg);
  23862. client.close();
  23863. }
  23864. // Regression test: a certificate with a trusted chain but no identity match
  23865. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23866. // verification entirely for IP hosts, so this connection succeeded there.
  23867. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23868. // chain verification while the identity check must still fail.
  23869. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23870. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23871. ASSERT_TRUE(svr.is_valid());
  23872. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23873. std::string msg;
  23874. while (ws.read(msg)) {
  23875. ws.send(msg);
  23876. }
  23877. });
  23878. auto port = svr.bind_to_any_port("127.0.0.1");
  23879. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23880. auto se = detail::scope_exit([&] {
  23881. svr.stop();
  23882. t.join();
  23883. });
  23884. svr.wait_until_ready();
  23885. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23886. "/echo");
  23887. std::string cert;
  23888. read_file(SERVER_CERT_FILE, cert);
  23889. client.load_ca_cert_store(cert.c_str(), cert.size());
  23890. ASSERT_FALSE(client.connect());
  23891. }
  23892. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23893. // SNI, so nothing binds the host name to the TLS session. These bind the
  23894. // server to "localhost" instead, the only shape that exercises the SNI and
  23895. // hostname-verification path with certificate verification left enabled.
  23896. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23897. protected:
  23898. void Start(const char *cert_file) {
  23899. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23900. SERVER_PRIVATE_KEY_FILE);
  23901. ASSERT_TRUE(server_->is_valid());
  23902. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23903. std::string msg;
  23904. while (ws.read(msg)) {
  23905. ws.send(msg);
  23906. }
  23907. });
  23908. port_ = server_->bind_to_any_port("localhost");
  23909. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23910. server_->wait_until_ready();
  23911. }
  23912. void TearDown() override {
  23913. if (server_) { server_->stop(); }
  23914. if (server_thread_.joinable()) { server_thread_.join(); }
  23915. }
  23916. std::string url() const {
  23917. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23918. }
  23919. std::unique_ptr<SSLServer> server_;
  23920. std::thread server_thread_;
  23921. int port_ = 0;
  23922. };
  23923. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23924. // out and the connection is usable
  23925. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23926. Start(SERVER_CERT2_FILE);
  23927. ws::WebSocketClient client(url());
  23928. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23929. ASSERT_TRUE(client.connect());
  23930. ASSERT_TRUE(client.send("hello"));
  23931. std::string msg;
  23932. EXPECT_EQ(ws::Text, client.read(msg));
  23933. EXPECT_EQ("hello", msg);
  23934. client.close();
  23935. }
  23936. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23937. // while the identity check must still reject "localhost"
  23938. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23939. Start(SERVER_CERT_FILE);
  23940. ws::WebSocketClient client(url());
  23941. client.set_ca_cert_path(SERVER_CERT_FILE);
  23942. auto res = client.connect();
  23943. ASSERT_FALSE(res);
  23944. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23945. EXPECT_EQ(-1, res.status());
  23946. }
  23947. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23948. // disabled: the chain is still checked, only the identity check is skipped
  23949. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23950. Start(SERVER_CERT_FILE);
  23951. ws::WebSocketClient client(url());
  23952. client.set_ca_cert_path(SERVER_CERT_FILE);
  23953. client.enable_server_hostname_verification(false);
  23954. ASSERT_TRUE(client.connect());
  23955. ASSERT_TRUE(client.send("hello"));
  23956. std::string msg;
  23957. EXPECT_EQ(ws::Text, client.read(msg));
  23958. EXPECT_EQ("hello", msg);
  23959. client.close();
  23960. }
  23961. // A CA that did not sign the server certificate fails the chain, even though
  23962. // the name would match
  23963. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23964. Start(SERVER_CERT2_FILE);
  23965. ws::WebSocketClient client(url());
  23966. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23967. ASSERT_FALSE(client.connect());
  23968. }
  23969. // With verification disabled, neither the chain nor the name is checked
  23970. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23971. Start(SERVER_CERT_FILE);
  23972. ws::WebSocketClient client(url());
  23973. client.enable_server_certificate_verification(false);
  23974. ASSERT_TRUE(client.connect());
  23975. ASSERT_TRUE(client.send("hello"));
  23976. std::string msg;
  23977. EXPECT_EQ(ws::Text, client.read(msg));
  23978. EXPECT_EQ("hello", msg);
  23979. client.close();
  23980. }
  23981. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23982. protected:
  23983. void SetUp() override {
  23984. server_ = httplib::detail::make_unique<SSLServer>(
  23985. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23986. ASSERT_TRUE(server_->is_valid());
  23987. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23988. std::string msg;
  23989. while (ws.read(msg)) {
  23990. ws.send(msg);
  23991. }
  23992. });
  23993. port_ = server_->bind_to_any_port("localhost");
  23994. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23995. server_->wait_until_ready();
  23996. }
  23997. void TearDown() override {
  23998. server_->stop();
  23999. if (server_thread_.joinable()) { server_thread_.join(); }
  24000. }
  24001. std::string url() const {
  24002. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24003. }
  24004. void ConnectWithClientCert(const std::string &client_cert_file,
  24005. const std::string &client_private_key_file,
  24006. const char *private_key_password) {
  24007. std::string cert_pem, key_pem;
  24008. read_file(client_cert_file, cert_pem);
  24009. read_file(client_private_key_file, key_pem);
  24010. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24011. key_pem.c_str(), key_pem.size(),
  24012. private_key_password};
  24013. ws::WebSocketClient client(url(), pem);
  24014. ASSERT_TRUE(client.is_valid());
  24015. client.enable_server_certificate_verification(false);
  24016. ASSERT_TRUE(client.connect());
  24017. ASSERT_TRUE(client.send("hello"));
  24018. std::string msg;
  24019. EXPECT_EQ(ws::Text, client.read(msg));
  24020. EXPECT_EQ("hello", msg);
  24021. client.close();
  24022. }
  24023. std::unique_ptr<SSLServer> server_;
  24024. std::thread server_thread_;
  24025. int port_ = 0;
  24026. };
  24027. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24028. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24029. }
  24030. // Control for the tests above: the fixture's server really does require a
  24031. // client certificate, so it is the PEM the constructor installed that decides
  24032. // the outcome.
  24033. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24034. ws::WebSocketClient client(url());
  24035. ASSERT_TRUE(client.is_valid());
  24036. client.enable_server_certificate_verification(false);
  24037. EXPECT_FALSE(client.connect());
  24038. }
  24039. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24040. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24041. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24042. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24043. }
  24044. #endif
  24045. #if !defined(_WIN32)
  24046. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  24047. auto secret_dir = std::string("./symlink_test_secret");
  24048. auto served_dir = std::string("./symlink_test_served");
  24049. auto secret_file = secret_dir + "/secret.txt";
  24050. auto symlink_path = served_dir + "/escape";
  24051. // Setup: create directories and files
  24052. mkdir(secret_dir.c_str(), 0755);
  24053. mkdir(served_dir.c_str(), 0755);
  24054. {
  24055. std::ofstream ofs(secret_file);
  24056. ofs << "SECRET_DATA";
  24057. }
  24058. // Create symlink using absolute path so it resolves correctly
  24059. #ifdef PATH_MAX
  24060. char abs_secret[PATH_MAX];
  24061. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  24062. #else
  24063. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  24064. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  24065. ASSERT_NE(nullptr, abs_secret);
  24066. #endif
  24067. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  24068. auto se = detail::scope_exit([&] {
  24069. unlink(symlink_path.c_str());
  24070. unlink(secret_file.c_str());
  24071. rmdir(served_dir.c_str());
  24072. rmdir(secret_dir.c_str());
  24073. });
  24074. Server svr;
  24075. svr.set_mount_point("/", served_dir);
  24076. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  24077. auto se2 = detail::scope_exit([&] {
  24078. svr.stop();
  24079. listen_thread.join();
  24080. });
  24081. svr.wait_until_ready();
  24082. Client cli("localhost", PORT);
  24083. // Symlink pointing outside base dir should be blocked
  24084. auto res = cli.Get("/escape/secret.txt");
  24085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24086. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  24087. }
  24088. #endif
  24089. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  24090. // "GET /smuggled" request), reads the first response, and only then sends the
  24091. // embedded request as the body. Returns how many times /smuggled ran.
  24092. //
  24093. // The body is sent AFTER receiving the first response (as in the original
  24094. // PoC) so that the stream_line_reader cannot buffer it together with the
  24095. // headers of the first request.
  24096. static int count_smuggled_requests(const std::string &outer_head,
  24097. std::string &first_response) {
  24098. Server svr;
  24099. svr.set_mount_point("/", "./www");
  24100. std::atomic<int> smuggled_count(0);
  24101. svr.Get("/smuggled", [&](const Request &, Response &res) {
  24102. smuggled_count++;
  24103. res.set_content("oops", "text/plain");
  24104. });
  24105. svr.Post("/post", [&](const Request &req, Response &res) {
  24106. res.set_content(req.body, "text/plain");
  24107. });
  24108. auto port = svr.bind_to_any_port("localhost");
  24109. thread t = thread([&] { svr.listen_after_bind(); });
  24110. auto se = detail::scope_exit([&] {
  24111. svr.stop();
  24112. t.join();
  24113. });
  24114. svr.wait_until_ready();
  24115. auto error = Error::Success;
  24116. auto sock = detail::create_client_socket(
  24117. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  24118. /*connection_timeout_sec=*/2, 0,
  24119. /*read_timeout_sec=*/2, 0,
  24120. /*write_timeout_sec=*/2, 0, std::string(), error);
  24121. EXPECT_NE(INVALID_SOCKET, sock);
  24122. if (sock == INVALID_SOCKET) { return -1; }
  24123. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24124. // The "smuggled" request will be sent as the body of the outer request
  24125. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  24126. "Host: localhost\r\n"
  24127. "Connection: close\r\n"
  24128. "\r\n";
  24129. auto head = outer_head;
  24130. auto len = std::to_string(smuggled.size());
  24131. for (auto pos = head.find("{len}"); pos != std::string::npos;
  24132. pos = head.find("{len}", pos + len.size())) {
  24133. head.replace(pos, 5, len);
  24134. }
  24135. // Step 1: Send only the outer request headers (no body yet)
  24136. auto sent = send(sock, head.data(), head.size(), 0);
  24137. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  24138. // Step 2: Read the first response
  24139. char buf[4096];
  24140. for (;;) {
  24141. auto n = recv(sock, buf, sizeof(buf), 0);
  24142. if (n <= 0) break;
  24143. first_response.append(buf, static_cast<size_t>(n));
  24144. // Stop once we have a complete response (headers + body)
  24145. auto hdr_end = first_response.find("\r\n\r\n");
  24146. if (hdr_end != std::string::npos) {
  24147. // Check for Content-Length to know when the body is complete
  24148. auto cl_pos = first_response.find("Content-Length:");
  24149. if (cl_pos != std::string::npos) {
  24150. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  24151. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  24152. auto cl = std::stoul(
  24153. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  24154. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  24155. } else {
  24156. break; // No Content-Length, assume headers-only response
  24157. }
  24158. }
  24159. }
  24160. // Step 3: Now send the body, which looks like a new HTTP request. On a
  24161. // vulnerable server the keep-alive loop reads this as a second request. The
  24162. // server may already have closed the connection, so the result is ignored.
  24163. send(sock, smuggled.data(), smuggled.size(), 0);
  24164. // Half-close so that a server which drained the body sees EOF and closes,
  24165. // instead of the read below waiting for the read timeout.
  24166. #ifdef _WIN32
  24167. ::shutdown(sock, SD_SEND);
  24168. #else
  24169. ::shutdown(sock, SHUT_WR);
  24170. #endif
  24171. // Step 4: Read until the server closes the connection
  24172. for (;;) {
  24173. auto n = recv(sock, buf, sizeof(buf), 0);
  24174. if (n <= 0) break;
  24175. }
  24176. return smuggled_count.load();
  24177. }
  24178. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  24179. // A GET request with Content-Length to a static file handler must have its
  24180. // body drained before the keep-alive connection is reused. Otherwise the
  24181. // unread body bytes are interpreted as the next HTTP request.
  24182. std::string first_response;
  24183. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24184. "Host: localhost\r\n"
  24185. "Content-Length: {len}\r\n"
  24186. "\r\n",
  24187. first_response));
  24188. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  24189. }
  24190. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  24191. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  24192. // be answered with 400 and the connection closed. Treating it as "no body"
  24193. // leaves the body to be parsed as the next request.
  24194. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  24195. const char *targets[] = {
  24196. "GET /file", // handler that never reads the body
  24197. "GET /not-found", // no handler matches (404)
  24198. "POST /post", // handler that reads the body
  24199. };
  24200. for (auto target : targets) {
  24201. for (auto value : values) {
  24202. std::string first_response;
  24203. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  24204. " HTTP/1.1\r\n"
  24205. "Host: localhost\r\n"
  24206. "Content-Length: " +
  24207. value + "\r\n\r\n",
  24208. first_response))
  24209. << target << " with Content-Length: " << value;
  24210. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  24211. << target << " with Content-Length: " << value;
  24212. }
  24213. }
  24214. }
  24215. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  24216. // A 400 for an unparseable request line leaves the rest of the message
  24217. // unread, so the connection must be closed rather than reused.
  24218. std::string first_response;
  24219. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  24220. "Host: localhost\r\n"
  24221. "Content-Length: {len}\r\n"
  24222. "\r\n",
  24223. first_response));
  24224. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24225. }
  24226. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  24227. // Same as above for a header block that fails to parse.
  24228. std::string first_response;
  24229. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24230. "Host: localhost\r\n"
  24231. "Bad Header\r\n"
  24232. "Content-Length: {len}\r\n"
  24233. "\r\n",
  24234. first_response));
  24235. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24236. }
  24237. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  24238. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  24239. // server must not read another request on that connection, even when the
  24240. // request had no body to drain.
  24241. std::string first_response;
  24242. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  24243. "Host: localhost\r\n"
  24244. "\r\n",
  24245. first_response));
  24246. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  24247. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  24248. }
  24249. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  24250. // A content reader that stops early leaves the stream inside the body.
  24251. // Draining the whole Content-Length from there, or reading the body again,
  24252. // reads into the next request, and whatever follows is parsed as a request
  24253. // of its own.
  24254. Server svr;
  24255. std::atomic<int> smuggled_count(0);
  24256. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  24257. svr.Post("/upload", [](const Request &req, Response &res,
  24258. const ContentReader &content_reader) {
  24259. // Stop at the last chunk, so the whole body has been read however it
  24260. // arrives.
  24261. auto length = req.get_header_value_u64("Content-Length");
  24262. size_t total = 0;
  24263. auto consumed = content_reader([&](const char *, size_t n) {
  24264. total += n;
  24265. return total < length;
  24266. });
  24267. EXPECT_FALSE(consumed);
  24268. if (req.has_param("retry")) {
  24269. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  24270. }
  24271. // Replace the 400 the aborted read set, which would close the connection.
  24272. res.set_redirect("/done");
  24273. });
  24274. auto port = svr.bind_to_any_port(HOST);
  24275. thread t = thread([&] { svr.listen_after_bind(); });
  24276. auto se = detail::scope_exit([&] {
  24277. svr.stop();
  24278. t.join();
  24279. });
  24280. svr.wait_until_ready();
  24281. // A front end sees the second request as a POST whose body is the GET. The
  24282. // first body is as long as the POST's headers, so draining it again reads
  24283. // exactly those and leaves the GET to be parsed next.
  24284. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  24285. "Host: localhost\r\n"
  24286. "\r\n";
  24287. std::string second_head = "POST /post HTTP/1.1\r\n"
  24288. "Host: localhost\r\n"
  24289. "Content-Length: " +
  24290. std::to_string(inner.size()) +
  24291. "\r\n"
  24292. "\r\n";
  24293. for (auto target : {"/upload", "/upload?retry"}) {
  24294. smuggled_count = 0;
  24295. std::string request = "POST " + std::string(target) +
  24296. " HTTP/1.1\r\n"
  24297. "Host: localhost\r\n"
  24298. "Content-Length: " +
  24299. std::to_string(second_head.size()) +
  24300. "\r\n"
  24301. "\r\n" +
  24302. std::string(second_head.size(), 'A') + second_head +
  24303. inner;
  24304. std::string response;
  24305. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  24306. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  24307. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  24308. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  24309. EXPECT_EQ(0, smuggled_count.load()) << target;
  24310. }
  24311. }
  24312. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  24313. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  24314. // must be rejected with 400 Bad Request.
  24315. Server svr;
  24316. svr.Post("/test", [&](const Request &, Response &res) {
  24317. res.set_content("ok", "text/plain");
  24318. });
  24319. thread t = thread([&] { svr.listen(HOST, PORT); });
  24320. auto se = detail::scope_exit([&] {
  24321. svr.stop();
  24322. t.join();
  24323. ASSERT_FALSE(svr.is_running());
  24324. });
  24325. svr.wait_until_ready();
  24326. // Exact "chunked"
  24327. {
  24328. auto req = "POST /test HTTP/1.1\r\n"
  24329. "Host: localhost\r\n"
  24330. "Content-Length: 5\r\n"
  24331. "Transfer-Encoding: chunked\r\n"
  24332. "Connection: close\r\n"
  24333. "\r\n"
  24334. "hello";
  24335. std::string response;
  24336. ASSERT_TRUE(send_request(1, req, &response));
  24337. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24338. response.substr(0, response.find("\r\n")));
  24339. }
  24340. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  24341. {
  24342. auto req = "POST /test HTTP/1.1\r\n"
  24343. "Host: localhost\r\n"
  24344. "Content-Length: 5\r\n"
  24345. "Transfer-Encoding: gzip, chunked\r\n"
  24346. "Connection: close\r\n"
  24347. "\r\n"
  24348. "hello";
  24349. std::string response;
  24350. ASSERT_TRUE(send_request(1, req, &response));
  24351. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24352. response.substr(0, response.find("\r\n")));
  24353. }
  24354. }
  24355. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  24356. Server svr;
  24357. svr.Post("/test", [&](const Request &, Response &res) {
  24358. res.set_content("ok", "text/plain");
  24359. });
  24360. thread t = thread([&] { svr.listen(HOST, PORT); });
  24361. auto se = detail::scope_exit([&] {
  24362. svr.stop();
  24363. t.join();
  24364. ASSERT_FALSE(svr.is_running());
  24365. });
  24366. svr.wait_until_ready();
  24367. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  24368. // length cannot be determined, so the server must answer 400 and close
  24369. // rather than treat the request as bodyless and leave the body in the
  24370. // socket for the next request to pick up.
  24371. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  24372. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  24373. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  24374. std::string response;
  24375. ASSERT_TRUE(send_request(1, req, &response));
  24376. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24377. response.substr(0, response.find("\r\n")))
  24378. << transfer_encoding;
  24379. }
  24380. // RFC 9110 5.3: the codings may also be split across several
  24381. // Transfer-Encoding lines, which combine in the order they were received.
  24382. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  24383. // just like the single-line "chunked, gzip" above.
  24384. {
  24385. auto req = "POST /test HTTP/1.1\r\n"
  24386. "Host: localhost\r\n"
  24387. "Transfer-Encoding: chunked\r\n"
  24388. "Transfer-Encoding: gzip\r\n"
  24389. "\r\n"
  24390. "0\r\n\r\n";
  24391. std::string response;
  24392. ASSERT_TRUE(send_request(1, req, &response));
  24393. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24394. response.substr(0, response.find("\r\n")));
  24395. }
  24396. // A sequence ending in chunked stays valid.
  24397. auto req = "POST /test HTTP/1.1\r\n"
  24398. "Host: localhost\r\n"
  24399. "Transfer-Encoding: gzip, chunked\r\n"
  24400. "Connection: close\r\n"
  24401. "\r\n"
  24402. "0\r\n\r\n";
  24403. std::string response;
  24404. ASSERT_TRUE(send_request(1, req, &response));
  24405. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  24406. // ...including when it is spread over several lines.
  24407. auto split_req = "POST /test HTTP/1.1\r\n"
  24408. "Host: localhost\r\n"
  24409. "Transfer-Encoding: gzip\r\n"
  24410. "Transfer-Encoding: chunked\r\n"
  24411. "Connection: close\r\n"
  24412. "\r\n"
  24413. "0\r\n\r\n";
  24414. std::string split_response;
  24415. ASSERT_TRUE(send_request(1, split_req, &split_response));
  24416. EXPECT_EQ("HTTP/1.1 200 OK",
  24417. split_response.substr(0, split_response.find("\r\n")));
  24418. }
  24419. // Regression for issue #2450: a DELETE without Content-Length on a
  24420. // keep-alive connection must not let the post-response drain consume the
  24421. // next request's bytes.
  24422. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  24423. Server svr;
  24424. std::atomic<int> delete_count(0);
  24425. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  24426. delete_count++;
  24427. res.status = StatusCode::NoContent_204;
  24428. });
  24429. auto port = svr.bind_to_any_port(HOST);
  24430. thread t = thread([&] { svr.listen_after_bind(); });
  24431. auto se = detail::scope_exit([&] {
  24432. svr.stop();
  24433. t.join();
  24434. });
  24435. svr.wait_until_ready();
  24436. auto error = Error::Success;
  24437. auto sock = detail::create_client_socket(
  24438. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24439. /*connection_timeout_sec=*/2, 0,
  24440. /*read_timeout_sec=*/2, 0,
  24441. /*write_timeout_sec=*/2, 0, std::string(), error);
  24442. ASSERT_NE(INVALID_SOCKET, sock);
  24443. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24444. auto send_request_and_read_response = [&](const std::string &req,
  24445. std::string &out) -> bool {
  24446. auto sent = send(sock, req.data(), req.size(), 0);
  24447. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  24448. char buf[4096];
  24449. for (;;) {
  24450. auto n = recv(sock, buf, sizeof(buf), 0);
  24451. if (n <= 0) { return !out.empty(); }
  24452. out.append(buf, static_cast<size_t>(n));
  24453. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  24454. }
  24455. };
  24456. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  24457. "Host: localhost\r\n"
  24458. "\r\n";
  24459. std::string resp1;
  24460. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  24461. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  24462. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  24463. "Host: localhost\r\n"
  24464. "Connection: close\r\n"
  24465. "\r\n";
  24466. std::string resp2;
  24467. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  24468. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  24469. EXPECT_EQ(2, delete_count.load());
  24470. }
  24471. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  24472. Server svr;
  24473. svr.Post("/ingest", [&](const Request &, Response &res,
  24474. const ContentReader &content_reader) {
  24475. auto consumed = content_reader([](const char *, size_t) { return false; });
  24476. EXPECT_FALSE(consumed);
  24477. res.status = StatusCode::Conflict_409;
  24478. res.set_header("Connection", "close");
  24479. });
  24480. auto port = svr.bind_to_any_port(HOST);
  24481. thread t = thread([&] { svr.listen_after_bind(); });
  24482. auto se = detail::scope_exit([&] {
  24483. svr.stop();
  24484. t.join();
  24485. });
  24486. svr.wait_until_ready();
  24487. auto error = Error::Success;
  24488. auto sock = detail::create_client_socket(
  24489. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24490. /*connection_timeout_sec=*/2, 0,
  24491. /*read_timeout_sec=*/1, 0,
  24492. /*write_timeout_sec=*/2, 0, std::string(), error);
  24493. ASSERT_NE(INVALID_SOCKET, sock);
  24494. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24495. std::string request = "POST /ingest HTTP/1.1\r\n"
  24496. "Host: localhost\r\n"
  24497. "Transfer-Encoding: chunked\r\n"
  24498. "\r\n"
  24499. "4\r\n"
  24500. "data\r\n";
  24501. auto sent = send(sock, request.data(), request.size(), 0);
  24502. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24503. std::string response;
  24504. ssize_t received = 0;
  24505. do {
  24506. char buf[4096];
  24507. received = recv(sock, buf, sizeof(buf), 0);
  24508. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24509. } while (received > 0);
  24510. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24511. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24512. EXPECT_EQ(0, received);
  24513. }
  24514. namespace no_proxy_test {
  24515. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24516. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24517. // calling listen().
  24518. class ScopedServer {
  24519. public:
  24520. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24521. ~ScopedServer() {
  24522. svr_.stop();
  24523. if (th_.joinable()) { th_.join(); }
  24524. }
  24525. Server &svr() { return svr_; }
  24526. int port() const { return port_; }
  24527. void listen() {
  24528. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24529. svr_.wait_until_ready();
  24530. }
  24531. private:
  24532. Server svr_;
  24533. std::thread th_;
  24534. int port_ = 0;
  24535. };
  24536. class ProxyAndTargetServers {
  24537. public:
  24538. ProxyAndTargetServers() {
  24539. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24540. proxy_hits_++;
  24541. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24542. res.set_content("via-proxy", "text/plain");
  24543. });
  24544. target_.Get(".*", [this](const Request &req, Response &res) {
  24545. target_hits_++;
  24546. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24547. res.set_content("direct", "text/plain");
  24548. });
  24549. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24550. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24551. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24552. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24553. proxy_mock_.wait_until_ready();
  24554. target_.wait_until_ready();
  24555. }
  24556. ~ProxyAndTargetServers() {
  24557. proxy_mock_.stop();
  24558. target_.stop();
  24559. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24560. if (target_thread_.joinable()) { target_thread_.join(); }
  24561. }
  24562. Server &proxy_mock() { return proxy_mock_; }
  24563. Server &target() { return target_; }
  24564. int proxy_port() const { return proxy_port_; }
  24565. int target_port() const { return target_port_; }
  24566. int proxy_hits() const { return proxy_hits_.load(); }
  24567. int target_hits() const { return target_hits_.load(); }
  24568. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24569. void reset_counters() {
  24570. proxy_hits_ = 0;
  24571. target_hits_ = 0;
  24572. last_had_proxy_authz_ = false;
  24573. }
  24574. private:
  24575. Server proxy_mock_;
  24576. Server target_;
  24577. std::thread proxy_thread_;
  24578. std::thread target_thread_;
  24579. int proxy_port_ = 0;
  24580. int target_port_ = 0;
  24581. std::atomic<int> proxy_hits_{0};
  24582. std::atomic<int> target_hits_{0};
  24583. std::atomic<bool> last_had_proxy_authz_{false};
  24584. };
  24585. inline std::unique_ptr<Client> make_client(const std::string &host,
  24586. ProxyAndTargetServers &s) {
  24587. auto cli = detail::make_unique<Client>(host, s.target_port());
  24588. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24589. cli->set_proxy("127.0.0.1", s.proxy_port());
  24590. return cli;
  24591. }
  24592. } // namespace no_proxy_test
  24593. using no_proxy_test::make_client;
  24594. using no_proxy_test::ProxyAndTargetServers;
  24595. TEST(NoProxyTest, ExactHostnameBypasses) {
  24596. ProxyAndTargetServers s;
  24597. auto cli = make_client("example.com", s);
  24598. cli->set_no_proxy({"example.com"});
  24599. auto res = cli->Get("/");
  24600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24601. EXPECT_EQ(0, s.proxy_hits());
  24602. EXPECT_EQ(1, s.target_hits());
  24603. }
  24604. TEST(NoProxyTest, SubdomainBypasses) {
  24605. ProxyAndTargetServers s;
  24606. auto cli = make_client("foo.example.com", s);
  24607. cli->set_no_proxy({"example.com"});
  24608. auto res = cli->Get("/");
  24609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24610. EXPECT_EQ(0, s.proxy_hits());
  24611. EXPECT_EQ(1, s.target_hits());
  24612. }
  24613. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24614. // Regression guard: "evilexample.com" must not be considered a subdomain
  24615. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24616. // check would let traffic bypass the proxy and leak credentials direct
  24617. // to the attacker host.
  24618. ProxyAndTargetServers s;
  24619. auto cli = make_client("evilexample.com", s);
  24620. cli->set_no_proxy({"example.com"});
  24621. auto res = cli->Get("/");
  24622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24623. EXPECT_GE(s.proxy_hits(), 1);
  24624. EXPECT_EQ(0, s.target_hits());
  24625. }
  24626. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24627. ProxyAndTargetServers s;
  24628. auto cli = make_client("example.com.evil.com", s);
  24629. cli->set_no_proxy({"example.com"});
  24630. auto res = cli->Get("/");
  24631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24632. EXPECT_GE(s.proxy_hits(), 1);
  24633. EXPECT_EQ(0, s.target_hits());
  24634. }
  24635. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24636. ProxyAndTargetServers s;
  24637. auto cli = make_client("example.com", s);
  24638. cli->set_no_proxy({".example.com"});
  24639. auto res = cli->Get("/");
  24640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24641. EXPECT_EQ(0, s.proxy_hits());
  24642. EXPECT_EQ(1, s.target_hits());
  24643. }
  24644. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24645. ProxyAndTargetServers s;
  24646. auto cli = make_client("Example.COM", s);
  24647. cli->set_no_proxy({"EXAMPLE.com"});
  24648. auto res = cli->Get("/");
  24649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24650. EXPECT_EQ(0, s.proxy_hits());
  24651. EXPECT_EQ(1, s.target_hits());
  24652. }
  24653. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24654. ProxyAndTargetServers s;
  24655. auto cli = make_client("example.com.", s);
  24656. cli->set_no_proxy({"example.com"});
  24657. auto res = cli->Get("/");
  24658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24659. EXPECT_EQ(0, s.proxy_hits());
  24660. EXPECT_EQ(1, s.target_hits());
  24661. }
  24662. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24663. // Trailing dots must be normalized on BOTH sides — host and entry.
  24664. // An implementation that only strips the host-side trailing dot would
  24665. // fail to match host "example.com" against entry "example.com." because
  24666. // a literal substring search would compare 11 chars against 12.
  24667. ProxyAndTargetServers s;
  24668. auto cli = make_client("example.com", s);
  24669. cli->set_no_proxy({"example.com."});
  24670. auto res = cli->Get("/");
  24671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24672. EXPECT_EQ(0, s.proxy_hits());
  24673. EXPECT_EQ(1, s.target_hits());
  24674. }
  24675. TEST(NoProxyTest, WildcardBypassesEverything) {
  24676. ProxyAndTargetServers s;
  24677. auto cli = make_client("anything.invalid.test", s);
  24678. cli->set_no_proxy({"*"});
  24679. auto res = cli->Get("/");
  24680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24681. EXPECT_EQ(0, s.proxy_hits());
  24682. EXPECT_EQ(1, s.target_hits());
  24683. }
  24684. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24685. ProxyAndTargetServers s;
  24686. Client cli("127.0.0.1", s.target_port());
  24687. cli.set_proxy("127.0.0.1", s.proxy_port());
  24688. cli.set_no_proxy({"127.0.0.1"});
  24689. auto res = cli.Get("/");
  24690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24691. EXPECT_EQ(0, s.proxy_hits());
  24692. EXPECT_EQ(1, s.target_hits());
  24693. }
  24694. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24695. ProxyAndTargetServers s;
  24696. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24697. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24698. cli.set_proxy("127.0.0.1", s.proxy_port());
  24699. cli.set_no_proxy({"::1"});
  24700. auto res = cli.Get("/");
  24701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24702. EXPECT_EQ(0, s.proxy_hits());
  24703. EXPECT_EQ(1, s.target_hits());
  24704. }
  24705. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24706. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24707. // must still be recognized as IPv6 for CIDR matching. Implementations
  24708. // that detect IPv6 only when the host begins with '[' would parse the
  24709. // host as a hostname and miss the match.
  24710. ProxyAndTargetServers s;
  24711. Client cli("fe80::1", s.target_port());
  24712. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24713. cli.set_proxy("127.0.0.1", s.proxy_port());
  24714. cli.set_no_proxy({"fe80::/10"});
  24715. auto res = cli.Get("/");
  24716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24717. EXPECT_EQ(0, s.proxy_hits());
  24718. EXPECT_EQ(1, s.target_hits());
  24719. }
  24720. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24721. ProxyAndTargetServers s;
  24722. Client cli("::1", s.target_port());
  24723. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24724. cli.set_proxy("127.0.0.1", s.proxy_port());
  24725. cli.set_no_proxy({"[::1]"});
  24726. auto res = cli.Get("/");
  24727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24728. EXPECT_EQ(0, s.proxy_hits());
  24729. EXPECT_EQ(1, s.target_hits());
  24730. }
  24731. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24732. ProxyAndTargetServers s;
  24733. Client cli("fe80::1", s.target_port());
  24734. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24735. cli.set_proxy("127.0.0.1", s.proxy_port());
  24736. cli.set_no_proxy({"[fe80::]/10"});
  24737. auto res = cli.Get("/");
  24738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24739. EXPECT_EQ(0, s.proxy_hits());
  24740. EXPECT_EQ(1, s.target_hits());
  24741. }
  24742. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24743. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24744. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24745. // tricks via address-family conversion.
  24746. ProxyAndTargetServers s;
  24747. Client cli("::ffff:127.0.0.1", s.target_port());
  24748. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24749. cli.set_proxy("127.0.0.1", s.proxy_port());
  24750. cli.set_no_proxy({"127.0.0.1"});
  24751. auto res = cli.Get("/");
  24752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24753. EXPECT_GE(s.proxy_hits(), 1);
  24754. EXPECT_EQ(0, s.target_hits());
  24755. }
  24756. TEST(NoProxyTest, IPv4CidrMatch) {
  24757. ProxyAndTargetServers s;
  24758. Client cli("127.0.0.1", s.target_port());
  24759. cli.set_proxy("127.0.0.1", s.proxy_port());
  24760. cli.set_no_proxy({"127.0.0.0/8"});
  24761. auto res = cli.Get("/");
  24762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24763. EXPECT_EQ(0, s.proxy_hits());
  24764. EXPECT_EQ(1, s.target_hits());
  24765. }
  24766. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24767. ProxyAndTargetServers s;
  24768. Client cli("127.0.0.1", s.target_port());
  24769. cli.set_proxy("127.0.0.1", s.proxy_port());
  24770. cli.set_no_proxy({"10.0.0.0/8"});
  24771. auto res = cli.Get("/");
  24772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24773. EXPECT_GE(s.proxy_hits(), 1);
  24774. EXPECT_EQ(0, s.target_hits());
  24775. }
  24776. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24777. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24778. // IPv4 target matches.
  24779. ProxyAndTargetServers s;
  24780. Client cli("127.0.0.1", s.target_port());
  24781. cli.set_proxy("127.0.0.1", s.proxy_port());
  24782. cli.set_no_proxy({"0.0.0.0/0"});
  24783. auto res = cli.Get("/");
  24784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24785. EXPECT_EQ(0, s.proxy_hits());
  24786. EXPECT_EQ(1, s.target_hits());
  24787. }
  24788. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24789. ProxyAndTargetServers s;
  24790. Client cli("127.0.0.1", s.target_port());
  24791. cli.set_proxy("127.0.0.1", s.proxy_port());
  24792. cli.set_no_proxy({"127.0.0.1"});
  24793. auto res = cli.Get("/");
  24794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24795. EXPECT_EQ(0, s.proxy_hits());
  24796. EXPECT_EQ(1, s.target_hits());
  24797. }
  24798. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24799. ProxyAndTargetServers s;
  24800. Client cli("127.0.0.1", s.target_port());
  24801. cli.set_proxy("127.0.0.1", s.proxy_port());
  24802. cli.set_no_proxy({"127.0.0.0/33"});
  24803. auto res = cli.Get("/");
  24804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24805. EXPECT_GE(s.proxy_hits(), 1);
  24806. EXPECT_EQ(0, s.target_hits());
  24807. }
  24808. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24809. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24810. ProxyAndTargetServers s;
  24811. Client cli("127.0.0.1", s.target_port());
  24812. cli.set_proxy("127.0.0.1", s.proxy_port());
  24813. cli.set_no_proxy({"127.0.0.1/"});
  24814. auto res = cli.Get("/");
  24815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24816. EXPECT_GE(s.proxy_hits(), 1);
  24817. EXPECT_EQ(0, s.target_hits());
  24818. }
  24819. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24820. ProxyAndTargetServers s;
  24821. auto cli = make_client("internal.corp", s);
  24822. cli->set_proxy_basic_auth("u", "p");
  24823. cli->set_no_proxy({"internal.corp"});
  24824. auto res = cli->Get("/");
  24825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24826. EXPECT_EQ(1, s.target_hits());
  24827. EXPECT_EQ(0, s.proxy_hits());
  24828. EXPECT_FALSE(s.last_had_proxy_authz())
  24829. << "Proxy-Authorization must not be sent direct to the target";
  24830. }
  24831. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24832. ProxyAndTargetServers s;
  24833. auto cli = make_client("public.example", s);
  24834. cli->set_proxy_basic_auth("u", "p");
  24835. cli->set_no_proxy({"internal.corp"}); // does not match
  24836. auto res = cli->Get("/");
  24837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24838. EXPECT_GE(s.proxy_hits(), 1);
  24839. EXPECT_TRUE(s.last_had_proxy_authz());
  24840. }
  24841. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24842. std::atomic<int> hits{0};
  24843. std::atomic<int> hits_with_authz{0};
  24844. no_proxy_test::ScopedServer proxy_mock;
  24845. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24846. hits++;
  24847. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24848. if (req.target.find("/redir") != std::string::npos) {
  24849. res.set_redirect("http://other.example/landed");
  24850. } else {
  24851. res.set_content("via-proxy", "text/plain");
  24852. }
  24853. });
  24854. proxy_mock.listen();
  24855. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24856. hits = 0;
  24857. hits_with_authz = 0;
  24858. Client cli("public.example", 80);
  24859. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24860. cli.set_proxy_basic_auth(c.first, c.second);
  24861. cli.set_follow_location(true);
  24862. // The redirect to another host goes through the proxy as well
  24863. auto res = cli.Get("/redir");
  24864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24865. EXPECT_EQ(2, hits.load());
  24866. EXPECT_EQ(2, hits_with_authz.load());
  24867. }
  24868. }
  24869. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24870. ProxyAndTargetServers s;
  24871. auto cli = make_client("anything.test", s);
  24872. auto res = cli->Get("/");
  24873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24874. EXPECT_GE(s.proxy_hits(), 1);
  24875. EXPECT_EQ(0, s.target_hits());
  24876. }
  24877. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24878. ProxyAndTargetServers s;
  24879. auto cli = make_client("example.com", s);
  24880. cli->set_no_proxy({"example.com:8080"});
  24881. auto res = cli->Get("/");
  24882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24883. EXPECT_GE(s.proxy_hits(), 1);
  24884. EXPECT_EQ(0, s.target_hits());
  24885. }
  24886. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24887. ProxyAndTargetServers s;
  24888. auto cli = make_client("anything.test", s);
  24889. cli->set_no_proxy({"", " ", "\t"});
  24890. auto res = cli->Get("/");
  24891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24892. EXPECT_GE(s.proxy_hits(), 1);
  24893. EXPECT_EQ(0, s.target_hits());
  24894. }
  24895. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24896. // An entry with leading/trailing whitespace must still match — env-style
  24897. // values are commonly pasted with stray spaces and an implementation
  24898. // that feeds the raw token directly to inet_pton would fail to match
  24899. // valid CIDRs because of the spaces.
  24900. ProxyAndTargetServers s;
  24901. Client cli("127.0.0.1", s.target_port());
  24902. cli.set_proxy("127.0.0.1", s.proxy_port());
  24903. cli.set_no_proxy({" 127.0.0.0/8 "});
  24904. auto res = cli.Get("/");
  24905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24906. EXPECT_EQ(0, s.proxy_hits());
  24907. EXPECT_EQ(1, s.target_hits());
  24908. }
  24909. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24910. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24911. // go direct and must NOT carry Proxy-Authorization.
  24912. std::atomic<int> proxy_hits{0};
  24913. std::atomic<int> target_hits{0};
  24914. std::atomic<bool> target_saw_authz{false};
  24915. no_proxy_test::ScopedServer proxy_mock, target;
  24916. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24917. proxy_hits++;
  24918. res.status = 302;
  24919. res.set_header("Location", "http://127.0.0.1:" +
  24920. std::to_string(target.port()) + "/landed");
  24921. });
  24922. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24923. target_hits++;
  24924. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24925. res.set_content("direct", "text/plain");
  24926. });
  24927. proxy_mock.listen();
  24928. target.listen();
  24929. Client cli("public.example", target.port());
  24930. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24931. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24932. cli.set_proxy_basic_auth("u", "p");
  24933. cli.set_no_proxy({"127.0.0.1"});
  24934. cli.set_follow_location(true);
  24935. auto res = cli.Get("/redir");
  24936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24937. EXPECT_GE(proxy_hits.load(), 1);
  24938. EXPECT_GE(target_hits.load(), 1);
  24939. EXPECT_FALSE(target_saw_authz.load());
  24940. }
  24941. #ifdef CPPHTTPLIB_SSL_ENABLED
  24942. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24943. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24944. // proxy creds would be sent to the (possibly hostile) origin.
  24945. std::atomic<int> target_hits{0};
  24946. std::atomic<bool> target_saw_proxy_authz{false};
  24947. no_proxy_test::ScopedServer target;
  24948. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24949. target_hits++;
  24950. if (req.has_header("Proxy-Authorization")) {
  24951. target_saw_proxy_authz = true;
  24952. }
  24953. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24954. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24955. "nonce=\"abc\", algorithm=MD5");
  24956. });
  24957. target.listen();
  24958. // The proxy address is set to the target's port: the bypass MUST kick in;
  24959. // if it doesn't, the test still routes "via proxy" to the same server and
  24960. // the Proxy-Authorization assertion below catches the leak.
  24961. Client cli("evil.example", target.port());
  24962. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24963. cli.set_proxy("127.0.0.1", target.port());
  24964. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24965. cli.set_no_proxy({"evil.example"});
  24966. auto res = cli.Get("/x");
  24967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24968. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24969. EXPECT_EQ(1, target_hits.load());
  24970. EXPECT_FALSE(target_saw_proxy_authz.load());
  24971. }
  24972. #endif
  24973. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24974. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24975. std::atomic<int> proxy_hits{0};
  24976. std::atomic<int> bypass_hits{0};
  24977. std::atomic<bool> proxy_saw_c_url{false};
  24978. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24979. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24980. proxy_hits++;
  24981. if (req.path.find("/start") != std::string::npos) {
  24982. res.status = 302;
  24983. res.set_header("Location", "http://127.0.0.1:" +
  24984. std::to_string(bypass_server.port()) +
  24985. "/middle");
  24986. return;
  24987. }
  24988. if (req.path.find("/end") != std::string::npos) {
  24989. proxy_saw_c_url = true;
  24990. res.set_content("c-via-proxy", "text/plain");
  24991. return;
  24992. }
  24993. res.set_content("unexpected", "text/plain");
  24994. });
  24995. // public.example's "advertised" port is arbitrary (the request never lands
  24996. // there — it goes through the proxy), but use a dynamic value to stay
  24997. // friendly with sharded parallel runs.
  24998. int public_port = bypass_server.port();
  24999. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  25000. bypass_hits++;
  25001. res.status = 302;
  25002. res.set_header("Location", "http://public.example:" +
  25003. std::to_string(public_port) + "/end");
  25004. });
  25005. proxy_mock.listen();
  25006. bypass_server.listen();
  25007. Client cli("public.example", public_port);
  25008. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25009. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25010. cli.set_no_proxy({"127.0.0.1"});
  25011. cli.set_follow_location(true);
  25012. auto res = cli.Get("/start");
  25013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25014. EXPECT_EQ(StatusCode::OK_200, res->status);
  25015. EXPECT_EQ("c-via-proxy", res->body);
  25016. EXPECT_GE(proxy_hits.load(), 2);
  25017. EXPECT_GE(bypass_hits.load(), 1);
  25018. EXPECT_TRUE(proxy_saw_c_url.load());
  25019. }
  25020. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  25021. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  25022. // request reconnects to the correct endpoint.
  25023. std::atomic<int> proxy_hits{0};
  25024. std::atomic<int> target_hits{0};
  25025. no_proxy_test::ScopedServer proxy_mock, target;
  25026. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25027. proxy_hits++;
  25028. res.set_content("via-proxy", "text/plain");
  25029. });
  25030. target.svr().Get(".*", [&](const Request &, Response &res) {
  25031. target_hits++;
  25032. res.set_content("direct", "text/plain");
  25033. });
  25034. proxy_mock.listen();
  25035. target.listen();
  25036. Client cli("public.example", target.port());
  25037. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25038. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25039. cli.set_keep_alive(true);
  25040. auto res1 = cli.Get("/a");
  25041. ASSERT_TRUE(res1);
  25042. EXPECT_EQ("via-proxy", res1->body);
  25043. EXPECT_EQ(1, proxy_hits.load());
  25044. EXPECT_EQ(0, target_hits.load());
  25045. cli.set_no_proxy({"public.example"});
  25046. auto res2 = cli.Get("/b");
  25047. ASSERT_TRUE(res2);
  25048. EXPECT_EQ("direct", res2->body);
  25049. EXPECT_EQ(1, proxy_hits.load());
  25050. EXPECT_EQ(1, target_hits.load());
  25051. }
  25052. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  25053. namespace proxy_tunnel_test {
  25054. // SSLServer counterpart to no_proxy_test::ScopedServer.
  25055. class ScopedSSLServer {
  25056. public:
  25057. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  25058. port_ = svr_.bind_to_any_port("127.0.0.1");
  25059. }
  25060. ~ScopedSSLServer() {
  25061. svr_.stop();
  25062. if (th_.joinable()) { th_.join(); }
  25063. }
  25064. SSLServer &svr() { return svr_; }
  25065. int port() const { return port_; }
  25066. void listen() {
  25067. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25068. svr_.wait_until_ready();
  25069. }
  25070. private:
  25071. SSLServer svr_;
  25072. std::thread th_;
  25073. int port_ = 0;
  25074. };
  25075. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  25076. class ScopedConnectProxy {
  25077. public:
  25078. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  25079. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  25080. if (listen_fd_ < 0) { return; }
  25081. int yes = 1;
  25082. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  25083. sockaddr_in a{};
  25084. a.sin_family = AF_INET;
  25085. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25086. a.sin_port = 0;
  25087. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  25088. return;
  25089. }
  25090. socklen_t alen = sizeof(a);
  25091. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  25092. 0) {
  25093. return;
  25094. }
  25095. port_ = ntohs(a.sin_port);
  25096. if (::listen(listen_fd_, 1) != 0) { return; }
  25097. th_ = std::thread([this] { run(); });
  25098. }
  25099. ~ScopedConnectProxy() {
  25100. stop_ = true;
  25101. if (listen_fd_ >= 0) {
  25102. ::shutdown(listen_fd_, SHUT_RDWR);
  25103. ::close(listen_fd_);
  25104. }
  25105. if (th_.joinable()) { th_.join(); }
  25106. }
  25107. int port() const { return port_; }
  25108. int connect_hits() const { return connect_hits_.load(); }
  25109. // Head of the last CONNECT request, as the proxy saw it on the wire.
  25110. std::string connect_request() const {
  25111. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25112. return connect_request_;
  25113. }
  25114. private:
  25115. void run() {
  25116. while (!stop_.load()) {
  25117. fd_set rfds;
  25118. FD_ZERO(&rfds);
  25119. FD_SET(listen_fd_, &rfds);
  25120. timeval tv{0, 100 * 1000};
  25121. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  25122. if (sel <= 0) { continue; }
  25123. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  25124. if (client_fd < 0) { continue; }
  25125. std::string req;
  25126. char buf[2048];
  25127. while (req.find("\r\n\r\n") == std::string::npos) {
  25128. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  25129. if (n <= 0) { break; }
  25130. req.append(buf, static_cast<size_t>(n));
  25131. }
  25132. if (req.compare(0, 7, "CONNECT") != 0) {
  25133. ::close(client_fd);
  25134. continue;
  25135. }
  25136. connect_hits_++;
  25137. {
  25138. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25139. connect_request_ = req;
  25140. }
  25141. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  25142. ::send(client_fd, ok, std::strlen(ok), 0);
  25143. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  25144. sockaddr_in o{};
  25145. o.sin_family = AF_INET;
  25146. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25147. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  25148. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  25149. 0) {
  25150. ::close(client_fd);
  25151. ::close(origin_fd);
  25152. continue;
  25153. }
  25154. auto forward = [](int from, int to) {
  25155. char b[8192];
  25156. for (;;) {
  25157. ssize_t n = ::recv(from, b, sizeof(b), 0);
  25158. if (n <= 0) { break; }
  25159. ssize_t off = 0;
  25160. while (off < n) {
  25161. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  25162. if (s <= 0) {
  25163. off = n;
  25164. break;
  25165. }
  25166. off += s;
  25167. }
  25168. }
  25169. ::shutdown(to, SHUT_WR);
  25170. };
  25171. std::thread t1([&] { forward(client_fd, origin_fd); });
  25172. std::thread t2([&] { forward(origin_fd, client_fd); });
  25173. t1.join();
  25174. t2.join();
  25175. ::close(client_fd);
  25176. ::close(origin_fd);
  25177. }
  25178. }
  25179. int forward_port_ = -1;
  25180. int listen_fd_ = -1;
  25181. int port_ = 0;
  25182. std::thread th_;
  25183. std::atomic<bool> stop_{false};
  25184. std::atomic<int> connect_hits_{0};
  25185. mutable std::mutex connect_request_mutex_;
  25186. std::string connect_request_;
  25187. };
  25188. // Sends one request through the CONNECT proxy to the TLS origin with a
  25189. // credential configured for each hop, and checks that each credential reaches
  25190. // only the hop it was configured for: the proxy's on the CONNECT request, the
  25191. // origin's (every header in origin_headers) on the tunnelled request.
  25192. void CredentialsStayWithTheirHop(
  25193. const std::function<void(SSLClient &)> &set_credentials,
  25194. const std::string &scheme,
  25195. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  25196. std::atomic<int> origin_hits{0};
  25197. std::atomic<bool> origin_saw_proxy_authz{false};
  25198. std::atomic<bool> origin_saw_headers{false};
  25199. ScopedSSLServer origin;
  25200. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25201. origin_hits++;
  25202. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  25203. origin_saw_headers =
  25204. std::all_of(origin_headers.begin(), origin_headers.end(),
  25205. [&](const std::string &h) { return req.has_header(h); });
  25206. res.set_content("ok", "text/plain");
  25207. });
  25208. origin.listen();
  25209. ScopedConnectProxy proxy(origin.port());
  25210. ASSERT_NE(0, proxy.port());
  25211. // Pinned to 127.0.0.1 for the same reason as the test below.
  25212. SSLClient cli("127.0.0.1", origin.port());
  25213. cli.enable_server_certificate_verification(false);
  25214. cli.set_proxy("127.0.0.1", proxy.port());
  25215. set_credentials(cli);
  25216. auto res = cli.Get("/x");
  25217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25218. EXPECT_EQ(StatusCode::OK_200, res->status);
  25219. EXPECT_EQ(1, origin_hits.load());
  25220. EXPECT_EQ(1, proxy.connect_hits());
  25221. EXPECT_TRUE(origin_saw_headers.load());
  25222. EXPECT_FALSE(origin_saw_proxy_authz.load())
  25223. << "Proxy-Authorization must not be sent inside the tunnel";
  25224. auto connect_req = proxy.connect_request();
  25225. EXPECT_NE(std::string::npos,
  25226. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  25227. for (const auto &h : origin_headers) {
  25228. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  25229. << h << " must not be sent to the proxy on CONNECT";
  25230. }
  25231. }
  25232. } // namespace proxy_tunnel_test
  25233. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  25234. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25235. [](SSLClient &cli) {
  25236. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25237. cli.set_basic_auth("origin-user", "origin-pass");
  25238. },
  25239. "Basic");
  25240. }
  25241. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  25242. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25243. [](SSLClient &cli) {
  25244. cli.set_proxy_bearer_token_auth("proxy-token");
  25245. cli.set_bearer_token_auth("origin-token");
  25246. },
  25247. "Bearer");
  25248. }
  25249. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  25250. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25251. [](SSLClient &cli) {
  25252. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25253. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  25254. {"Cookie", "sid=origin-session"},
  25255. {"X-Api-Key", "origin-key"}});
  25256. },
  25257. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  25258. }
  25259. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  25260. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  25261. // retry; otherwise proxy creds would be sent to the origin.
  25262. std::atomic<int> origin_hits{0};
  25263. std::atomic<bool> origin_saw_proxy_authz{false};
  25264. proxy_tunnel_test::ScopedSSLServer origin;
  25265. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25266. origin_hits++;
  25267. if (req.has_header("Proxy-Authorization")) {
  25268. origin_saw_proxy_authz = true;
  25269. }
  25270. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25271. res.set_header("Proxy-Authenticate",
  25272. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  25273. "algorithm=MD5");
  25274. });
  25275. origin.listen();
  25276. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25277. ASSERT_NE(0, proxy.port());
  25278. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  25279. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  25280. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  25281. // and answer with its own status, making this test flaky.
  25282. SSLClient cli("127.0.0.1", origin.port());
  25283. cli.enable_server_certificate_verification(false);
  25284. cli.set_proxy("127.0.0.1", proxy.port());
  25285. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25286. auto res = cli.Get("/x");
  25287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25288. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25289. EXPECT_EQ(1, origin_hits.load());
  25290. EXPECT_FALSE(origin_saw_proxy_authz.load());
  25291. EXPECT_EQ(1, proxy.connect_hits());
  25292. }
  25293. #endif