1
0

test.cc 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451
  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_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. ctx_t create_client_context();
  75. void set_verify_client(ctx_t ctx, bool require);
  76. session_t create_session(ctx_t ctx, socket_t sock);
  77. void free_session(session_t session);
  78. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  79. time_t timeout_usec, TlsError *err,
  80. const std::function<bool()> &interrupted);
  81. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  82. time_t timeout_usec, TlsError *err,
  83. const std::function<bool()> &interrupted);
  84. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  85. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  86. void shutdown(session_t session, bool graceful);
  87. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  88. namespace impl {
  89. SecTrustSettingsResult
  90. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  91. } // namespace impl
  92. #endif
  93. } // namespace tls
  94. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  95. namespace detail {
  96. bool ssl_free_buffers_is_safe(unsigned long version);
  97. } // namespace detail
  98. #endif
  99. } // namespace httplib
  100. #endif
  101. using namespace std;
  102. using namespace httplib;
  103. const char *HOST = "localhost";
  104. static int get_base_port() {
  105. const char *shard = getenv("GTEST_SHARD_INDEX");
  106. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  107. }
  108. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  109. // New standalone tests MUST use svr.bind_to_any_port() instead.
  110. const int PORT = get_base_port();
  111. const string LONG_QUERY_VALUE = string(25000, '@');
  112. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  113. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  114. const string TOO_LONG_QUERY_URL =
  115. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  116. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  117. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  118. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  119. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  120. return file.name == key;
  121. });
  122. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  123. return *it;
  124. #else
  125. if (it != items.end()) { return *it; }
  126. throw std::runtime_error("invalid multipart form data name error");
  127. #endif
  128. }
  129. static void read_file(const std::string &path, std::string &out) {
  130. std::ifstream fs(path, std::ios_base::binary);
  131. if (!fs) {
  132. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  133. return;
  134. #else
  135. throw std::runtime_error("File not found: " + path);
  136. #endif
  137. }
  138. fs.seekg(0, std::ios_base::end);
  139. auto size = fs.tellg();
  140. fs.seekg(0);
  141. out.resize(static_cast<size_t>(size));
  142. fs.read(&out[0], static_cast<std::streamsize>(size));
  143. }
  144. // Failures of the services that the *_Online tests reach, unrelated to the
  145. // client under test: httpbingo.org intermittently answers with gateway errors,
  146. // and badssl.com drops connections from CI runners before it sends its
  147. // certificate. A handshake that fails before any verdict on the certificate is
  148. // left to the tests against local servers.
  149. static bool is_service_failure(const Result &res) {
  150. if (res) {
  151. return res->status == StatusCode::BadGateway_502 ||
  152. res->status == StatusCode::ServiceUnavailable_503 ||
  153. res->status == StatusCode::GatewayTimeout_504;
  154. }
  155. return res.error() == Error::SSLConnection;
  156. }
  157. template <typename F> static Result retry_service_failures(F &&send) {
  158. auto res = send();
  159. for (auto wait : {1, 2}) {
  160. if (!is_service_failure(res)) { break; }
  161. std::this_thread::sleep_for(std::chrono::seconds(wait));
  162. res = send();
  163. }
  164. return res;
  165. }
  166. #define SKIP_ON_SERVICE_FAILURE(res) \
  167. do { \
  168. if (is_service_failure(res)) { \
  169. if (res) { \
  170. GTEST_SKIP() << "service failure: status " << (res)->status; \
  171. } else { \
  172. GTEST_SKIP() << "service failure: " << to_string((res).error()); \
  173. } \
  174. } \
  175. } while (0)
  176. class UnixSocketTest : public ::testing::Test {
  177. protected:
  178. void TearDown() override { std::remove(pathname_.c_str()); }
  179. void client_GET(const std::string &addr) {
  180. httplib::Client cli{addr};
  181. cli.set_address_family(AF_UNIX);
  182. ASSERT_TRUE(cli.is_valid());
  183. const auto &result = cli.Get(pattern_);
  184. ASSERT_TRUE(result) << "error: " << result.error();
  185. const auto &resp = result.value();
  186. EXPECT_EQ(resp.status, StatusCode::OK_200);
  187. EXPECT_EQ(resp.body, content_);
  188. }
  189. static std::string make_sock_path() {
  190. const char *shard = getenv("GTEST_SHARD_INDEX");
  191. return shard ? std::string("./httplib-server-") + shard + ".sock"
  192. : "./httplib-server.sock";
  193. }
  194. const std::string pathname_{make_sock_path()};
  195. const std::string pattern_{"/hi"};
  196. const std::string content_{"Hello World!"};
  197. };
  198. TEST_F(UnixSocketTest, pathname) {
  199. httplib::Server svr;
  200. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  201. res.set_content(content_, "text/plain");
  202. });
  203. std::thread t{[&] {
  204. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  205. }};
  206. auto se = detail::scope_exit([&] {
  207. svr.stop();
  208. t.join();
  209. ASSERT_FALSE(svr.is_running());
  210. });
  211. svr.wait_until_ready();
  212. ASSERT_TRUE(svr.is_running());
  213. client_GET(pathname_);
  214. // ".//x.sock", which is not taken for a URL
  215. client_GET("./" + pathname_.substr(1));
  216. }
  217. #if defined(__linux__) || \
  218. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  219. TEST_F(UnixSocketTest, PeerPid) {
  220. httplib::Server svr;
  221. std::string remote_port_val;
  222. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  223. res.set_content(content_, "text/plain");
  224. remote_port_val = std::to_string(req.remote_port);
  225. });
  226. std::thread t{[&] {
  227. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  228. }};
  229. auto se = detail::scope_exit([&] {
  230. svr.stop();
  231. t.join();
  232. ASSERT_FALSE(svr.is_running());
  233. });
  234. svr.wait_until_ready();
  235. ASSERT_TRUE(svr.is_running());
  236. client_GET(pathname_);
  237. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  238. }
  239. #endif
  240. #ifdef __linux__
  241. TEST_F(UnixSocketTest, abstract) {
  242. constexpr char svr_path[]{"\x00httplib-server.sock"};
  243. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  244. httplib::Server svr;
  245. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  246. res.set_content(content_, "text/plain");
  247. });
  248. std::thread t{[&] {
  249. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  250. }};
  251. auto se = detail::scope_exit([&] {
  252. svr.stop();
  253. t.join();
  254. ASSERT_FALSE(svr.is_running());
  255. });
  256. svr.wait_until_ready();
  257. ASSERT_TRUE(svr.is_running());
  258. client_GET(abstract_addr);
  259. }
  260. #endif
  261. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  262. httplib::Server svr;
  263. std::string received_host_header;
  264. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  265. // Capture the Host header sent by the client
  266. auto host_iter = req.headers.find("Host");
  267. if (host_iter != req.headers.end()) {
  268. received_host_header = host_iter->second;
  269. }
  270. res.set_content(content_, "text/plain");
  271. });
  272. std::thread t{[&] {
  273. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  274. }};
  275. auto se = detail::scope_exit([&] {
  276. svr.stop();
  277. t.join();
  278. ASSERT_FALSE(svr.is_running());
  279. });
  280. svr.wait_until_ready();
  281. ASSERT_TRUE(svr.is_running());
  282. // Test that Host header is automatically set to "localhost" for Unix socket
  283. // connections
  284. httplib::Client cli{pathname_};
  285. cli.set_address_family(AF_UNIX);
  286. ASSERT_TRUE(cli.is_valid());
  287. const auto &result = cli.Get(pattern_);
  288. ASSERT_TRUE(result) << "error: " << result.error();
  289. const auto &resp = result.value();
  290. EXPECT_EQ(resp.status, StatusCode::OK_200);
  291. EXPECT_EQ(resp.body, content_);
  292. // Verify that Host header was automatically set to "localhost"
  293. EXPECT_EQ(received_host_header, "localhost");
  294. }
  295. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  296. // Another socket in the working directory, which a Location can name as
  297. // its host
  298. const auto other_path = "other-" + pathname_.substr(2);
  299. httplib::Server svr;
  300. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  301. // An absolute Location naming the Host this client sends
  302. res.set_redirect("http://localhost" + pattern_);
  303. });
  304. svr.Get("/upper", [&](const httplib::Request &, httplib::Response &res) {
  305. res.set_redirect("http://LOCALHOST" + pattern_);
  306. });
  307. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  308. res.set_redirect("http://" + other_path + pattern_);
  309. });
  310. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  311. res.set_redirect("http://mapped.test" + pattern_);
  312. });
  313. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  314. res.set_header("X-Auth", req.get_header_value("Authorization"));
  315. res.set_content(content_, "text/plain");
  316. });
  317. httplib::Server other;
  318. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  319. res.set_content("other", "text/plain");
  320. });
  321. std::thread t{[&] {
  322. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  323. }};
  324. std::thread t2{[&] {
  325. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  326. }};
  327. auto se = detail::scope_exit([&] {
  328. svr.stop();
  329. other.stop();
  330. t.join();
  331. t2.join();
  332. std::remove(other_path.c_str());
  333. });
  334. svr.wait_until_ready();
  335. other.wait_until_ready();
  336. httplib::Client cli{pathname_};
  337. cli.set_address_family(AF_UNIX);
  338. cli.set_follow_location(true);
  339. cli.set_bearer_token_auth("token");
  340. // Another host: the same socket, without the credentials
  341. auto res = cli.Get("/cross");
  342. ASSERT_TRUE(res) << "error: " << res.error();
  343. EXPECT_EQ(StatusCode::OK_200, res->status);
  344. EXPECT_EQ(content_, res->body);
  345. EXPECT_EQ("", res->get_header_value("X-Auth"));
  346. // localhost is this client's own host
  347. res = cli.Get("/redirect");
  348. ASSERT_TRUE(res) << "error: " << res.error();
  349. EXPECT_EQ(StatusCode::OK_200, res->status);
  350. EXPECT_EQ(content_, res->body);
  351. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  352. // in any case
  353. res = cli.Get("/upper");
  354. ASSERT_TRUE(res) << "error: " << res.error();
  355. EXPECT_EQ(StatusCode::OK_200, res->status);
  356. EXPECT_EQ(content_, res->body);
  357. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  358. // A host the caller mapped to a socket goes there
  359. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  360. res = cli.Get("/mapped");
  361. ASSERT_TRUE(res) << "error: " << res.error();
  362. EXPECT_EQ(StatusCode::OK_200, res->status);
  363. EXPECT_EQ("other", res->body);
  364. }
  365. #ifndef _WIN32
  366. TEST(SocketStream, wait_writable_UNIX) {
  367. int fds[2];
  368. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  369. const auto asSocketStream = [&](socket_t fd,
  370. std::function<bool(Stream &)> func) {
  371. return detail::process_client_socket(
  372. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  373. };
  374. asSocketStream(fds[0], [&](Stream &s0) {
  375. EXPECT_EQ(s0.socket(), fds[0]);
  376. EXPECT_TRUE(s0.wait_writable());
  377. EXPECT_TRUE(s0.is_peer_alive());
  378. EXPECT_EQ(0, close(fds[1]));
  379. EXPECT_FALSE(s0.is_peer_alive());
  380. return true;
  381. });
  382. EXPECT_EQ(0, close(fds[0]));
  383. }
  384. TEST(SocketStream, wait_writable_INET) {
  385. sockaddr_in addr;
  386. memset(&addr, 0, sizeof(addr));
  387. addr.sin_family = AF_INET;
  388. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  389. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  390. int disconnected_svr_sock = -1;
  391. std::thread svr{[&] {
  392. const int s = socket(AF_INET, SOCK_STREAM, 0);
  393. ASSERT_LE(0, s);
  394. // PORT + 1 is shared with the SSL redirect tests and with
  395. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  396. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  397. // because that happens on a worker thread the ASSERT does not stop the
  398. // test: it runs on and fails at the disconnected_svr_sock check instead.
  399. default_socket_options(s);
  400. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  401. ASSERT_EQ(0, listen(s, 1));
  402. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  403. ASSERT_EQ(0, close(s));
  404. }};
  405. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  406. std::thread cli{[&] {
  407. const int s = socket(AF_INET, SOCK_STREAM, 0);
  408. ASSERT_LE(0, s);
  409. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  410. ASSERT_EQ(0, close(s));
  411. }};
  412. cli.join();
  413. svr.join();
  414. ASSERT_NE(disconnected_svr_sock, -1);
  415. const auto asSocketStream = [&](socket_t fd,
  416. std::function<bool(Stream &)> func) {
  417. return detail::process_client_socket(
  418. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  419. };
  420. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  421. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  422. // wait_writable() returns true because select_write() only checks if the
  423. // send buffer has space. Peer disconnection is detected later by send().
  424. EXPECT_TRUE(ss.wait_writable());
  425. return true;
  426. });
  427. ASSERT_EQ(0, close(disconnected_svr_sock));
  428. }
  429. #endif // #ifndef _WIN32
  430. TEST(SetSocketOptTest, TcpNoDelay) {
  431. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  432. ASSERT_NE(sock, INVALID_SOCKET);
  433. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  434. int val = 0;
  435. socklen_t len = sizeof(val);
  436. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  437. reinterpret_cast<char *>(&val), &len));
  438. EXPECT_NE(val, 0);
  439. detail::close_socket(sock);
  440. }
  441. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  442. // accept() reports failures through WSAGetLastError() on Windows and through
  443. // errno everywhere else. Asking the wrong one is what made the accept loop
  444. // treat every recoverable failure as fatal on Windows.
  445. struct Classification {
  446. bool resource;
  447. bool transient;
  448. };
  449. auto classify = [](int err) {
  450. #ifdef _WIN32
  451. WSASetLastError(err);
  452. #else
  453. errno = err;
  454. #endif
  455. // Read both before asserting: an assertion may clobber the error slot.
  456. Classification c;
  457. c.resource = detail::is_accept_resource_error();
  458. c.transient = detail::is_accept_transient_error();
  459. return c;
  460. };
  461. #ifdef _WIN32
  462. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  463. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  464. WSAECONNRESET, WSAECONNABORTED};
  465. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  466. #else
  467. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  468. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  469. ECONNABORTED};
  470. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  471. #endif
  472. for (auto err : resource_errors) {
  473. const auto c = classify(err);
  474. EXPECT_TRUE(c.resource) << "error " << err;
  475. EXPECT_FALSE(c.transient) << "error " << err;
  476. }
  477. for (auto err : transient_errors) {
  478. const auto c = classify(err);
  479. EXPECT_TRUE(c.transient) << "error " << err;
  480. EXPECT_FALSE(c.resource) << "error " << err;
  481. }
  482. for (auto err : fatal_errors) {
  483. const auto c = classify(err);
  484. EXPECT_FALSE(c.resource) << "error " << err;
  485. EXPECT_FALSE(c.transient) << "error " << err;
  486. }
  487. #ifdef _WIN32
  488. WSASetLastError(0);
  489. #else
  490. errno = 0;
  491. #endif
  492. }
  493. TEST(ClientTest, MoveConstructible) {
  494. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  495. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  496. }
  497. TEST(ClientTest, MoveAssignable) {
  498. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  499. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  500. }
  501. #ifdef _WIN32
  502. TEST(StartupTest, WSAStartup) {
  503. WSADATA wsaData;
  504. int ret = WSAStartup(0x0002, &wsaData);
  505. ASSERT_EQ(0, ret);
  506. }
  507. #endif
  508. TEST(DecodePathTest, PercentCharacter) {
  509. EXPECT_EQ(
  510. decode_path_component(
  511. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  512. U8("descrip=Gastos áéíóúñÑ 6"));
  513. }
  514. TEST(DecodePathTest, PercentCharacterNUL) {
  515. string expected;
  516. expected.push_back('x');
  517. expected.push_back('\0');
  518. expected.push_back('x');
  519. EXPECT_EQ(decode_path_component("x%00x"), expected);
  520. }
  521. TEST(DecodePathTest, UnicodeEncoding) {
  522. // %u0041 = 'A' (1-byte UTF-8)
  523. EXPECT_EQ("A", decode_path_component("%u0041"));
  524. // %u00E9 = 'é' (2-byte UTF-8)
  525. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  526. // %u3042 = 'あ' (3-byte UTF-8)
  527. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  528. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  529. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  530. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  531. // neighbours)
  532. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  533. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  534. }
  535. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  536. // A sign or whitespace inside the two-character escape window must not be
  537. // accepted as a valid percent-encoding; the sequence is passed through
  538. // literally, matching decode_uri_component / decode_path_component.
  539. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  540. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  541. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  542. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  543. // Well-formed escapes still decode.
  544. EXPECT_EQ("-", decode_query_component("%2D", false));
  545. EXPECT_EQ("A", decode_query_component("%41", false));
  546. }
  547. TEST(SanitizeFilenameTest, VariousPatterns) {
  548. // Path traversal
  549. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  550. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  551. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  552. // Normal and edge cases
  553. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  554. EXPECT_EQ("filename.txt",
  555. httplib::sanitize_filename("/path/to/filename.txt"));
  556. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  557. EXPECT_EQ("", httplib::sanitize_filename(".."));
  558. EXPECT_EQ("", httplib::sanitize_filename(""));
  559. // Null bytes stripped
  560. EXPECT_EQ("safe.txt",
  561. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  562. // Whitespace-only rejected
  563. EXPECT_EQ("", httplib::sanitize_filename(" "));
  564. }
  565. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  566. // before it is dropped; anywhere else it is an ordinary file name character.
  567. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  568. #ifdef _WIN32
  569. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  570. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  571. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  572. #else
  573. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  574. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  575. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  576. #endif
  577. }
  578. // Forward declaration (see the base64_encode note below): split builds move the
  579. // definition into httplib.cc, so re-declaring it here lets the test link.
  580. namespace httplib {
  581. namespace detail {
  582. bool is_chunked_transfer_encoding(const Headers &headers);
  583. } // namespace detail
  584. } // namespace httplib
  585. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  586. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  587. auto make = [](std::initializer_list<const char *> lines) {
  588. Headers h;
  589. for (auto te : lines) {
  590. if (te) { h.emplace("Transfer-Encoding", te); }
  591. }
  592. return h;
  593. };
  594. // Sole coding, matched case-insensitively.
  595. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  596. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  597. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  598. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  599. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  600. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  601. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  602. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  603. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  604. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  605. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  606. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  607. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  608. // were received, into one list. Headers preserves that order, so the answer
  609. // is decided by the last coding of the last line and the order the lines
  610. // arrived in is significant.
  611. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  612. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  613. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  614. // The split can fall anywhere in the list.
  615. EXPECT_TRUE(
  616. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  617. EXPECT_FALSE(
  618. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  619. // A trailing line naming no coding leaves the list ending in nothing, so it
  620. // must not inherit the chunked from the line before it.
  621. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  622. }
  623. // Forward declarations (see the base64_encode note below).
  624. namespace httplib {
  625. namespace detail {
  626. bool parse_status_line(const char *line, std::string &version, int &status,
  627. std::string &reason);
  628. std::string file_extension(const std::string &path);
  629. std::string
  630. find_content_type(const std::string &path,
  631. const std::map<std::string, std::string> &user_data,
  632. const std::string &default_content_type);
  633. bool can_compress_content_type(const std::string &content_type);
  634. bool is_prohibited_header_name(const std::string &name);
  635. bool is_valid_path(const std::string &path);
  636. #ifdef CPPHTTPLIB_SSL_ENABLED
  637. bool match_hostname(const std::string &pattern, const std::string &hostname);
  638. #endif
  639. } // namespace detail
  640. } // namespace httplib
  641. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  642. struct {
  643. const char *line;
  644. const char *version;
  645. int status;
  646. const char *reason;
  647. } cases[] = {
  648. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  649. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  650. // The reason phrase may be empty, or left out along with its space.
  651. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  652. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  653. };
  654. for (const auto &c : cases) {
  655. std::string version;
  656. int status = 0;
  657. std::string reason = "unset";
  658. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  659. << c.line;
  660. EXPECT_EQ(c.version, version);
  661. EXPECT_EQ(c.status, status);
  662. EXPECT_EQ(c.reason, reason);
  663. }
  664. }
  665. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  666. const char *lines[] = {
  667. "HTTP/2 200 OK\r\n",
  668. "HTTP/1.2 200 OK\r\n",
  669. "HTTP/1.1 20 OK\r\n",
  670. "HTTP/1.1 2000 OK\r\n",
  671. "HTTP/1.1 2x0 OK\r\n",
  672. "HTTP/1.1 200 OK\r\n",
  673. "HTTP/1.1 200OK\r\n",
  674. "HTTP/1.1 200 O\rK\r\n",
  675. "HTTP/1.1 200 OK",
  676. "HTTP/1.1 200 OK\r\nX",
  677. "",
  678. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  679. "HTTP/1.1 200 OK\n",
  680. #endif
  681. };
  682. for (auto line : lines) {
  683. std::string version;
  684. int status = 0;
  685. std::string reason;
  686. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  687. << line;
  688. }
  689. }
  690. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  691. // Long enough to overflow the stack when matched with std::regex.
  692. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  693. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  694. std::string version;
  695. int status = 0;
  696. std::string reason;
  697. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  698. EXPECT_EQ(200, status);
  699. EXPECT_EQ(long_reason, reason);
  700. }
  701. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  702. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  703. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  704. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  705. EXPECT_EQ("", detail::file_extension("noext"));
  706. EXPECT_EQ("", detail::file_extension("a."));
  707. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  708. EXPECT_EQ("", detail::file_extension("a.b-c"));
  709. // Long enough to overflow the stack when matched with std::regex.
  710. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  711. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  712. }
  713. #ifdef CPPHTTPLIB_SSL_ENABLED
  714. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  715. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  716. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  717. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  718. // A wildcard needs two labels after it, in the leftmost label only
  719. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  720. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  721. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  722. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  723. EXPECT_FALSE(
  724. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  725. // No name may have an empty label
  726. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  727. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  728. }
  729. #endif
  730. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  731. detail::case_ignore::hash hash;
  732. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  733. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  734. // Long enough to overflow the stack if hashed one call per character.
  735. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  736. }
  737. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  738. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  739. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  740. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  741. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  742. // Same 26-bit hash as html, svg and js.
  743. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  744. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  745. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  746. }
  747. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  748. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  749. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  750. }
  751. }
  752. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  753. // name anywhere else.
  754. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  755. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  756. #ifdef _WIN32
  757. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  758. #else
  759. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  760. #endif
  761. }
  762. }
  763. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  764. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  765. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  766. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  767. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  768. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  769. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  770. // Same 26-bit hash as application/json.
  771. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  772. }
  773. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  774. Request req;
  775. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  776. EXPECT_TRUE(req.is_multipart_form_data());
  777. std::string boundary;
  778. EXPECT_TRUE(detail::parse_multipart_boundary(
  779. req.get_header_value("Content-Type"), boundary));
  780. EXPECT_EQ("x", boundary);
  781. }
  782. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  783. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  784. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  785. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  786. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  787. // Same 26-bit hash as REMOTE_ADDR.
  788. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  789. }
  790. // Forward declaration: in split builds split.py strips `inline` and moves the
  791. // definition into httplib.cc, so detail::base64_encode is not visible from the
  792. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  793. // in both header-only and split builds.
  794. namespace httplib {
  795. namespace detail {
  796. std::string base64_encode(const std::string &in);
  797. } // namespace detail
  798. } // namespace httplib
  799. TEST(Base64EncodeTest, KnownAnswers) {
  800. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  801. // where the accumulator's top bit is already set before the next shift.
  802. EXPECT_EQ("", detail::base64_encode(""));
  803. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  804. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  805. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  806. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  807. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  808. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  809. // High bytes keep the top bit set across several rounds.
  810. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  811. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  812. }
  813. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  814. string unescapedCharacters = "-_.!~*'()";
  815. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  816. }
  817. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  818. string reservedCharacters = ";,/?:@&=+$";
  819. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  820. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  821. }
  822. TEST(ClientQueryOrder, PreserveOrder) {
  823. // This test reproduces Issue #2259: client may reorder query parameters
  824. // when sending a GET request. The expected behavior is that the client
  825. // preserves the original query string order when the caller supplied it
  826. // as part of the path.
  827. Server svr;
  828. svr.Get("/", [&](const Request &req, Response &res) {
  829. // Echo back the raw target so the test can assert ordering
  830. res.set_content(req.target, "text/plain");
  831. });
  832. std::thread t{[&] { svr.listen(HOST, PORT); }};
  833. auto se = detail::scope_exit([&] {
  834. svr.stop();
  835. t.join();
  836. ASSERT_FALSE(svr.is_running());
  837. });
  838. svr.wait_until_ready();
  839. Client cli(HOST, PORT);
  840. ASSERT_TRUE(cli.is_valid());
  841. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  842. auto res = cli.Get(original);
  843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  844. // Expect the echoed target to exactly match the original path (order
  845. // preserved)
  846. EXPECT_EQ(res->body, original);
  847. }
  848. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  849. string chineseCharacters = U8("中国語");
  850. string russianCharacters = U8("дом");
  851. string brazilianCharacters = U8("óculos");
  852. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  853. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  854. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  855. "%D0%B4%D0%BE%D0%BC");
  856. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  857. }
  858. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  859. string unescapedCharacters = "-_.!~*'()";
  860. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  861. }
  862. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  863. string reservedCharacters = ";,/?:@&=+$";
  864. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  865. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  866. }
  867. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  868. string chineseCharacters = U8("中国語");
  869. string russianCharacters = U8("дом");
  870. string brazilianCharacters = U8("óculos");
  871. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  872. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  873. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  874. "%D0%B4%D0%BE%D0%BC");
  875. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  876. }
  877. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  878. // Issue #2082 use case: encoding path component with ampersand
  879. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  880. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  881. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  882. }
  883. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  884. string unescapedCharacters = "-_.!~*'()";
  885. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  886. }
  887. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  888. string reservedCharacters = ";,/?:@&=+$#";
  889. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  890. }
  891. TEST(EncodeUriTest, TestUTF8Characters) {
  892. string chineseCharacters = U8("中国語");
  893. string russianCharacters = U8("дом");
  894. string brazilianCharacters = U8("óculos");
  895. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  896. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  897. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  898. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  899. }
  900. TEST(EncodeUriTest, TestCompleteUri) {
  901. string uri =
  902. "https://example.com/path/to/resource?query=value&param=test#fragment";
  903. EXPECT_EQ(
  904. httplib::encode_uri(uri),
  905. "https://example.com/path/to/resource?query=value&param=test#fragment");
  906. }
  907. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  908. string uri =
  909. "https://example.com/path with spaces/file name.html?q=hello world";
  910. EXPECT_EQ(httplib::encode_uri(uri),
  911. "https://example.com/path%20with%20spaces/"
  912. "file%20name.html?q=hello%20world");
  913. }
  914. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  915. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  916. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  917. }
  918. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  919. string unescapedCharacters = "-_.!~*'()";
  920. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  921. }
  922. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  923. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  924. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  925. string encodedBrazilian = "%C3%B3culos";
  926. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  927. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  928. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  929. }
  930. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  931. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  932. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  933. "Piri Tommy Villiers - on & on");
  934. }
  935. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  936. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  937. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  938. }
  939. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  940. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  941. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  942. }
  943. TEST(DecodeUriTest, TestUTF8Characters) {
  944. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  945. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  946. string encodedBrazilian = "%C3%B3culos";
  947. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  948. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  949. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  950. }
  951. TEST(DecodeUriTest, TestCompleteUri) {
  952. string encodedUri = "https://example.com/path%20with%20spaces/"
  953. "file%20name.html?q=hello%20world";
  954. EXPECT_EQ(
  955. httplib::decode_uri(encodedUri),
  956. "https://example.com/path with spaces/file name.html?q=hello world");
  957. }
  958. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  959. string original =
  960. "https://example.com/path with spaces/file name.html?q=hello world";
  961. string encoded = httplib::encode_uri(original);
  962. string decoded = httplib::decode_uri(encoded);
  963. EXPECT_EQ(decoded, original);
  964. }
  965. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  966. // decode_uri is the inverse of encode_uri: an escaped reserved character
  967. // stays encoded so it is not promoted into a real delimiter, while
  968. // non-reserved escapes still decode (like JS decodeURI).
  969. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  970. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  971. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  972. "%3F%3A%40%26%3D%2B%24%2C%3B");
  973. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  974. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  975. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  976. "http://example.com/a%2Fb");
  977. // decode_uri_component still decodes the reserved character.
  978. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  979. }
  980. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  981. string original = "Piri Tommy Villiers - on & on";
  982. string encoded = httplib::encode_uri_component(original);
  983. string decoded = httplib::decode_uri_component(encoded);
  984. EXPECT_EQ(decoded, original);
  985. }
  986. TEST(TrimTests, TrimStringTests) {
  987. EXPECT_EQ("abc", detail::trim_copy("abc"));
  988. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  989. EXPECT_TRUE(detail::trim_copy("").empty());
  990. }
  991. TEST(AsciiTest, LocaleIndependentClassification) {
  992. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  993. // which consult the global C locale: std::isalnum(0xC5) can return true
  994. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  995. // helpers must classify every byte by the ASCII grammar alone.
  996. for (int i = 0; i < 256; i++) {
  997. auto c = static_cast<char>(i);
  998. auto is_digit = i >= '0' && i <= '9';
  999. auto is_upper = i >= 'A' && i <= 'Z';
  1000. auto is_lower = i >= 'a' && i <= 'z';
  1001. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  1002. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  1003. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  1004. << "byte " << i;
  1005. }
  1006. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  1007. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  1008. // Non-ASCII bytes must be percent-encoded, never passed through as
  1009. // alphanumeric.
  1010. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  1011. }
  1012. TEST(FromCharsTest, Double) {
  1013. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  1014. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  1015. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  1016. auto parse = [](const std::string &s, double &v) {
  1017. return detail::from_chars(s.data(), s.data() + s.size(), v);
  1018. };
  1019. double v = -1.0;
  1020. // Representative quality values.
  1021. EXPECT_EQ(parse("0", v).ec, std::errc{});
  1022. EXPECT_DOUBLE_EQ(v, 0.0);
  1023. EXPECT_EQ(parse("1", v).ec, std::errc{});
  1024. EXPECT_DOUBLE_EQ(v, 1.0);
  1025. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  1026. EXPECT_DOUBLE_EQ(v, 0.8);
  1027. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  1028. EXPECT_DOUBLE_EQ(v, 0.001);
  1029. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  1030. EXPECT_DOUBLE_EQ(v, 1.0);
  1031. // A missing integer or fractional part is tolerated.
  1032. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  1033. EXPECT_DOUBLE_EQ(v, 0.5);
  1034. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  1035. EXPECT_DOUBLE_EQ(v, 5.0);
  1036. // Values outside [0, 1] still parse; the caller range-checks them.
  1037. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  1038. EXPECT_DOUBLE_EQ(v, 123.456);
  1039. // Stops at the first byte that is not part of the number and reports where.
  1040. std::string trailing = "0.9, text/html";
  1041. auto r = parse(trailing, v);
  1042. EXPECT_EQ(r.ec, std::errc{});
  1043. EXPECT_DOUBLE_EQ(v, 0.9);
  1044. EXPECT_EQ(*r.ptr, ',');
  1045. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  1046. // outright, and an 'e'/'E' simply ends the number.
  1047. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  1048. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  1049. std::string exp_input = "1.5e3";
  1050. r = parse(exp_input, v);
  1051. EXPECT_EQ(r.ec, std::errc{});
  1052. EXPECT_DOUBLE_EQ(v, 1.5);
  1053. EXPECT_EQ(*r.ptr, 'e');
  1054. // Invalid inputs.
  1055. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1056. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1057. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1058. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1059. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1060. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1061. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1062. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1063. std::errc{});
  1064. EXPECT_DOUBLE_EQ(v, 0.0);
  1065. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1066. std::errc{});
  1067. EXPECT_GE(v, 0.0);
  1068. EXPECT_LE(v, 1.0);
  1069. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1070. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1071. }
  1072. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1073. // Simple case without quality values
  1074. std::vector<std::string> result1;
  1075. EXPECT_TRUE(detail::parse_accept_header(
  1076. "text/html,application/json,text/plain", result1));
  1077. EXPECT_EQ(result1.size(), 3U);
  1078. EXPECT_EQ(result1[0], "text/html");
  1079. EXPECT_EQ(result1[1], "application/json");
  1080. EXPECT_EQ(result1[2], "text/plain");
  1081. // With quality values
  1082. std::vector<std::string> result2;
  1083. EXPECT_TRUE(detail::parse_accept_header(
  1084. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1085. EXPECT_EQ(result2.size(), 3U);
  1086. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1087. EXPECT_EQ(result2[1], "text/html");
  1088. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1089. }
  1090. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1091. // Mixed with and without quality values
  1092. std::vector<std::string> result;
  1093. EXPECT_TRUE(detail::parse_accept_header(
  1094. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1095. EXPECT_EQ(result.size(), 3U);
  1096. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1097. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1098. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1099. }
  1100. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1101. // Empty header
  1102. std::vector<std::string> empty_result;
  1103. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1104. EXPECT_TRUE(empty_result.empty());
  1105. // Single type
  1106. std::vector<std::string> single_result;
  1107. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1108. EXPECT_EQ(single_result.size(), 1U);
  1109. EXPECT_EQ(single_result[0], "application/json");
  1110. // Wildcard types
  1111. std::vector<std::string> wildcard_result;
  1112. EXPECT_TRUE(detail::parse_accept_header(
  1113. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1114. EXPECT_EQ(wildcard_result.size(), 3U);
  1115. EXPECT_EQ(wildcard_result[0], "application/json");
  1116. EXPECT_EQ(wildcard_result[1], "text/*");
  1117. EXPECT_EQ(wildcard_result[2], "*/*");
  1118. }
  1119. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1120. // Common browser Accept header
  1121. std::vector<std::string> browser_result;
  1122. EXPECT_TRUE(
  1123. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1124. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1125. browser_result));
  1126. EXPECT_EQ(browser_result.size(), 6U);
  1127. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1128. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1129. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1130. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1131. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1132. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1133. // API client header
  1134. std::vector<std::string> api_result;
  1135. EXPECT_TRUE(detail::parse_accept_header(
  1136. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1137. api_result));
  1138. EXPECT_EQ(api_result.size(), 3U);
  1139. EXPECT_EQ(api_result[0], "application/json");
  1140. EXPECT_EQ(api_result[1], "application/xml");
  1141. EXPECT_EQ(api_result[2], "text/plain");
  1142. }
  1143. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1144. // Quality value with 3 decimal places
  1145. std::vector<std::string> decimal_result;
  1146. EXPECT_TRUE(detail::parse_accept_header(
  1147. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1148. EXPECT_EQ(decimal_result.size(), 2U);
  1149. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1150. EXPECT_EQ(decimal_result[1], "text/html");
  1151. // Zero quality (should still be included but with lowest priority)
  1152. std::vector<std::string> zero_q_result;
  1153. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1154. zero_q_result));
  1155. EXPECT_EQ(zero_q_result.size(), 2U);
  1156. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1157. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1158. // No spaces around commas
  1159. std::vector<std::string> no_space_result;
  1160. EXPECT_TRUE(detail::parse_accept_header(
  1161. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1162. no_space_result));
  1163. EXPECT_EQ(no_space_result.size(), 3U);
  1164. EXPECT_EQ(no_space_result[0], "text/html");
  1165. EXPECT_EQ(no_space_result[1], "application/json");
  1166. EXPECT_EQ(no_space_result[2], "text/plain");
  1167. }
  1168. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1169. // Quality values always use '.' as the decimal separator, so parsing must
  1170. // not depend on the process locale. An embedding application may have
  1171. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1172. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1173. std::string saved = cur ? cur : "C";
  1174. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1175. "fr_FR.UTF-8"};
  1176. bool switched = false;
  1177. for (const auto loc : comma_locales) {
  1178. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1179. std::localeconv()->decimal_point[0] == ',') {
  1180. switched = true;
  1181. break;
  1182. }
  1183. }
  1184. if (!switched) {
  1185. std::setlocale(LC_NUMERIC, saved.c_str());
  1186. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1187. }
  1188. // The higher-weighted type appears later in the list, so a correct parse
  1189. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1190. // sensitive parse reads both weights as 0 and leaves the original order.
  1191. std::vector<std::string> result;
  1192. EXPECT_TRUE(detail::parse_accept_header(
  1193. "application/json;q=0.1,text/html;q=0.9", result));
  1194. ASSERT_EQ(result.size(), 2U);
  1195. EXPECT_EQ(result[0], "text/html");
  1196. EXPECT_EQ(result[1], "application/json");
  1197. std::setlocale(LC_NUMERIC, saved.c_str());
  1198. }
  1199. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1200. std::vector<std::string> result;
  1201. // Invalid quality value (> 1.0)
  1202. EXPECT_FALSE(
  1203. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1204. // Invalid quality value (< 0.0)
  1205. EXPECT_FALSE(
  1206. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1207. // Invalid quality value (not a number)
  1208. EXPECT_FALSE(detail::parse_accept_header(
  1209. "text/html;q=invalid,application/json", result));
  1210. // A valid numeric prefix does not make the entire quality value valid.
  1211. EXPECT_FALSE(detail::parse_accept_header(
  1212. "text/html;q=0.5junk,application/json", result));
  1213. // Empty quality value
  1214. EXPECT_FALSE(
  1215. detail::parse_accept_header("text/html;q=,application/json", result));
  1216. // Invalid media type format (no slash and not wildcard)
  1217. EXPECT_FALSE(
  1218. detail::parse_accept_header("invalidtype,application/json", result));
  1219. // Valid cases should still work
  1220. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1221. EXPECT_EQ(result.size(), 1U);
  1222. EXPECT_EQ(result[0], "*/*");
  1223. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1224. EXPECT_EQ(result.size(), 1U);
  1225. EXPECT_EQ(result[0], "*");
  1226. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1227. EXPECT_EQ(result.size(), 1U);
  1228. EXPECT_EQ(result[0], "text/*");
  1229. }
  1230. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1231. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1232. // and must not be answered with 400 Bad Request.
  1233. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1234. struct {
  1235. const char *value;
  1236. std::vector<std::string> expected;
  1237. } cases[] = {
  1238. {",application/json", {"application/json"}},
  1239. {"text/html,", {"text/html"}},
  1240. {"text/html,,*/*", {"text/html", "*/*"}},
  1241. // An empty element may be spelled with whitespace in it
  1242. {"text/html, , application/json", {"text/html", "application/json"}},
  1243. // Nothing but empty elements is an empty list, which means the same
  1244. // thing as no Accept header at all
  1245. {",,,", {}},
  1246. // Quality values still apply across ignored empty elements
  1247. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1248. };
  1249. for (const auto &c : cases) {
  1250. std::vector<std::string> result;
  1251. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1252. << "value: " << c.value;
  1253. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1254. }
  1255. // An invalid entry is still rejected when empty elements surround it
  1256. std::vector<std::string> result;
  1257. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1258. }
  1259. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1260. // or ';' inside one does not end the list element or the parameter. Section
  1261. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1262. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1263. struct {
  1264. const char *value;
  1265. std::vector<std::string> expected;
  1266. } cases[] = {
  1267. {"text/html;profile=\"a,b\",application/json",
  1268. {"text/html", "application/json"}},
  1269. // A "q=" inside a quoted value is not the weight
  1270. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1271. {"text/html", "application/json"}},
  1272. // The weight after a quoted value still applies
  1273. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1274. {"application/json", "text/html"}},
  1275. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1276. {"application/json", "text/html"}},
  1277. {"text/html;profile=\"a\\\"b\",application/json",
  1278. {"text/html", "application/json"}},
  1279. // An escaped backslash does not escape the '"' after it
  1280. {"text/html;profile=\"a\\\\\",application/json",
  1281. {"text/html", "application/json"}},
  1282. };
  1283. for (const auto &c : cases) {
  1284. std::vector<std::string> result;
  1285. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1286. << "value: " << c.value;
  1287. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1288. }
  1289. }
  1290. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1291. Server svr;
  1292. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1293. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1294. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1295. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1296. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1297. res.set_content("ok", "text/plain");
  1298. });
  1299. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1300. EXPECT_TRUE(false);
  1301. res.set_content("bad request", "text/plain");
  1302. });
  1303. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1304. auto se = detail::scope_exit([&] {
  1305. svr.stop();
  1306. listen_thread.join();
  1307. ASSERT_FALSE(svr.is_running());
  1308. });
  1309. svr.wait_until_ready();
  1310. Client cli("localhost", PORT);
  1311. {
  1312. auto res = cli.Get(
  1313. "/accept_ok",
  1314. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1316. EXPECT_EQ(StatusCode::OK_200, res->status);
  1317. }
  1318. {
  1319. auto res = cli.Get("/accept_bad_request",
  1320. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1322. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1323. }
  1324. }
  1325. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1326. Server svr;
  1327. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1328. res.set_content("ok", "text/plain");
  1329. });
  1330. std::atomic<int> start_count{0};
  1331. std::atomic<bool> running_when_called{false};
  1332. svr.set_start_handler([&]() {
  1333. running_when_called = svr.is_running();
  1334. start_count++;
  1335. });
  1336. auto port = svr.bind_to_any_port(HOST);
  1337. std::thread t([&]() { svr.listen_after_bind(); });
  1338. auto se = detail::scope_exit([&] {
  1339. svr.stop();
  1340. t.join();
  1341. ASSERT_FALSE(svr.is_running());
  1342. });
  1343. svr.wait_until_ready();
  1344. // A successful request proves the accept loop is running, which the start
  1345. // handler precedes; so by now the handler must have run exactly once.
  1346. Client cli(HOST, port);
  1347. cli.set_connection_timeout(std::chrono::seconds(5));
  1348. auto res = cli.Get("/");
  1349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1350. EXPECT_EQ(StatusCode::OK_200, res->status);
  1351. EXPECT_EQ(1, start_count.load());
  1352. EXPECT_TRUE(running_when_called.load());
  1353. }
  1354. TEST(DivideTest, DivideStringTests) {
  1355. auto divide = [](const std::string &str, char d) {
  1356. std::string lhs;
  1357. std::string rhs;
  1358. detail::divide(str, d,
  1359. [&](const char *lhs_data, std::size_t lhs_size,
  1360. const char *rhs_data, std::size_t rhs_size) {
  1361. lhs.assign(lhs_data, lhs_size);
  1362. rhs.assign(rhs_data, rhs_size);
  1363. });
  1364. return std::make_pair(std::move(lhs), std::move(rhs));
  1365. };
  1366. {
  1367. const auto res = divide("", '=');
  1368. EXPECT_EQ(res.first, "");
  1369. EXPECT_EQ(res.second, "");
  1370. }
  1371. {
  1372. const auto res = divide("=", '=');
  1373. EXPECT_EQ(res.first, "");
  1374. EXPECT_EQ(res.second, "");
  1375. }
  1376. {
  1377. const auto res = divide(" ", '=');
  1378. EXPECT_EQ(res.first, " ");
  1379. EXPECT_EQ(res.second, "");
  1380. }
  1381. {
  1382. const auto res = divide("a", '=');
  1383. EXPECT_EQ(res.first, "a");
  1384. EXPECT_EQ(res.second, "");
  1385. }
  1386. {
  1387. const auto res = divide("a=", '=');
  1388. EXPECT_EQ(res.first, "a");
  1389. EXPECT_EQ(res.second, "");
  1390. }
  1391. {
  1392. const auto res = divide("=b", '=');
  1393. EXPECT_EQ(res.first, "");
  1394. EXPECT_EQ(res.second, "b");
  1395. }
  1396. {
  1397. const auto res = divide("a=b", '=');
  1398. EXPECT_EQ(res.first, "a");
  1399. EXPECT_EQ(res.second, "b");
  1400. }
  1401. {
  1402. const auto res = divide("a=b=", '=');
  1403. EXPECT_EQ(res.first, "a");
  1404. EXPECT_EQ(res.second, "b=");
  1405. }
  1406. {
  1407. const auto res = divide("a=b=c", '=');
  1408. EXPECT_EQ(res.first, "a");
  1409. EXPECT_EQ(res.second, "b=c");
  1410. }
  1411. }
  1412. TEST(SplitTest, ParseQueryString) {
  1413. string s = "key1=val1&key2=val2&key3=val3";
  1414. Params dic;
  1415. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1416. [&](const char *b, const char *e) {
  1417. string key, val;
  1418. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1419. if (key.empty()) {
  1420. key.assign(b2, e2);
  1421. } else {
  1422. val.assign(b2, e2);
  1423. }
  1424. });
  1425. dic.emplace(key, val);
  1426. });
  1427. EXPECT_EQ("val1", dic.find("key1")->second);
  1428. EXPECT_EQ("val2", dic.find("key2")->second);
  1429. EXPECT_EQ("val3", dic.find("key3")->second);
  1430. }
  1431. TEST(SplitTest, ParseInvalidQueryTests) {
  1432. {
  1433. string s = " ";
  1434. Params dict;
  1435. detail::parse_query_text(s, dict);
  1436. EXPECT_TRUE(dict.empty());
  1437. }
  1438. {
  1439. string s = " = =";
  1440. Params dict;
  1441. detail::parse_query_text(s, dict);
  1442. EXPECT_TRUE(dict.empty());
  1443. }
  1444. }
  1445. TEST(ParseQueryTest, ParseQueryString) {
  1446. {
  1447. std::string s = "key1=val1&key2=val2&key3=val3";
  1448. Params dic;
  1449. detail::parse_query_text(s, dic);
  1450. EXPECT_EQ("val1", dic.find("key1")->second);
  1451. EXPECT_EQ("val2", dic.find("key2")->second);
  1452. EXPECT_EQ("val3", dic.find("key3")->second);
  1453. }
  1454. {
  1455. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1456. Params dic;
  1457. detail::parse_query_text(s, dic);
  1458. EXPECT_EQ("", dic.find("key1")->second);
  1459. EXPECT_EQ("val1", dic.find("key2")->second);
  1460. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1461. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1462. }
  1463. }
  1464. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1465. Params dic;
  1466. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1467. dic.emplace("key1", "val1");
  1468. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1469. dic.emplace("key2", "val2");
  1470. dic.emplace("key3", "val3");
  1471. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1472. }
  1473. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1474. Params params;
  1475. params.emplace("a", "1");
  1476. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1477. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1478. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1479. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1480. // Long enough to overflow the stack when matched with std::regex.
  1481. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1482. EXPECT_EQ("/p?" + long_query + "&a=1",
  1483. append_query_params("/p?" + long_query, params));
  1484. }
  1485. // Joins every entry of a Headers or Params into "key=value " so a whole
  1486. // traversal can be compared in one assertion. Both are instantiations of the
  1487. // same insertion-ordered container, so one helper serves both.
  1488. template <typename Map> static std::string entries_to_string(const Map &m) {
  1489. std::string s;
  1490. for (const auto &entry : m) {
  1491. s += entry.first + "=" + entry.second + " ";
  1492. }
  1493. return s;
  1494. }
  1495. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1496. // Params used to be a std::multimap, which sorted by name and handed the
  1497. // caller's query back alphabetised. A client signing its query string could
  1498. // not reproduce the order it asked for.
  1499. Params dic;
  1500. dic.emplace("zulu", "1");
  1501. dic.emplace("alpha", "2");
  1502. dic.emplace("mike", "3");
  1503. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1504. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1505. }
  1506. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1507. Params dic;
  1508. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1509. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1510. }
  1511. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1512. Request req;
  1513. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1514. req.params);
  1515. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1516. EXPECT_EQ("first", req.get_param_value("tag"));
  1517. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1518. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1519. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1520. EXPECT_EQ("", req.get_param_value("tag", 3));
  1521. }
  1522. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1523. // Params shares its container with Headers, which matches field names
  1524. // case-insensitively. Parameter names must not pick that up.
  1525. Params dic;
  1526. dic.emplace("Key", "upper");
  1527. dic.emplace("key", "lower");
  1528. EXPECT_EQ(2U, dic.size());
  1529. EXPECT_EQ(1U, dic.count("Key"));
  1530. EXPECT_EQ(1U, dic.count("key"));
  1531. EXPECT_EQ("upper", dic.find("Key")->second);
  1532. EXPECT_EQ("lower", dic.find("key")->second);
  1533. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1534. }
  1535. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1536. Server svr;
  1537. std::string order;
  1538. svr.Get("/order", [&](const Request &req, Response &res) {
  1539. order = entries_to_string(req.params);
  1540. res.set_content("ok", "text/plain");
  1541. });
  1542. auto port = svr.bind_to_any_port(HOST);
  1543. thread t = thread([&] { svr.listen_after_bind(); });
  1544. auto se = detail::scope_exit([&] {
  1545. svr.stop();
  1546. t.join();
  1547. ASSERT_FALSE(svr.is_running());
  1548. });
  1549. svr.wait_until_ready();
  1550. Client cli(HOST, port);
  1551. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1552. ASSERT_TRUE(res);
  1553. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1554. }
  1555. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1556. Server svr;
  1557. std::string field_order, file_order;
  1558. svr.Post("/order", [&](const Request &req, Response &res) {
  1559. for (const auto &field : req.form.fields) {
  1560. field_order += field.first + "=" + field.second.content + " ";
  1561. }
  1562. for (const auto &file : req.form.files) {
  1563. file_order += file.first + "=" + file.second.filename + " ";
  1564. }
  1565. res.set_content("ok", "text/plain");
  1566. });
  1567. auto port = svr.bind_to_any_port(HOST);
  1568. thread t = thread([&] { svr.listen_after_bind(); });
  1569. auto se = detail::scope_exit([&] {
  1570. svr.stop();
  1571. t.join();
  1572. ASSERT_FALSE(svr.is_running());
  1573. });
  1574. svr.wait_until_ready();
  1575. UploadFormDataItems items = {
  1576. {"zulu", "1", "", ""},
  1577. {"alpha", "2", "", ""},
  1578. {"mike", "3", "", ""},
  1579. {"zebra", "z", "z.txt", "text/plain"},
  1580. {"apple", "a", "a.txt", "text/plain"},
  1581. };
  1582. Client cli(HOST, port);
  1583. auto res = cli.Post("/order", items);
  1584. ASSERT_TRUE(res);
  1585. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1586. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1587. }
  1588. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1589. Server svr;
  1590. std::vector<std::string> values;
  1591. std::string first, second, out_of_range, order;
  1592. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1593. values = req.form.get_fields("tag");
  1594. first = req.form.get_field("tag", 0);
  1595. second = req.form.get_field("tag", 1);
  1596. out_of_range = req.form.get_field("tag", 2);
  1597. for (const auto &field : req.form.fields) {
  1598. order += field.first + "=" + field.second.content + " ";
  1599. }
  1600. res.set_content("ok", "text/plain");
  1601. });
  1602. auto port = svr.bind_to_any_port(HOST);
  1603. thread t = thread([&] { svr.listen_after_bind(); });
  1604. auto se = detail::scope_exit([&] {
  1605. svr.stop();
  1606. t.join();
  1607. ASSERT_FALSE(svr.is_running());
  1608. });
  1609. svr.wait_until_ready();
  1610. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1611. // not adjacent in the container.
  1612. UploadFormDataItems items = {
  1613. {"tag", "first", "", ""},
  1614. {"other", "x", "", ""},
  1615. {"tag", "second", "", ""},
  1616. };
  1617. Client cli(HOST, port);
  1618. auto res = cli.Post("/repeated", items);
  1619. ASSERT_TRUE(res);
  1620. ASSERT_EQ(2U, values.size());
  1621. EXPECT_EQ("first", values[0]);
  1622. EXPECT_EQ("second", values[1]);
  1623. EXPECT_EQ("first", first);
  1624. EXPECT_EQ("second", second);
  1625. // std::multimap already kept entries sharing a name in insertion order, so
  1626. // everything above passes without this change too. The whole traversal is
  1627. // what tells the two apart: sorting by name would hoist "other" to the front
  1628. // and the two "tag" parts would end up adjacent.
  1629. EXPECT_EQ("tag=first other=x tag=second ", order);
  1630. // Advancing past the last entry of a name used to run off the container;
  1631. // the container's saturating increment makes it return the default instead.
  1632. EXPECT_EQ("", out_of_range);
  1633. }
  1634. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1635. Server svr;
  1636. std::string file_names;
  1637. svr.Post("/upload", [&](const Request &req, Response &res) {
  1638. for (const auto &file : req.form.files) {
  1639. file_names += file.first + "|" + file.second.filename + " ";
  1640. }
  1641. res.set_content("ok", "text/plain");
  1642. });
  1643. auto port = svr.bind_to_any_port(HOST);
  1644. thread t = thread([&] { svr.listen_after_bind(); });
  1645. auto se = detail::scope_exit([&] {
  1646. svr.stop();
  1647. t.join();
  1648. ASSERT_FALSE(svr.is_running());
  1649. });
  1650. svr.wait_until_ready();
  1651. // A trailing backslash would otherwise escape the closing quote.
  1652. UploadFormDataItems items = {
  1653. {"dir\\", "x", "a.txt", "text/plain"},
  1654. {"b", "y", "a\\\\b.txt", "text/plain"},
  1655. };
  1656. Client cli(HOST, port);
  1657. auto res = cli.Post("/upload", items);
  1658. ASSERT_TRUE(res);
  1659. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1660. }
  1661. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1662. // Server::read_content() keeps a FormFields::iterator alive across the
  1663. // content callbacks that fill the part it points at. The container is
  1664. // vector-backed, so a later emplace can reallocate and invalidate an older
  1665. // iterator; 64 parts grow the vector through seven reallocations, which
  1666. // checks that every part's content still lands in its own entry.
  1667. const size_t part_count = 64;
  1668. // One formula for both the parts sent and the values expected back, so the
  1669. // two cannot drift apart.
  1670. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1671. auto content_of = [](size_t i) {
  1672. return std::string(64, static_cast<char>('a' + (i % 26)));
  1673. };
  1674. Server svr;
  1675. std::vector<std::pair<std::string, std::string>> received;
  1676. svr.Post("/many", [&](const Request &req, Response &res) {
  1677. for (const auto &field : req.form.fields) {
  1678. received.emplace_back(field.first, field.second.content);
  1679. }
  1680. res.set_content("ok", "text/plain");
  1681. });
  1682. auto port = svr.bind_to_any_port(HOST);
  1683. thread t = thread([&] { svr.listen_after_bind(); });
  1684. auto se = detail::scope_exit([&] {
  1685. svr.stop();
  1686. t.join();
  1687. ASSERT_FALSE(svr.is_running());
  1688. });
  1689. svr.wait_until_ready();
  1690. UploadFormDataItems items;
  1691. for (size_t i = 0; i < part_count; i++) {
  1692. items.push_back({name_of(i), content_of(i), "", ""});
  1693. }
  1694. Client cli(HOST, port);
  1695. auto res = cli.Post("/many", items);
  1696. ASSERT_TRUE(res);
  1697. ASSERT_EQ(part_count, received.size());
  1698. for (size_t i = 0; i < part_count; i++) {
  1699. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1700. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1701. }
  1702. }
  1703. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1704. string content_type = "multipart/form-data; boundary=something";
  1705. string boundary;
  1706. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1707. EXPECT_TRUE(ret);
  1708. EXPECT_EQ(boundary, "something");
  1709. }
  1710. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1711. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1712. string boundary;
  1713. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1714. EXPECT_TRUE(ret);
  1715. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1716. }
  1717. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1718. string content_type =
  1719. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1720. string boundary;
  1721. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1722. EXPECT_TRUE(ret);
  1723. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1724. }
  1725. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1726. string content_type =
  1727. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1728. string boundary;
  1729. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1730. EXPECT_TRUE(ret);
  1731. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1732. }
  1733. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1734. const string boundary(70, 'a');
  1735. string content_type = "multipart/form-data; boundary=" + boundary;
  1736. string parsed;
  1737. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1738. EXPECT_TRUE(ret);
  1739. EXPECT_EQ(parsed, boundary);
  1740. }
  1741. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1742. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1743. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1744. string parsed;
  1745. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1746. EXPECT_FALSE(ret);
  1747. }
  1748. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1749. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1750. // is 72 characters on the wire and still valid.
  1751. const string boundary(70, 'a');
  1752. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1753. string parsed;
  1754. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1755. EXPECT_EQ(parsed, boundary);
  1756. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1757. parsed.clear();
  1758. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1759. }
  1760. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1761. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1762. // The parameter parser must not treat that '=' as the key/value separator.
  1763. string content_type =
  1764. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1765. "charset=UTF-8";
  1766. string parsed;
  1767. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1768. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1769. }
  1770. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1771. // A ';' inside the quoted-string is part of the value, not a parameter
  1772. // separator, so it must not truncate the boundary.
  1773. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1774. string parsed;
  1775. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1776. EXPECT_EQ(parsed, "a;b");
  1777. }
  1778. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1779. string parsed;
  1780. EXPECT_TRUE(detail::parse_multipart_boundary(
  1781. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1782. EXPECT_EQ("a\\b", parsed);
  1783. EXPECT_TRUE(detail::parse_multipart_boundary(
  1784. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1785. EXPECT_EQ("a\"b", parsed);
  1786. }
  1787. TEST(ParseDispositionParamsTest, QuotedValues) {
  1788. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1789. // ';' and '=' are ordinary characters inside one.
  1790. struct {
  1791. const char *value;
  1792. std::vector<std::pair<const char *, const char *>> expected;
  1793. } cases[] = {
  1794. {"name=\"file1\"; filename=\"a.txt\"",
  1795. {{"name", "file1"}, {"filename", "a.txt"}}},
  1796. // MIME parameter names are case-insensitive, but their values are not.
  1797. {"NaMe=\"Upload\"; FiLeNaMe=\"Report.TXT\"",
  1798. {{"name", "Upload"}, {"filename", "Report.TXT"}}},
  1799. // Whitespace around '=' and ';' is still trimmed
  1800. {"name=\"file2\" ;filename = \"a.html\"",
  1801. {{"name", "file2"}, {"filename", "a.html"}}},
  1802. // '=' inside the value used to leave only the text after the last one
  1803. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1804. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1805. {"name=\"x=y\"", {{"name", "x=y"}}},
  1806. // ';' inside the value used to truncate the pair and leave a bogus one
  1807. {"name=\"file3\"; filename=\"a;b.txt\"",
  1808. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1809. // An unquoted value keeps working, and so does filename*
  1810. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1811. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1812. // A parameter with no key is dropped rather than turned into one whose
  1813. // key is the value
  1814. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1815. // An escaped quote does not end the value
  1816. {"name=\"a\\\"; filename=evil.php\"",
  1817. {{"name", "a\"; filename=evil.php"}}},
  1818. // Other backslashes, as in a Windows path, are kept
  1819. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1820. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1821. };
  1822. for (const auto &c : cases) {
  1823. Params params;
  1824. detail::parse_disposition_params(c.value, params);
  1825. for (const auto &kv : c.expected) {
  1826. auto it = params.find(kv.first);
  1827. ASSERT_NE(it, params.end())
  1828. << "value: " << c.value << ", key: " << kv.first;
  1829. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1830. }
  1831. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1832. }
  1833. }
  1834. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1835. Server svr;
  1836. std::string filename;
  1837. std::string content;
  1838. svr.Post("/upload", [&](const Request &req, Response &) {
  1839. const auto &file = req.form.get_file("file");
  1840. filename = file.filename;
  1841. content = file.content;
  1842. });
  1843. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1844. auto se = detail::scope_exit([&] {
  1845. svr.stop();
  1846. thread.join();
  1847. ASSERT_FALSE(svr.is_running());
  1848. });
  1849. svr.wait_until_ready();
  1850. std::string body = "--B\r\n"
  1851. "Content-Disposition: form-data; name=\"file\"; "
  1852. "filename=\"a.txt\"\r\n"
  1853. "Content-Type: text/plain\r\n"
  1854. "\r\n"
  1855. "hello\r\n"
  1856. "--B--\r\n";
  1857. Client cli(HOST, PORT);
  1858. auto res = cli.Post(
  1859. "/upload",
  1860. [&](size_t offset, DataSink &sink) {
  1861. if (offset < body.size()) {
  1862. sink.write(&body[offset], 1);
  1863. } else {
  1864. sink.done();
  1865. }
  1866. return true;
  1867. },
  1868. "multipart/form-data; boundary=B");
  1869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1870. EXPECT_EQ(StatusCode::OK_200, res->status);
  1871. EXPECT_EQ("a.txt", filename);
  1872. EXPECT_EQ("hello", content);
  1873. }
  1874. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1875. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1876. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1877. Server svr;
  1878. std::string field_value, file_name, file_filename;
  1879. bool has_field = false, has_file = false;
  1880. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1881. has_field = req.form.has_field("x=y");
  1882. field_value = req.form.get_field("x=y");
  1883. has_file = req.form.has_file("file1");
  1884. const auto &file = req.form.get_file("file1");
  1885. file_name = file.name;
  1886. file_filename = file.filename;
  1887. res.set_content("ok", "text/plain");
  1888. });
  1889. auto port = svr.bind_to_any_port(HOST);
  1890. thread t = thread([&] { svr.listen_after_bind(); });
  1891. auto se = detail::scope_exit([&] {
  1892. svr.stop();
  1893. t.join();
  1894. ASSERT_FALSE(svr.is_running());
  1895. });
  1896. svr.wait_until_ready();
  1897. UploadFormDataItems items = {
  1898. {"x=y", "field-value", "", ""},
  1899. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1900. };
  1901. Client cli(HOST, port);
  1902. auto res = cli.Post("/quoted", items);
  1903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1904. ASSERT_EQ(StatusCode::OK_200, res->status);
  1905. EXPECT_TRUE(has_field);
  1906. EXPECT_EQ("field-value", field_value);
  1907. EXPECT_TRUE(has_file);
  1908. EXPECT_EQ("file1", file_name);
  1909. EXPECT_EQ("a;b=report.pdf", file_filename);
  1910. }
  1911. TEST(GetHeaderValueTest, DefaultValue) {
  1912. Headers headers = {{"Dummy", "Dummy"}};
  1913. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1914. EXPECT_STREQ("text/plain", val);
  1915. }
  1916. TEST(GetHeaderValueTest, DefaultValueInt) {
  1917. Headers headers = {{"Dummy", "Dummy"}};
  1918. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1919. EXPECT_EQ(100ull, val);
  1920. }
  1921. TEST(GetHeaderValueTest, RegularValue) {
  1922. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1923. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1924. EXPECT_STREQ("text/html", val);
  1925. }
  1926. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1927. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1928. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1929. EXPECT_STREQ("text/html", val);
  1930. }
  1931. TEST(GetHeaderValueTest, SetContent) {
  1932. Response res;
  1933. res.set_content("html", "text/html");
  1934. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1935. res.set_content("text", "text/plain");
  1936. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1937. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1938. }
  1939. TEST(GetHeaderValueTest, RegularValueInt) {
  1940. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1941. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1942. EXPECT_EQ(100ull, val);
  1943. }
  1944. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1945. Headers headers = {{"Content-Length", "x"}};
  1946. auto is_invalid_value = false;
  1947. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1948. is_invalid_value);
  1949. EXPECT_EQ(0ull, val);
  1950. EXPECT_TRUE(is_invalid_value);
  1951. }
  1952. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1953. // An all-digit value that overflows size_t must be reported as invalid, not
  1954. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1955. // a large length to a small one on 32-bit builds, leaving the framing length
  1956. // wrong while is_invalid_value stayed false.
  1957. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1958. auto is_invalid_value = false;
  1959. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1960. is_invalid_value);
  1961. EXPECT_TRUE(is_invalid_value);
  1962. // A well-formed length is unaffected.
  1963. Headers ok = {{"Content-Length", "1234"}};
  1964. is_invalid_value = false;
  1965. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1966. is_invalid_value);
  1967. EXPECT_EQ(1234ull, val);
  1968. EXPECT_FALSE(is_invalid_value);
  1969. }
  1970. TEST(GetHeaderValueTest, Range) {
  1971. {
  1972. Headers headers = {make_range_header({{1, -1}})};
  1973. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1974. EXPECT_STREQ("bytes=1-", val);
  1975. }
  1976. {
  1977. Headers headers = {make_range_header({{-1, 1}})};
  1978. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1979. EXPECT_STREQ("bytes=-1", val);
  1980. }
  1981. {
  1982. Headers headers = {make_range_header({{1, 10}})};
  1983. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1984. EXPECT_STREQ("bytes=1-10", val);
  1985. }
  1986. {
  1987. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1988. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1989. EXPECT_STREQ("bytes=1-10, 100-", val);
  1990. }
  1991. {
  1992. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1993. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1994. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1995. }
  1996. {
  1997. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1998. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1999. EXPECT_STREQ("bytes=0-0, -1", val);
  2000. }
  2001. }
  2002. TEST(BearerTokenAuthTest, SchemeValidation) {
  2003. // A value shorter than "Bearer " must not throw from the fixed-length
  2004. // substr, and a non-Bearer scheme must not be reported as a token.
  2005. struct {
  2006. const char *value;
  2007. const char *expected;
  2008. } cases[] = {
  2009. {"x", ""},
  2010. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  2011. {"Bearer abc123", "abc123"},
  2012. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  2013. {"Bearer abc123", "abc123"}, // 1*SP after the scheme
  2014. };
  2015. for (const auto &c : cases) {
  2016. Request req;
  2017. req.set_header("Authorization", c.value);
  2018. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  2019. }
  2020. }
  2021. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  2022. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  2023. // to depend on the standard library (libstdc++ handed back duplicates in
  2024. // reverse insertion order, libc++ in insertion order).
  2025. Request req;
  2026. req.set_header("Accept-Encoding", "gzip");
  2027. req.set_header("Accept-Encoding", "deflate");
  2028. req.set_header("Accept-Encoding", "br");
  2029. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  2030. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  2031. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  2032. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  2033. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  2034. }
  2035. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  2036. Request req;
  2037. req.set_header("X-Test", "only");
  2038. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  2039. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  2040. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  2041. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  2042. }
  2043. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  2044. Request req;
  2045. req.set_header("X-First", "1");
  2046. req.set_header("X-Test", "2");
  2047. req.params.emplace("first", "1");
  2048. req.params.emplace("test", "2");
  2049. req.form.fields.emplace("first", FormField{"first", "1", {}});
  2050. req.form.fields.emplace("test", FormField{"test", "2", {}});
  2051. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  2052. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  2053. // The second one is negative when read as a signed value
  2054. const auto max_id = (std::numeric_limits<size_t>::max)();
  2055. for (auto id : {max_id / 2, max_id}) {
  2056. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2057. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2058. EXPECT_EQ("", req.get_param_value("test", id));
  2059. EXPECT_EQ("", req.form.get_field("test", id));
  2060. EXPECT_EQ("", req.form.get_file("test", id).content);
  2061. }
  2062. }
  2063. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2064. Headers headers;
  2065. headers.emplace("Host", "example.com");
  2066. headers.emplace("Accept-Encoding", "gzip");
  2067. headers.emplace("User-Agent", "test");
  2068. headers.emplace("Accept-Encoding", "deflate");
  2069. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2070. "Accept-Encoding=deflate ",
  2071. entries_to_string(headers));
  2072. }
  2073. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2074. Headers headers = {{"Content-Type", "text/html"},
  2075. {"CONTENT-TYPE", "text/xml"}};
  2076. EXPECT_EQ(2U, headers.count("content-type"));
  2077. auto it = headers.find("content-type");
  2078. ASSERT_TRUE(it != headers.end());
  2079. EXPECT_EQ("text/html", it->second);
  2080. }
  2081. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2082. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2083. // drop only those fields and leave everything positioned between them.
  2084. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2085. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2086. auto rng = headers.equal_range("a");
  2087. headers.erase(rng.first, rng.second);
  2088. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2089. }
  2090. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2091. Headers headers = {
  2092. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2093. EXPECT_EQ(3U, headers.erase("A"));
  2094. EXPECT_EQ(0U, headers.count("A"));
  2095. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2096. }
  2097. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2098. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2099. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2100. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2101. }
  2102. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2103. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2104. headers.emplace_front("Host", "example.com");
  2105. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2106. entries_to_string(headers));
  2107. }
  2108. TEST(ParseHeaderValueTest, Range) {
  2109. {
  2110. Ranges ranges;
  2111. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2112. EXPECT_TRUE(ret);
  2113. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2114. }
  2115. {
  2116. Ranges ranges;
  2117. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2118. EXPECT_TRUE(ret);
  2119. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2120. }
  2121. {
  2122. Ranges ranges;
  2123. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2124. EXPECT_TRUE(ret);
  2125. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2126. }
  2127. {
  2128. Ranges ranges;
  2129. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2130. EXPECT_FALSE(ret);
  2131. }
  2132. {
  2133. Ranges ranges;
  2134. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2135. EXPECT_TRUE(ret);
  2136. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2137. }
  2138. {
  2139. Ranges ranges;
  2140. auto ret =
  2141. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2142. EXPECT_TRUE(ret);
  2143. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2144. }
  2145. {
  2146. Ranges ranges;
  2147. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2148. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2149. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2150. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2151. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2152. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2153. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2154. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2155. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2156. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2157. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2158. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2159. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2160. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2161. EXPECT_FALSE(
  2162. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2163. EXPECT_TRUE(ranges.empty());
  2164. }
  2165. {
  2166. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2167. // remainder of the representation, so it stays accepted.
  2168. Ranges ranges;
  2169. auto ret =
  2170. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2171. EXPECT_TRUE(ret);
  2172. ASSERT_EQ(1u, ranges.size());
  2173. EXPECT_EQ(0, ranges[0].first);
  2174. EXPECT_EQ(-1, ranges[0].second);
  2175. }
  2176. // RFC 9110 14.1: range unit names are case-insensitive.
  2177. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2178. Ranges ranges;
  2179. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2180. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2181. }
  2182. }
  2183. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2184. Request req;
  2185. req.set_header("Accept-Encoding", "gzip");
  2186. Response res;
  2187. res.set_header("Content-Type", "text/plain");
  2188. auto ret = detail::encoding_type(req, res);
  2189. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2190. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2191. #else
  2192. EXPECT_TRUE(ret == detail::EncodingType::None);
  2193. #endif
  2194. }
  2195. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2196. Request req;
  2197. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2198. Response res;
  2199. res.set_header("Content-Type", "text/plain");
  2200. auto ret = detail::encoding_type(req, res);
  2201. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2202. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2203. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2204. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2205. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2206. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2207. #else
  2208. EXPECT_TRUE(ret == detail::EncodingType::None);
  2209. #endif
  2210. }
  2211. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2212. Request req;
  2213. req.set_header("Accept-Encoding",
  2214. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2215. Response res;
  2216. res.set_header("Content-Type", "text/plain");
  2217. auto ret = detail::encoding_type(req, res);
  2218. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2219. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2220. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2221. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2222. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2223. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2224. #else
  2225. EXPECT_TRUE(ret == detail::EncodingType::None);
  2226. #endif
  2227. }
  2228. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2229. // All supported encodings rejected with q=0 should return None
  2230. Request req;
  2231. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2232. Response res;
  2233. res.set_header("Content-Type", "text/plain");
  2234. auto ret = detail::encoding_type(req, res);
  2235. EXPECT_TRUE(ret == detail::EncodingType::None);
  2236. }
  2237. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2238. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2239. Request req;
  2240. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2241. Response res;
  2242. res.set_header("Content-Type", "text/plain");
  2243. auto ret = detail::encoding_type(req, res);
  2244. EXPECT_TRUE(ret == detail::EncodingType::None);
  2245. }
  2246. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2247. Request req;
  2248. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2249. Response res;
  2250. res.set_header("Content-Type", "text/plain");
  2251. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2252. }
  2253. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2254. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2255. Request req;
  2256. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2257. Response res;
  2258. res.set_header("Content-Type", "text/plain");
  2259. auto ret = detail::encoding_type(req, res);
  2260. EXPECT_TRUE(ret == detail::EncodingType::None);
  2261. }
  2262. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2263. // RFC 7231: Accept-Encoding values are case-insensitive
  2264. Request req;
  2265. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2266. Response res;
  2267. res.set_header("Content-Type", "text/plain");
  2268. auto ret = detail::encoding_type(req, res);
  2269. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2270. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2271. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2272. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2273. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2274. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2275. #else
  2276. EXPECT_TRUE(ret == detail::EncodingType::None);
  2277. #endif
  2278. }
  2279. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2280. // q value should determine priority, not hardcoded order
  2281. Request req;
  2282. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2283. Response res;
  2284. res.set_header("Content-Type", "text/plain");
  2285. auto ret = detail::encoding_type(req, res);
  2286. // gzip has highest q=1.0, so it should be selected even though
  2287. // br and zstd are also supported
  2288. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2289. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2290. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2291. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2292. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2293. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2294. #else
  2295. EXPECT_TRUE(ret == detail::EncodingType::None);
  2296. #endif
  2297. }
  2298. TEST(BufferStreamTest, read) {
  2299. detail::BufferStream strm1;
  2300. Stream &strm = strm1;
  2301. EXPECT_EQ(5, strm.write("hello"));
  2302. char buf[512];
  2303. EXPECT_EQ(2, strm.read(buf, 2));
  2304. EXPECT_EQ('h', buf[0]);
  2305. EXPECT_EQ('e', buf[1]);
  2306. EXPECT_EQ(2, strm.read(buf, 2));
  2307. EXPECT_EQ('l', buf[0]);
  2308. EXPECT_EQ('l', buf[1]);
  2309. EXPECT_EQ(1, strm.read(buf, 1));
  2310. EXPECT_EQ('o', buf[0]);
  2311. EXPECT_EQ(0, strm.read(buf, 1));
  2312. }
  2313. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2314. auto host = "www.httpwatch.com";
  2315. auto ip = hosted_at(host);
  2316. EXPECT_EQ("23.96.13.243", ip);
  2317. std::vector<std::string> addrs;
  2318. hosted_at(host, addrs);
  2319. EXPECT_EQ(1u, addrs.size());
  2320. }
  2321. #if 0 // It depends on each test environment...
  2322. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2323. auto host = "www.youtube.com";
  2324. std::vector<std::string> addrs;
  2325. hosted_at(host, addrs);
  2326. EXPECT_EQ(20u, addrs.size());
  2327. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2328. EXPECT_TRUE(it != addrs.end());
  2329. }
  2330. #endif
  2331. class ChunkedEncodingTest : public ::testing::Test {
  2332. protected:
  2333. ChunkedEncodingTest()
  2334. : cli_(HOST, PORT)
  2335. #ifdef CPPHTTPLIB_SSL_ENABLED
  2336. ,
  2337. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2338. #endif
  2339. {
  2340. cli_.set_connection_timeout(2);
  2341. #ifdef CPPHTTPLIB_SSL_ENABLED
  2342. cli_.enable_server_certificate_verification(false);
  2343. #endif
  2344. }
  2345. virtual void SetUp() {
  2346. read_file("./image.jpg", image_data_);
  2347. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2348. res.set_content("Hello World!", "text/plain");
  2349. });
  2350. svr_.Get(
  2351. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2352. res.set_chunked_content_provider(
  2353. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2354. size_t remaining = image_data_.size() - offset;
  2355. if (remaining == 0) {
  2356. sink.done();
  2357. } else {
  2358. constexpr size_t CHUNK_SIZE = 1024;
  2359. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2360. sink.write(&image_data_[offset], send_size);
  2361. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2362. }
  2363. return true;
  2364. });
  2365. });
  2366. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2367. svr_.wait_until_ready();
  2368. }
  2369. virtual void TearDown() {
  2370. svr_.stop();
  2371. if (!request_threads_.empty()) {
  2372. std::this_thread::sleep_for(std::chrono::seconds(1));
  2373. for (auto &t : request_threads_) {
  2374. t.join();
  2375. }
  2376. }
  2377. t_.join();
  2378. }
  2379. #ifdef CPPHTTPLIB_SSL_ENABLED
  2380. SSLClient cli_;
  2381. SSLServer svr_;
  2382. #else
  2383. Client cli_;
  2384. Server svr_;
  2385. #endif
  2386. thread t_;
  2387. std::vector<thread> request_threads_;
  2388. std::string image_data_;
  2389. };
  2390. TEST_F(ChunkedEncodingTest, NormalGet) {
  2391. auto res = cli_.Get("/chunked");
  2392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2393. std::string out;
  2394. read_file("./image.jpg", out);
  2395. EXPECT_EQ(StatusCode::OK_200, res->status);
  2396. EXPECT_EQ(out, res->body);
  2397. }
  2398. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2399. std::string body;
  2400. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2401. body.append(data, data_length);
  2402. return true;
  2403. });
  2404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2405. std::string out;
  2406. read_file("./image.jpg", out);
  2407. EXPECT_EQ(StatusCode::OK_200, res->status);
  2408. EXPECT_EQ(out, body);
  2409. }
  2410. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2411. std::string body;
  2412. auto res = cli_.Get(
  2413. "/chunked",
  2414. [&](const Response &response) {
  2415. EXPECT_EQ(StatusCode::OK_200, response.status);
  2416. return true;
  2417. },
  2418. [&](const char *data, size_t data_length) {
  2419. body.append(data, data_length);
  2420. return true;
  2421. });
  2422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2423. std::string out;
  2424. read_file("./image.jpg", out);
  2425. EXPECT_EQ(StatusCode::OK_200, res->status);
  2426. EXPECT_EQ(out, body);
  2427. }
  2428. TEST(RangeTest, FromHTTPBin_Online) {
  2429. auto host = "httpbingo.org";
  2430. auto path = std::string{"/range/32"};
  2431. #ifdef CPPHTTPLIB_SSL_ENABLED
  2432. auto port = 443;
  2433. SSLClient cli(host, port);
  2434. #else
  2435. auto port = 80;
  2436. Client cli(host, port);
  2437. #endif
  2438. cli.set_connection_timeout(5);
  2439. {
  2440. auto res = retry_service_failures([&] { return cli.Get(path); });
  2441. SKIP_ON_SERVICE_FAILURE(res);
  2442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2443. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2444. EXPECT_EQ(StatusCode::OK_200, res->status);
  2445. }
  2446. {
  2447. Headers headers = {make_range_header({{1, -1}})};
  2448. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2449. SKIP_ON_SERVICE_FAILURE(res);
  2450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2451. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2452. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2453. }
  2454. {
  2455. Headers headers = {make_range_header({{1, 10}})};
  2456. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2457. SKIP_ON_SERVICE_FAILURE(res);
  2458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2459. EXPECT_EQ("bcdefghijk", res->body);
  2460. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2461. }
  2462. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2463. // entire resource, while the original httpbin returned 200. Both are
  2464. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2465. {
  2466. Headers headers = {make_range_header({{0, 31}})};
  2467. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2468. SKIP_ON_SERVICE_FAILURE(res);
  2469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2470. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2471. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2472. res->status == StatusCode::PartialContent_206);
  2473. }
  2474. {
  2475. Headers headers = {make_range_header({{0, -1}})};
  2476. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2477. SKIP_ON_SERVICE_FAILURE(res);
  2478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2479. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2480. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2481. res->status == StatusCode::PartialContent_206);
  2482. }
  2483. // go-httpbin returns 206 with clamped range for over-range requests,
  2484. // while the original httpbin returned 416. Both behaviors are observed
  2485. // in real servers, so we only verify the request succeeds.
  2486. {
  2487. Headers headers = {make_range_header({{0, 32}})};
  2488. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2489. SKIP_ON_SERVICE_FAILURE(res);
  2490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2491. }
  2492. }
  2493. TEST(RangeTest, IgnoredForPost) {
  2494. Server svr;
  2495. svr.Post("/", [](const Request &, Response &res) {
  2496. res.set_content("abcdefg", "text/plain");
  2497. });
  2498. auto port = svr.bind_to_any_port(HOST);
  2499. ASSERT_GT(port, 0);
  2500. thread t = thread([&] { svr.listen_after_bind(); });
  2501. auto se = detail::scope_exit([&] {
  2502. svr.stop();
  2503. t.join();
  2504. ASSERT_FALSE(svr.is_running());
  2505. });
  2506. svr.wait_until_ready();
  2507. Client cli(HOST, port);
  2508. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2509. auto res = cli.Post("/", Headers{{"Range", range}});
  2510. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2511. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2512. EXPECT_EQ("abcdefg", res->body) << range;
  2513. }
  2514. }
  2515. TEST(RangeTest, IgnoredForUnknownUnit) {
  2516. Server svr;
  2517. svr.Get("/", [](const Request &, Response &res) {
  2518. res.set_content("abcdefg", "text/plain");
  2519. });
  2520. auto port = svr.bind_to_any_port(HOST);
  2521. ASSERT_GT(port, 0);
  2522. thread t = thread([&] { svr.listen_after_bind(); });
  2523. auto se = detail::scope_exit([&] {
  2524. svr.stop();
  2525. t.join();
  2526. ASSERT_FALSE(svr.is_running());
  2527. });
  2528. svr.wait_until_ready();
  2529. Client cli(HOST, port);
  2530. for (auto range : {"items=1-2", "none=x"}) {
  2531. auto res = cli.Get("/", Headers{{"Range", range}});
  2532. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2533. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2534. EXPECT_EQ("abcdefg", res->body) << range;
  2535. }
  2536. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2537. ASSERT_TRUE(res) << to_string(res.error());
  2538. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2539. }
  2540. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2541. auto host = "unresolvableaddress.local";
  2542. auto path = std::string{"/"};
  2543. #ifdef CPPHTTPLIB_SSL_ENABLED
  2544. auto port = 443;
  2545. SSLClient cli(host, port);
  2546. #else
  2547. auto port = 80;
  2548. Client cli(host, port);
  2549. #endif
  2550. cli.set_connection_timeout(1);
  2551. {
  2552. auto res = cli.Get(path);
  2553. ASSERT_FALSE(res);
  2554. }
  2555. std::this_thread::sleep_for(std::chrono::seconds(8));
  2556. }
  2557. #if defined(__linux__) && defined(__GLIBC__) && \
  2558. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2559. // Forward declaration: in split builds split.py strips `inline` and moves the
  2560. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2561. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2562. // against the symbol in both header-only and split builds.
  2563. namespace httplib {
  2564. namespace detail {
  2565. int getaddrinfo_with_timeout(const char *node, const char *service,
  2566. const struct addrinfo *hints,
  2567. struct addrinfo **res, time_t timeout_sec);
  2568. } // namespace detail
  2569. } // namespace httplib
  2570. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2571. //
  2572. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2573. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2574. // gai_suspend() call hits the connection timeout the function calls
  2575. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2576. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2577. // still alive and still references the now-destroyed stack frame.
  2578. //
  2579. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2580. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2581. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2582. // and runs them in a container.
  2583. namespace {
  2584. bool should_run_issue_2431_tests() {
  2585. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2586. return v && *v && std::string(v) != "0";
  2587. }
  2588. std::string unique_unresolvable_host(int n) {
  2589. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2590. // glibc still asks the configured nameserver — which is exactly the path
  2591. // we want to exercise. A unique label per call avoids the resolver cache.
  2592. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2593. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2594. std::to_string(n) + ".invalid";
  2595. }
  2596. } // namespace
  2597. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2598. if (!should_run_issue_2431_tests()) {
  2599. GTEST_SKIP()
  2600. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2601. }
  2602. for (int i = 0; i < 8; ++i) {
  2603. struct addrinfo hints;
  2604. memset(&hints, 0, sizeof(hints));
  2605. hints.ai_family = AF_UNSPEC;
  2606. hints.ai_socktype = SOCK_STREAM;
  2607. auto host = unique_unresolvable_host(i);
  2608. struct addrinfo *result = nullptr;
  2609. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2610. &result, /*timeout_sec=*/1);
  2611. if (rc == 0 && result) { freeaddrinfo(result); }
  2612. }
  2613. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2614. // stack region they still believe holds their gaicb.
  2615. std::this_thread::sleep_for(std::chrono::seconds(3));
  2616. }
  2617. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2618. if (!should_run_issue_2431_tests()) {
  2619. GTEST_SKIP()
  2620. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2621. }
  2622. std::atomic<bool> stop{false};
  2623. std::vector<std::thread> threads;
  2624. for (int t = 0; t < 8; ++t) {
  2625. threads.emplace_back([t, &stop] {
  2626. int i = 0;
  2627. while (!stop.load(std::memory_order_relaxed)) {
  2628. struct addrinfo hints;
  2629. memset(&hints, 0, sizeof(hints));
  2630. hints.ai_family = AF_UNSPEC;
  2631. hints.ai_socktype = SOCK_STREAM;
  2632. auto host = unique_unresolvable_host(t * 100000 + i++);
  2633. struct addrinfo *result = nullptr;
  2634. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2635. &result, /*timeout_sec=*/1);
  2636. if (rc == 0 && result) { freeaddrinfo(result); }
  2637. }
  2638. });
  2639. }
  2640. std::this_thread::sleep_for(std::chrono::seconds(8));
  2641. stop.store(true, std::memory_order_relaxed);
  2642. for (auto &th : threads) {
  2643. th.join();
  2644. }
  2645. std::this_thread::sleep_for(std::chrono::seconds(3));
  2646. }
  2647. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2648. if (!should_run_issue_2431_tests()) {
  2649. GTEST_SKIP()
  2650. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2651. }
  2652. std::atomic<bool> stop{false};
  2653. std::vector<std::thread> threads;
  2654. for (int t = 0; t < 8; ++t) {
  2655. threads.emplace_back([t, &stop] {
  2656. int i = 0;
  2657. while (!stop.load(std::memory_order_relaxed)) {
  2658. auto host = unique_unresolvable_host(t * 100000 + i++);
  2659. Client cli(host, 80);
  2660. cli.set_connection_timeout(1, 0);
  2661. cli.set_read_timeout(1, 0);
  2662. cli.set_write_timeout(1, 0);
  2663. (void)cli.Get("/");
  2664. }
  2665. });
  2666. }
  2667. std::this_thread::sleep_for(std::chrono::seconds(8));
  2668. stop.store(true, std::memory_order_relaxed);
  2669. for (auto &th : threads) {
  2670. th.join();
  2671. }
  2672. std::this_thread::sleep_for(std::chrono::seconds(3));
  2673. }
  2674. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2675. TEST(ConnectionErrorTest, InvalidHost) {
  2676. auto host = "-abcde.com";
  2677. #ifdef CPPHTTPLIB_SSL_ENABLED
  2678. auto port = 443;
  2679. SSLClient cli(host, port);
  2680. #else
  2681. auto port = 80;
  2682. Client cli(host, port);
  2683. #endif
  2684. cli.set_connection_timeout(std::chrono::seconds(2));
  2685. auto res = cli.Get("/");
  2686. ASSERT_TRUE(!res);
  2687. EXPECT_EQ(Error::Connection, res.error());
  2688. }
  2689. TEST(ConnectionErrorTest, InvalidHost2) {
  2690. auto host = "httpcan.org/";
  2691. #ifdef CPPHTTPLIB_SSL_ENABLED
  2692. SSLClient cli(host);
  2693. #else
  2694. Client cli(host);
  2695. #endif
  2696. cli.set_connection_timeout(std::chrono::seconds(2));
  2697. auto res = cli.Get("/");
  2698. ASSERT_TRUE(!res);
  2699. EXPECT_EQ(Error::Connection, res.error());
  2700. }
  2701. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2702. auto host = "httpcan.org/";
  2703. #ifdef CPPHTTPLIB_SSL_ENABLED
  2704. SSLClient cli(host);
  2705. #else
  2706. Client cli(host);
  2707. #endif
  2708. cli.set_connection_timeout(std::chrono::seconds(2));
  2709. auto res = cli.Get("/");
  2710. ASSERT_TRUE(!res);
  2711. stringstream s;
  2712. s << "error code: " << res.error();
  2713. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2714. }
  2715. TEST(ConnectionErrorTest, InvalidPort) {
  2716. auto host = "localhost";
  2717. auto port = 44380;
  2718. #ifdef CPPHTTPLIB_SSL_ENABLED
  2719. SSLClient cli(host, port);
  2720. #else
  2721. Client cli(host, port);
  2722. #endif
  2723. cli.set_connection_timeout(std::chrono::seconds(2));
  2724. auto res = cli.Get("/");
  2725. ASSERT_TRUE(!res);
  2726. EXPECT_TRUE(Error::Connection == res.error() ||
  2727. Error::ConnectionTimeout == res.error());
  2728. }
  2729. TEST(ConnectionErrorTest, Timeout_Online) {
  2730. auto host = "google.com";
  2731. #ifdef CPPHTTPLIB_SSL_ENABLED
  2732. auto port = 44380;
  2733. SSLClient cli(host, port);
  2734. #else
  2735. auto port = 8080;
  2736. Client cli(host, port);
  2737. #endif
  2738. cli.set_connection_timeout(std::chrono::seconds(2));
  2739. // only probe one address type so that the error reason
  2740. // correlates to the timed-out IPv4, not the unsupported
  2741. // IPv6 connection attempt
  2742. cli.set_address_family(AF_INET);
  2743. auto res = cli.Get("/");
  2744. ASSERT_TRUE(!res);
  2745. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2746. }
  2747. TEST(CancelTest, NoCancel_Online) {
  2748. auto host = "httpbingo.org";
  2749. auto path = std::string{"/range/32"};
  2750. #ifdef CPPHTTPLIB_SSL_ENABLED
  2751. auto port = 443;
  2752. SSLClient cli(host, port);
  2753. #else
  2754. auto port = 80;
  2755. Client cli(host, port);
  2756. #endif
  2757. cli.set_connection_timeout(std::chrono::seconds(5));
  2758. auto res = retry_service_failures(
  2759. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return true; }); });
  2760. SKIP_ON_SERVICE_FAILURE(res);
  2761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2762. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2763. EXPECT_EQ(StatusCode::OK_200, res->status);
  2764. }
  2765. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2766. // Use /bytes with a large payload so that the DownloadProgress callback
  2767. // (which only fires for Content-Length responses) is invoked before the
  2768. // entire body is received, giving cancellation a chance to fire.
  2769. auto host = "httpbingo.org";
  2770. auto path = std::string{"/bytes/524288"};
  2771. #ifdef CPPHTTPLIB_SSL_ENABLED
  2772. auto port = 443;
  2773. SSLClient cli(host, port);
  2774. #else
  2775. auto port = 80;
  2776. Client cli(host, port);
  2777. #endif
  2778. auto res = retry_service_failures(
  2779. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return false; }); });
  2780. SKIP_ON_SERVICE_FAILURE(res);
  2781. cli.set_connection_timeout(std::chrono::seconds(5));
  2782. ASSERT_TRUE(!res);
  2783. EXPECT_EQ(Error::Canceled, res.error());
  2784. }
  2785. TEST(CancelTest, WithCancelLargePayload_Online) {
  2786. auto host = "httpbingo.org";
  2787. auto path = std::string{"/bytes/524288"};
  2788. #ifdef CPPHTTPLIB_SSL_ENABLED
  2789. auto port = 443;
  2790. SSLClient cli(host, port);
  2791. #else
  2792. auto port = 80;
  2793. Client cli(host, port);
  2794. #endif
  2795. cli.set_connection_timeout(std::chrono::seconds(5));
  2796. auto res = retry_service_failures([&] {
  2797. auto count = 0;
  2798. return cli.Get(path,
  2799. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2800. });
  2801. SKIP_ON_SERVICE_FAILURE(res);
  2802. ASSERT_TRUE(!res);
  2803. EXPECT_EQ(Error::Canceled, res.error());
  2804. }
  2805. TEST(CancelTest, NoCancelPost) {
  2806. Server svr;
  2807. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2808. res.set_content("Hello World!", "text/plain");
  2809. });
  2810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2811. auto se = detail::scope_exit([&] {
  2812. svr.stop();
  2813. thread.join();
  2814. ASSERT_FALSE(svr.is_running());
  2815. });
  2816. svr.wait_until_ready();
  2817. Client cli(HOST, PORT);
  2818. cli.set_connection_timeout(std::chrono::seconds(5));
  2819. auto res =
  2820. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2821. "application/json", [](uint64_t, uint64_t) { return true; });
  2822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2823. EXPECT_EQ("Hello World!", res->body);
  2824. EXPECT_EQ(StatusCode::OK_200, res->status);
  2825. }
  2826. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2827. Server svr;
  2828. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2829. res.set_content("Hello World!", "text/plain");
  2830. });
  2831. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2832. auto se = detail::scope_exit([&] {
  2833. svr.stop();
  2834. thread.join();
  2835. ASSERT_FALSE(svr.is_running());
  2836. });
  2837. svr.wait_until_ready();
  2838. Client cli(HOST, PORT);
  2839. cli.set_connection_timeout(std::chrono::seconds(5));
  2840. auto res =
  2841. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2842. "application/json", [](uint64_t, uint64_t) { return false; });
  2843. ASSERT_TRUE(!res);
  2844. EXPECT_EQ(Error::Canceled, res.error());
  2845. }
  2846. TEST(CancelTest, WithCancelLargePayloadPost) {
  2847. Server svr;
  2848. svr.set_payload_max_length(200 * 1024 * 1024);
  2849. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2850. res.set_content(LARGE_DATA, "text/plain");
  2851. });
  2852. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2853. auto se = detail::scope_exit([&] {
  2854. svr.stop();
  2855. thread.join();
  2856. ASSERT_FALSE(svr.is_running());
  2857. });
  2858. svr.wait_until_ready();
  2859. Client cli(HOST, PORT);
  2860. cli.set_payload_max_length(200 * 1024 * 1024);
  2861. cli.set_connection_timeout(std::chrono::seconds(5));
  2862. auto res =
  2863. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2864. "application/json", [](uint64_t, uint64_t) { return false; });
  2865. ASSERT_TRUE(!res);
  2866. EXPECT_EQ(Error::Canceled, res.error());
  2867. }
  2868. TEST(CancelTest, NoCancelPut) {
  2869. Server svr;
  2870. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2871. res.set_content("Hello World!", "text/plain");
  2872. });
  2873. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2874. auto se = detail::scope_exit([&] {
  2875. svr.stop();
  2876. thread.join();
  2877. ASSERT_FALSE(svr.is_running());
  2878. });
  2879. svr.wait_until_ready();
  2880. Client cli(HOST, PORT);
  2881. cli.set_connection_timeout(std::chrono::seconds(5));
  2882. auto res =
  2883. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2884. "application/json", [](uint64_t, uint64_t) { return true; });
  2885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2886. EXPECT_EQ("Hello World!", res->body);
  2887. EXPECT_EQ(StatusCode::OK_200, res->status);
  2888. }
  2889. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2890. Server svr;
  2891. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2892. res.set_content("Hello World!", "text/plain");
  2893. });
  2894. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2895. auto se = detail::scope_exit([&] {
  2896. svr.stop();
  2897. thread.join();
  2898. ASSERT_FALSE(svr.is_running());
  2899. });
  2900. svr.wait_until_ready();
  2901. Client cli(HOST, PORT);
  2902. cli.set_connection_timeout(std::chrono::seconds(5));
  2903. auto res =
  2904. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2905. "application/json", [](uint64_t, uint64_t) { return false; });
  2906. ASSERT_TRUE(!res);
  2907. EXPECT_EQ(Error::Canceled, res.error());
  2908. }
  2909. TEST(CancelTest, WithCancelLargePayloadPut) {
  2910. Server svr;
  2911. svr.set_payload_max_length(200 * 1024 * 1024);
  2912. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2913. res.set_content(LARGE_DATA, "text/plain");
  2914. });
  2915. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2916. auto se = detail::scope_exit([&] {
  2917. svr.stop();
  2918. thread.join();
  2919. ASSERT_FALSE(svr.is_running());
  2920. });
  2921. svr.wait_until_ready();
  2922. Client cli(HOST, PORT);
  2923. cli.set_payload_max_length(200 * 1024 * 1024);
  2924. cli.set_connection_timeout(std::chrono::seconds(5));
  2925. auto res =
  2926. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2927. "application/json", [](uint64_t, uint64_t) { return false; });
  2928. ASSERT_TRUE(!res);
  2929. EXPECT_EQ(Error::Canceled, res.error());
  2930. }
  2931. TEST(CancelTest, NoCancelPatch) {
  2932. Server svr;
  2933. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2934. res.set_content("Hello World!", "text/plain");
  2935. });
  2936. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2937. auto se = detail::scope_exit([&] {
  2938. svr.stop();
  2939. thread.join();
  2940. ASSERT_FALSE(svr.is_running());
  2941. });
  2942. svr.wait_until_ready();
  2943. Client cli(HOST, PORT);
  2944. cli.set_connection_timeout(std::chrono::seconds(5));
  2945. auto res =
  2946. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2947. "application/json", [](uint64_t, uint64_t) { return true; });
  2948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2949. EXPECT_EQ("Hello World!", res->body);
  2950. EXPECT_EQ(StatusCode::OK_200, res->status);
  2951. }
  2952. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2953. Server svr;
  2954. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2955. res.set_content("Hello World!", "text/plain");
  2956. });
  2957. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2958. auto se = detail::scope_exit([&] {
  2959. svr.stop();
  2960. thread.join();
  2961. ASSERT_FALSE(svr.is_running());
  2962. });
  2963. svr.wait_until_ready();
  2964. Client cli(HOST, PORT);
  2965. cli.set_connection_timeout(std::chrono::seconds(5));
  2966. auto res =
  2967. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2968. "application/json", [](uint64_t, uint64_t) { return false; });
  2969. ASSERT_TRUE(!res);
  2970. EXPECT_EQ(Error::Canceled, res.error());
  2971. }
  2972. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2973. Server svr;
  2974. svr.set_payload_max_length(200 * 1024 * 1024);
  2975. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2976. res.set_content(LARGE_DATA, "text/plain");
  2977. });
  2978. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2979. auto se = detail::scope_exit([&] {
  2980. svr.stop();
  2981. thread.join();
  2982. ASSERT_FALSE(svr.is_running());
  2983. });
  2984. svr.wait_until_ready();
  2985. Client cli(HOST, PORT);
  2986. cli.set_payload_max_length(200 * 1024 * 1024);
  2987. cli.set_connection_timeout(std::chrono::seconds(5));
  2988. auto res =
  2989. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2990. "application/json", [](uint64_t, uint64_t) { return false; });
  2991. ASSERT_TRUE(!res);
  2992. EXPECT_EQ(Error::Canceled, res.error());
  2993. }
  2994. TEST(CancelTest, NoCancelDelete) {
  2995. Server svr;
  2996. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2997. res.set_content("Hello World!", "text/plain");
  2998. });
  2999. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3000. auto se = detail::scope_exit([&] {
  3001. svr.stop();
  3002. thread.join();
  3003. ASSERT_FALSE(svr.is_running());
  3004. });
  3005. svr.wait_until_ready();
  3006. Client cli(HOST, PORT);
  3007. cli.set_connection_timeout(std::chrono::seconds(5));
  3008. auto res =
  3009. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3010. "application/json", [](uint64_t, uint64_t) { return true; });
  3011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3012. EXPECT_EQ("Hello World!", res->body);
  3013. EXPECT_EQ(StatusCode::OK_200, res->status);
  3014. }
  3015. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  3016. Server svr;
  3017. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3018. res.set_content("Hello World!", "text/plain");
  3019. });
  3020. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3021. auto se = detail::scope_exit([&] {
  3022. svr.stop();
  3023. thread.join();
  3024. ASSERT_FALSE(svr.is_running());
  3025. });
  3026. svr.wait_until_ready();
  3027. Client cli(HOST, PORT);
  3028. cli.set_connection_timeout(std::chrono::seconds(5));
  3029. auto res =
  3030. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3031. "application/json", [](uint64_t, uint64_t) { return false; });
  3032. ASSERT_TRUE(!res);
  3033. EXPECT_EQ(Error::Canceled, res.error());
  3034. }
  3035. TEST(CancelTest, WithCancelLargePayloadDelete) {
  3036. Server svr;
  3037. svr.set_payload_max_length(200 * 1024 * 1024);
  3038. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3039. res.set_content(LARGE_DATA, "text/plain");
  3040. });
  3041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3042. auto se = detail::scope_exit([&] {
  3043. svr.stop();
  3044. thread.join();
  3045. ASSERT_FALSE(svr.is_running());
  3046. });
  3047. svr.wait_until_ready();
  3048. Client cli(HOST, PORT);
  3049. cli.set_payload_max_length(200 * 1024 * 1024);
  3050. cli.set_connection_timeout(std::chrono::seconds(5));
  3051. auto res =
  3052. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3053. "application/json", [](uint64_t, uint64_t) { return false; });
  3054. ASSERT_TRUE(!res);
  3055. EXPECT_EQ(Error::Canceled, res.error());
  3056. }
  3057. // One stop() from another thread ends a request that waits for the response
  3058. TEST(ClientStopTest, StopEndsWaitForResponse) {
  3059. Server svr;
  3060. std::atomic<bool> received{false};
  3061. std::atomic<bool> done{false};
  3062. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  3063. received.store(true);
  3064. while (!done.load()) {
  3065. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3066. }
  3067. res.set_content("Hello World!", "text/plain");
  3068. });
  3069. auto port = svr.bind_to_any_port(HOST);
  3070. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3071. Client cli(HOST, port);
  3072. cli.set_read_timeout(std::chrono::seconds(30));
  3073. std::future<Result> request;
  3074. auto se = detail::scope_exit([&] {
  3075. done.store(true);
  3076. svr.stop();
  3077. thread.join();
  3078. ASSERT_FALSE(svr.is_running());
  3079. });
  3080. svr.wait_until_ready();
  3081. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3082. for (int i = 0; i < 500 && !received.load(); ++i) {
  3083. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3084. }
  3085. ASSERT_TRUE(received.load());
  3086. // Let the client block in the wait for the response
  3087. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3088. auto start = std::chrono::steady_clock::now();
  3089. cli.stop();
  3090. ASSERT_EQ(std::future_status::ready,
  3091. request.wait_for(std::chrono::seconds(5)));
  3092. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3093. auto res = request.get();
  3094. ASSERT_TRUE(!res);
  3095. EXPECT_EQ(Error::Read, res.error());
  3096. }
  3097. // A listener whose backlog completes the TCP connections of clients, and that
  3098. // never answers them
  3099. struct SilentListener {
  3100. socket_t sock = INVALID_SOCKET;
  3101. sockaddr_in addr{};
  3102. int port = 0;
  3103. explicit SilentListener(int backlog = 1) {
  3104. sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3105. addr.sin_family = AF_INET;
  3106. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3107. socklen_t len = sizeof(addr);
  3108. if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) != 0 ||
  3109. ::listen(sock, backlog) != 0 ||
  3110. ::getsockname(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
  3111. detail::close_socket(sock);
  3112. sock = INVALID_SOCKET;
  3113. }
  3114. port = ntohs(addr.sin_port);
  3115. }
  3116. ~SilentListener() { detail::close_socket(sock); }
  3117. // The next connection, whose reads give up after 5 seconds
  3118. socket_t accept() const {
  3119. auto peer = ::accept(sock, nullptr, nullptr);
  3120. if (peer != INVALID_SOCKET) {
  3121. detail::set_socket_opt_time(peer, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3122. }
  3123. return peer;
  3124. }
  3125. };
  3126. static bool receives_a_byte(socket_t peer) {
  3127. char c = 0;
  3128. return detail::read_socket(peer, &c, 1, 0) == 1;
  3129. }
  3130. // Runs op, stops cli once the listener receives the first byte op sends, and
  3131. // expects op to end with error soon after
  3132. template <typename ClientType, typename Op>
  3133. static void expect_stop_ends(ClientType &cli, const SilentListener &listener,
  3134. Op op, Error error = Error::Canceled) {
  3135. auto ended = std::async(std::launch::async, op);
  3136. auto peer = listener.accept();
  3137. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3138. ASSERT_NE(INVALID_SOCKET, peer);
  3139. ASSERT_TRUE(receives_a_byte(peer));
  3140. cli.stop();
  3141. EXPECT_EQ(std::future_status::ready, ended.wait_for(std::chrono::seconds(2)));
  3142. EXPECT_EQ(error, ended.get());
  3143. }
  3144. // Stops itself from another thread as the connection opens, the last moment a
  3145. // stop() cancels it. It waits for stop() at most a second, so a stop() that
  3146. // waits for the connection fails the test instead of hanging it.
  3147. class StoppedAsConnectedClient : public ClientImpl {
  3148. public:
  3149. using ClientImpl::ClientImpl;
  3150. protected:
  3151. bool ensure_socket_connection(Socket &socket, Error &error) override {
  3152. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  3153. stopper_ = std::async(std::launch::async, [this] { stop(); });
  3154. stopper_.wait_for(std::chrono::seconds(1));
  3155. return true;
  3156. }
  3157. private:
  3158. std::future<void> stopper_;
  3159. };
  3160. TEST(ClientStopTest, StopAsTheConnectionOpensEndsTheRequest) {
  3161. SilentListener listener;
  3162. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3163. StoppedAsConnectedClient cli("127.0.0.1", listener.port);
  3164. cli.set_read_timeout(std::chrono::seconds(3));
  3165. EXPECT_EQ(Error::Canceled, cli.Get("/").error());
  3166. auto peer = listener.accept();
  3167. EXPECT_FALSE(receives_a_byte(peer));
  3168. detail::close_socket(peer);
  3169. auto handle = cli.open_stream("GET", "/");
  3170. EXPECT_FALSE(handle.is_valid());
  3171. EXPECT_EQ(Error::Canceled, handle.error);
  3172. peer = listener.accept();
  3173. EXPECT_FALSE(receives_a_byte(peer));
  3174. detail::close_socket(peer);
  3175. }
  3176. #ifdef __linux__
  3177. // A connect that a listener with a full backlog never completes
  3178. TEST(ClientStopTest, StopEndsAConnect) {
  3179. SilentListener listener(0);
  3180. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3181. std::vector<socket_t> backlog;
  3182. auto close_backlog = detail::scope_exit([&] {
  3183. for (auto sock : backlog) {
  3184. detail::close_socket(sock);
  3185. }
  3186. });
  3187. for (int i = 0; i < 8; i++) {
  3188. auto sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  3189. ::connect(sock, reinterpret_cast<const sockaddr *>(&listener.addr),
  3190. sizeof(listener.addr));
  3191. backlog.push_back(sock);
  3192. }
  3193. Client cli("127.0.0.1", listener.port);
  3194. cli.set_connection_timeout(std::chrono::seconds(3));
  3195. auto ended =
  3196. std::async(std::launch::async, [&] { return cli.Get("/").error(); });
  3197. // A stop() before the request starts does not apply to it, so it repeats
  3198. auto status = std::future_status::timeout;
  3199. for (auto i = 0; i < 200 && status != std::future_status::ready; i++) {
  3200. cli.stop();
  3201. status = ended.wait_for(std::chrono::milliseconds(10));
  3202. }
  3203. EXPECT_EQ(std::future_status::ready, status);
  3204. EXPECT_EQ(Error::Canceled, ended.get());
  3205. }
  3206. #endif
  3207. // The stream holds the socket while it waits for the head, out of the reach
  3208. // of shutdown()
  3209. TEST(ClientStopTest, StopEndsTheWaitForTheHeadOfAStream) {
  3210. SilentListener listener;
  3211. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3212. Client cli("127.0.0.1", listener.port);
  3213. cli.set_read_timeout(std::chrono::seconds(3));
  3214. expect_stop_ends(
  3215. cli, listener, [&] { return cli.open_stream("GET", "/").error; },
  3216. Error::Read);
  3217. }
  3218. #ifdef CPPHTTPLIB_SSL_ENABLED
  3219. // A server that never answers the ClientHello
  3220. TEST(ClientStopTest, StopEndsATlsHandshake) {
  3221. SilentListener listener;
  3222. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3223. SSLClient cli("127.0.0.1", listener.port);
  3224. cli.enable_server_certificate_verification(false);
  3225. cli.set_connection_timeout(std::chrono::seconds(3));
  3226. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3227. expect_stop_ends(cli, listener,
  3228. [&] { return cli.open_stream("GET", "/").error; });
  3229. }
  3230. // A proxy that takes the CONNECT and never answers it
  3231. TEST(ClientStopTest, StopEndsAProxyTunnel) {
  3232. SilentListener listener;
  3233. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3234. SSLClient cli("example.com", 443);
  3235. cli.set_proxy("127.0.0.1", listener.port);
  3236. cli.set_read_timeout(std::chrono::seconds(3));
  3237. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3238. }
  3239. #endif
  3240. // A read timeout past what the clock reaches waits for the response
  3241. TEST(ClientReadTimeoutTest, PastTheClockWaitsForTheResponse) {
  3242. SilentListener listener;
  3243. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3244. Client cli("127.0.0.1", listener.port);
  3245. cli.set_read_timeout(
  3246. static_cast<time_t>((std::min)(static_cast<long long>(
  3247. (std::numeric_limits<time_t>::max)()),
  3248. 10000000000LL)),
  3249. 0);
  3250. auto res = std::async(std::launch::async, [&] { return cli.Get("/"); });
  3251. auto peer = listener.accept();
  3252. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3253. ASSERT_NE(INVALID_SOCKET, peer);
  3254. ASSERT_TRUE(receives_a_byte(peer));
  3255. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3256. std::string answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3257. "Connection: close\r\n\r\nok";
  3258. detail::send_socket(peer, answer.data(), answer.size(), 0);
  3259. auto result = res.get();
  3260. ASSERT_TRUE(result);
  3261. EXPECT_EQ("ok", result->body);
  3262. }
  3263. static std::string remove_whitespace(const std::string &input) {
  3264. std::string output;
  3265. output.reserve(input.size());
  3266. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3267. [](unsigned char c) { return !std::isspace(c); });
  3268. return output;
  3269. }
  3270. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3271. auto host = "httpbingo.org";
  3272. auto path = std::string{"/basic-auth/hello/world"};
  3273. #ifdef CPPHTTPLIB_SSL_ENABLED
  3274. auto port = 443;
  3275. SSLClient cli(host, port);
  3276. #else
  3277. auto port = 80;
  3278. Client cli(host, port);
  3279. #endif
  3280. {
  3281. auto res = retry_service_failures([&] { return cli.Get(path); });
  3282. SKIP_ON_SERVICE_FAILURE(res);
  3283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3284. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3285. }
  3286. {
  3287. auto res = retry_service_failures([&] {
  3288. return cli.Get(
  3289. path, Headers{make_basic_authentication_header("hello", "world")});
  3290. });
  3291. SKIP_ON_SERVICE_FAILURE(res);
  3292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3293. auto body = remove_whitespace(res->body);
  3294. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3295. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. }
  3298. {
  3299. cli.set_basic_auth("hello", "world");
  3300. auto res = retry_service_failures([&] { return cli.Get(path); });
  3301. SKIP_ON_SERVICE_FAILURE(res);
  3302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3303. auto body = remove_whitespace(res->body);
  3304. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3305. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3306. EXPECT_EQ(StatusCode::OK_200, res->status);
  3307. }
  3308. {
  3309. cli.set_basic_auth("hello", "bad");
  3310. auto res = retry_service_failures([&] { return cli.Get(path); });
  3311. SKIP_ON_SERVICE_FAILURE(res);
  3312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3313. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3314. }
  3315. {
  3316. cli.set_basic_auth("bad", "world");
  3317. auto res = retry_service_failures([&] { return cli.Get(path); });
  3318. SKIP_ON_SERVICE_FAILURE(res);
  3319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3320. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3321. }
  3322. }
  3323. #ifdef CPPHTTPLIB_SSL_ENABLED
  3324. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3325. auto host = "httpbingo.org";
  3326. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3327. auto paths = std::vector<std::string>{
  3328. "/digest-auth/auth/hello/world/MD5",
  3329. "/digest-auth/auth/hello/world/SHA-256",
  3330. };
  3331. auto port = 443;
  3332. SSLClient cli(host, port);
  3333. {
  3334. auto res = retry_service_failures([&] { return cli.Get(unauth_path); });
  3335. SKIP_ON_SERVICE_FAILURE(res);
  3336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3337. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3338. }
  3339. {
  3340. cli.set_digest_auth("hello", "world");
  3341. for (const auto &path : paths) {
  3342. auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
  3343. SKIP_ON_SERVICE_FAILURE(res);
  3344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3345. auto body = remove_whitespace(res->body);
  3346. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3347. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3348. EXPECT_EQ(StatusCode::OK_200, res->status);
  3349. }
  3350. cli.set_digest_auth("hello", "bad");
  3351. for (const auto &path : paths) {
  3352. auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
  3353. SKIP_ON_SERVICE_FAILURE(res);
  3354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3355. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3356. }
  3357. }
  3358. }
  3359. // Runs one 401 -> Digest-retry round trip with the given WWW-Authenticate
  3360. // field lines (get_combined_header_value() joins them in receipt order) and
  3361. // returns the Authorization header of the retry.
  3362. static std::string
  3363. get_digest_retry_authorization(const std::vector<std::string> &challenges) {
  3364. std::atomic<int> hits{0};
  3365. std::string authorization;
  3366. Server svr;
  3367. svr.Get("/x", [&](const Request &req, Response &res) {
  3368. if (++hits == 1) {
  3369. res.status = StatusCode::Unauthorized_401;
  3370. for (const auto &challenge : challenges) {
  3371. res.set_header("WWW-Authenticate", challenge);
  3372. }
  3373. } else {
  3374. authorization = req.get_header_value("Authorization");
  3375. res.set_content("ok", "text/plain");
  3376. }
  3377. });
  3378. auto port = svr.bind_to_any_port(HOST);
  3379. std::thread t([&]() { svr.listen_after_bind(); });
  3380. auto se = detail::scope_exit([&] {
  3381. svr.stop();
  3382. t.join();
  3383. });
  3384. svr.wait_until_ready();
  3385. Client cli(HOST, port);
  3386. cli.set_digest_auth("hello", "world");
  3387. auto res = cli.Get("/x");
  3388. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  3389. EXPECT_EQ(2, hits.load());
  3390. return authorization;
  3391. }
  3392. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3393. // comma-separated list of challenges, and each challenge may itself carry a
  3394. // comma-separated auth-param list, so a server can legally offer Basic
  3395. // before Digest, either as two field lines or packed into one. Checks that
  3396. // the retry carries a well-formed Digest Authorization header naming
  3397. // expected_realm.
  3398. static void
  3399. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3400. const std::string &expected_realm) {
  3401. auto authorization = get_digest_retry_authorization(challenges);
  3402. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3403. EXPECT_NE(std::string::npos,
  3404. authorization.find("realm=\"" + expected_realm + "\""));
  3405. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3406. }
  3407. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3408. static const char *kDigestChallenge =
  3409. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3410. "algorithm=MD5";
  3411. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3412. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3413. "testrealm");
  3414. }
  3415. // Same challenge list with the schemes in the opposite order, to make sure
  3416. // the fix above didn't just special-case "Basic first".
  3417. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3418. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3419. "testrealm");
  3420. }
  3421. // A comma inside a quoted auth-param value must not be mistaken for the
  3422. // separator between two challenges (or two auth-params).
  3423. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3424. run_digest_challenge_list_test(
  3425. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3426. "algorithm=MD5"},
  3427. "test,realm");
  3428. }
  3429. // RFC 9110 11.6.1: 1*SP separates the scheme from its first auth-param.
  3430. TEST(DigestAuthTest, SeveralSpacesAfterScheme) {
  3431. auto authorization =
  3432. get_digest_retry_authorization({"Digest realm=\"r\", nonce=\"n\""});
  3433. EXPECT_NE(std::string::npos, authorization.find("nonce=\"n\""));
  3434. }
  3435. // RFC 9110 11.2: auth-param names are matched case-insensitively.
  3436. TEST(DigestAuthTest, ParamNamesAreCaseInsensitive) {
  3437. auto authorization = get_digest_retry_authorization(
  3438. {"Digest Realm=\"testrealm\", QOP=\"auth\", Nonce=\"abc123\", "
  3439. "Algorithm=SHA-256, OPAQUE=\"op\""});
  3440. EXPECT_NE(std::string::npos, authorization.find("realm=\"testrealm\""));
  3441. EXPECT_NE(std::string::npos, authorization.find("nonce=\"abc123\""));
  3442. EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
  3443. EXPECT_NE(std::string::npos, authorization.find("qop=auth"));
  3444. EXPECT_NE(std::string::npos, authorization.find("opaque=\"op\""));
  3445. }
  3446. // The algorithm is matched case-insensitively and sent back as the server
  3447. // wrote it (RFC 7616 3.4).
  3448. TEST(DigestAuthTest, AlgorithmValueIsCaseInsensitive) {
  3449. auto authorization = get_digest_retry_authorization(
  3450. {"Digest realm=\"r\", nonce=\"n\", qop=\"auth\", algorithm=sha-256"});
  3451. EXPECT_NE(std::string::npos, authorization.find("algorithm=sha-256"));
  3452. const std::string prefix = "response=\"";
  3453. auto b = authorization.find(prefix);
  3454. ASSERT_NE(std::string::npos, b);
  3455. b += prefix.size();
  3456. EXPECT_EQ(64u, authorization.find('"', b) - b); // SHA-256, not MD5
  3457. }
  3458. // qop options are matched case-insensitively.
  3459. TEST(DigestAuthTest, QopValueIsCaseInsensitive) {
  3460. auto authorization = get_digest_retry_authorization(
  3461. {"Digest realm=\"r\", nonce=\"n\", qop=\"AUTH\""});
  3462. EXPECT_NE(std::string::npos, authorization.find("qop=auth,"));
  3463. }
  3464. // auth-int hashes req.body, which is empty when a content provider streams the
  3465. // body, so it is chosen only when the server offers no auth.
  3466. TEST(DigestAuthTest, PrefersQopAuthOverAuthInt) {
  3467. auto authorization = get_digest_retry_authorization(
  3468. {"Digest realm=\"r\", nonce=\"n\", qop=\"auth-int, auth\""});
  3469. EXPECT_NE(std::string::npos, authorization.find("qop=auth,"));
  3470. authorization = get_digest_retry_authorization(
  3471. {"Digest realm=\"r\", nonce=\"n\", qop=\"Auth-Int\""});
  3472. EXPECT_NE(std::string::npos, authorization.find("qop=auth-int,"));
  3473. }
  3474. // RFC 7616 3.7: the client uses the first Digest challenge it can answer.
  3475. TEST(DigestAuthTest, SkipsUnanswerableDigestChallenges) {
  3476. auto authorization = get_digest_retry_authorization(
  3477. {"Digest realm=\"r\", nonce=\"n1\", algorithm=SHA-512-256, "
  3478. "Digest realm=\"r\", nonce=\"n2\", algorithm=SHA-256"});
  3479. EXPECT_NE(std::string::npos, authorization.find("nonce=\"n2\""));
  3480. EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
  3481. authorization = get_digest_retry_authorization(
  3482. {"Digest realm=\"r\", qop=\"auth\", Digest realm=\"r\", nonce=\"n2\""});
  3483. EXPECT_NE(std::string::npos, authorization.find("nonce=\"n2\""));
  3484. }
  3485. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3486. // the params and leaves out the fragment.
  3487. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3488. Server svr;
  3489. std::string uri, target;
  3490. svr.Get("/a b", [&](const Request &req, Response &res) {
  3491. auto auth = req.get_header_value("Authorization");
  3492. if (auth.empty()) {
  3493. res.status = StatusCode::Unauthorized_401;
  3494. res.set_header("WWW-Authenticate",
  3495. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3496. return;
  3497. }
  3498. auto b = auth.find("uri=\"") + 5;
  3499. uri = auth.substr(b, auth.find('"', b) - b);
  3500. target = req.target;
  3501. });
  3502. auto port = svr.bind_to_any_port(HOST);
  3503. std::thread t([&]() { svr.listen_after_bind(); });
  3504. auto se = detail::scope_exit([&] {
  3505. svr.stop();
  3506. t.join();
  3507. });
  3508. svr.wait_until_ready();
  3509. Client cli(HOST, port);
  3510. cli.set_digest_auth("hello", "world");
  3511. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3513. EXPECT_EQ("/a%20b?x=1", target);
  3514. EXPECT_EQ(target, uri);
  3515. }
  3516. // A Digest challenge the client can't answer (realm or nonce missing, or no
  3517. // algorithm or qop option it implements) must leave the 401 as it is, without
  3518. // a retry.
  3519. static void
  3520. run_unanswerable_digest_challenge_test(const std::string &challenge) {
  3521. std::atomic<int> hits{0};
  3522. Server svr;
  3523. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3524. ++hits;
  3525. res.status = StatusCode::Unauthorized_401;
  3526. res.set_header("WWW-Authenticate", challenge);
  3527. });
  3528. auto port = svr.bind_to_any_port(HOST);
  3529. std::thread t([&]() { svr.listen_after_bind(); });
  3530. auto se = detail::scope_exit([&] {
  3531. svr.stop();
  3532. t.join();
  3533. });
  3534. svr.wait_until_ready();
  3535. Client cli(HOST, port);
  3536. cli.set_digest_auth("hello", "world");
  3537. auto res = cli.Get("/x");
  3538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3539. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3540. EXPECT_EQ(1, hits.load());
  3541. }
  3542. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3543. run_unanswerable_digest_challenge_test("Digest qop=\"auth\"");
  3544. }
  3545. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3546. run_unanswerable_digest_challenge_test("Digest realm=\"r\", qop=\"auth\"");
  3547. }
  3548. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3549. run_unanswerable_digest_challenge_test("Digest nonce=\"n\", qop=\"auth\"");
  3550. }
  3551. // RFC 7616 3.3: a challenge with an algorithm the client doesn't implement is
  3552. // ignored. The last value isn't a token and would otherwise inject auth-params
  3553. // into the Authorization header.
  3554. TEST(DigestAuthTest, UnsupportedAlgorithmIsIgnored) {
  3555. for (auto algorithm :
  3556. {"SHA-512-256", "MD5-sess", "\"MD5, injected=\\\"y\\\"\""}) {
  3557. SCOPED_TRACE(algorithm);
  3558. run_unanswerable_digest_challenge_test(
  3559. std::string("Digest realm=\"r\", nonce=\"n\", qop=\"auth\", "
  3560. "algorithm=") +
  3561. algorithm);
  3562. }
  3563. }
  3564. // RFC 7616 3.3: qop options the client doesn't implement are ignored, and a
  3565. // challenge that offers no other can't be answered.
  3566. TEST(DigestAuthTest, UnsupportedQopIsIgnored) {
  3567. run_unanswerable_digest_challenge_test(
  3568. "Digest realm=\"r\", nonce=\"n\", qop=\"auth-conf\"");
  3569. }
  3570. // A hostile server can put a '"' in realm/nonce/opaque in its challenge.
  3571. // parse_www_authenticate() de-escapes quoted-pairs when storing the values, so
  3572. // the header builder has to re-escape them; otherwise the value breaks out of
  3573. // its quoted-string and injects extra auth-params into the Authorization.
  3574. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3575. // On the wire the quotes embedded in the value are backslash-escaped.
  3576. auto authorization = get_digest_retry_authorization(
  3577. {"Digest realm=\"testrealm\", nonce=\"n\\\"; injected=\\\"x\", "
  3578. "qop=\"auth\""});
  3579. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3580. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3581. // inside its quoted-string rather than starting an "injected" auth-param.
  3582. EXPECT_NE(std::string::npos,
  3583. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3584. }
  3585. #endif
  3586. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3587. auto host = "google.com";
  3588. auto another_host = "example.com";
  3589. auto wrong_ip = "0.0.0.0";
  3590. #ifdef CPPHTTPLIB_SSL_ENABLED
  3591. SSLClient cli(host);
  3592. #else
  3593. Client cli(host);
  3594. #endif
  3595. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3596. auto res = cli.Get("/");
  3597. // Any status: Google may redirect or rate-limit CI runners.
  3598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3599. }
  3600. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3601. auto host = "google.com";
  3602. auto wrong_ip = "0.0.0.0";
  3603. #ifdef CPPHTTPLIB_SSL_ENABLED
  3604. SSLClient cli(host);
  3605. #else
  3606. Client cli(host);
  3607. #endif
  3608. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3609. auto res = cli.Get("/");
  3610. ASSERT_TRUE(!res);
  3611. EXPECT_EQ(Error::Connection, res.error());
  3612. }
  3613. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3614. // A mapped value that is not an IP literal must be resolved. "localhost"
  3615. // resolves from the hosts file, so this test needs no external DNS.
  3616. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3617. auto host = "target.invalid";
  3618. Server svr;
  3619. std::string received_host;
  3620. svr.Get("/hi", [&](const Request &req, Response &res) {
  3621. received_host = req.get_header_value("Host");
  3622. res.set_content("Hello World!", "text/plain");
  3623. });
  3624. auto port = svr.bind_to_any_port(HOST);
  3625. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3626. auto se = detail::scope_exit([&] {
  3627. svr.stop();
  3628. thread.join();
  3629. ASSERT_FALSE(svr.is_running());
  3630. });
  3631. svr.wait_until_ready();
  3632. Client cli(host, port);
  3633. cli.set_direct_hostname_addr_map({{host, HOST}});
  3634. auto res = cli.Get("/hi");
  3635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3636. EXPECT_EQ(StatusCode::OK_200, res->status);
  3637. // The mapping only redirects the connection; the identity stays host_.
  3638. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3639. }
  3640. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3641. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3642. auto host = "target.invalid";
  3643. Server svr;
  3644. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3645. res.set_content("Hello World!", "text/plain");
  3646. });
  3647. auto port = svr.bind_to_any_port("127.0.0.1");
  3648. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3649. auto se = detail::scope_exit([&] {
  3650. svr.stop();
  3651. thread.join();
  3652. ASSERT_FALSE(svr.is_running());
  3653. });
  3654. svr.wait_until_ready();
  3655. Client cli(host, port);
  3656. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3657. auto res = cli.Get("/hi");
  3658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3659. EXPECT_EQ(StatusCode::OK_200, res->status);
  3660. }
  3661. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3662. // An empty mapped value must leave host_ as the connection target. Without
  3663. // that guard the empty value would become the host argument, getaddrinfo
  3664. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3665. // loopback - silently connecting somewhere the caller never asked for.
  3666. // The server listens on loopback, so such a fallback would succeed and is
  3667. // therefore observable as a failure of this test.
  3668. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3669. Server svr;
  3670. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3671. res.set_content("Hello World!", "text/plain");
  3672. });
  3673. auto port = svr.bind_to_any_port(HOST);
  3674. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3675. auto se = detail::scope_exit([&] {
  3676. svr.stop();
  3677. thread.join();
  3678. ASSERT_FALSE(svr.is_running());
  3679. });
  3680. svr.wait_until_ready();
  3681. Client cli(blackhole, port);
  3682. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3683. cli.set_connection_timeout(1);
  3684. auto res = cli.Get("/hi");
  3685. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3686. }
  3687. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3688. auto host = "target.invalid";
  3689. Server svr;
  3690. std::string received_host;
  3691. svr.Get("/hi", [&](const Request &req, Response &res) {
  3692. received_host = req.get_header_value("Host");
  3693. res.set_content("Hello World!", "text/plain");
  3694. });
  3695. auto port = svr.bind_to_any_port("127.0.0.1");
  3696. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3697. auto se = detail::scope_exit([&] {
  3698. svr.stop();
  3699. thread.join();
  3700. ASSERT_FALSE(svr.is_running());
  3701. });
  3702. svr.wait_until_ready();
  3703. Client cli(host, port);
  3704. #pragma GCC diagnostic push
  3705. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3706. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3707. #pragma GCC diagnostic pop
  3708. auto res = cli.Get("/hi");
  3709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3710. EXPECT_EQ(StatusCode::OK_200, res->status);
  3711. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3712. }
  3713. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3714. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3715. Server svr;
  3716. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3717. res.set_content("Hello World!", "text/plain");
  3718. });
  3719. auto port = svr.bind_to_any_port("127.0.0.1");
  3720. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3721. auto se = detail::scope_exit([&] {
  3722. svr.stop();
  3723. thread.join();
  3724. ASSERT_FALSE(svr.is_running());
  3725. });
  3726. svr.wait_until_ready();
  3727. Client cli("127.0.0.1", port);
  3728. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3729. cli.set_connection_timeout(1);
  3730. auto res = cli.Get("/hi");
  3731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3732. EXPECT_EQ(StatusCode::OK_200, res->status);
  3733. }
  3734. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3735. auto host = "httpbingo.org";
  3736. auto path = std::string{"/absolute-redirect/3"};
  3737. #ifdef CPPHTTPLIB_SSL_ENABLED
  3738. SSLClient cli(host);
  3739. #else
  3740. Client cli(host);
  3741. #endif
  3742. cli.set_follow_location(true);
  3743. auto res = retry_service_failures([&] { return cli.Get(path); });
  3744. SKIP_ON_SERVICE_FAILURE(res);
  3745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3746. EXPECT_EQ(StatusCode::OK_200, res->status);
  3747. }
  3748. TEST(RedirectTest, Redirect_Online) {
  3749. auto host = "httpbingo.org";
  3750. auto path = std::string{"/redirect/3"};
  3751. #ifdef CPPHTTPLIB_SSL_ENABLED
  3752. SSLClient cli(host);
  3753. #else
  3754. Client cli(host);
  3755. #endif
  3756. cli.set_follow_location(true);
  3757. auto res = retry_service_failures([&] { return cli.Get(path); });
  3758. SKIP_ON_SERVICE_FAILURE(res);
  3759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3760. EXPECT_EQ(StatusCode::OK_200, res->status);
  3761. }
  3762. TEST(RelativeRedirectTest, Redirect_Online) {
  3763. auto host = "httpbingo.org";
  3764. auto path = std::string{"/relative-redirect/3"};
  3765. #ifdef CPPHTTPLIB_SSL_ENABLED
  3766. SSLClient cli(host);
  3767. #else
  3768. Client cli(host);
  3769. #endif
  3770. cli.set_follow_location(true);
  3771. auto res = retry_service_failures([&] { return cli.Get(path); });
  3772. SKIP_ON_SERVICE_FAILURE(res);
  3773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3774. EXPECT_EQ(StatusCode::OK_200, res->status);
  3775. }
  3776. TEST(TooManyRedirectTest, Redirect_Online) {
  3777. auto host = "httpbingo.org";
  3778. auto path = std::string{"/redirect/21"};
  3779. #ifdef CPPHTTPLIB_SSL_ENABLED
  3780. SSLClient cli(host);
  3781. #else
  3782. Client cli(host);
  3783. #endif
  3784. cli.set_follow_location(true);
  3785. auto res = retry_service_failures([&] { return cli.Get(path); });
  3786. SKIP_ON_SERVICE_FAILURE(res);
  3787. ASSERT_TRUE(!res);
  3788. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3789. }
  3790. #ifdef CPPHTTPLIB_SSL_ENABLED
  3791. TEST(YahooRedirectTest, Redirect_Online) {
  3792. Client cli("yahoo.com");
  3793. auto res = cli.Get("/");
  3794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3795. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3796. cli.set_follow_location(true);
  3797. res = cli.Get("/");
  3798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3799. EXPECT_EQ(StatusCode::OK_200, res->status);
  3800. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3801. }
  3802. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3803. #define REDIR_HOST "httpbingo.org"
  3804. #define REDIR_PATH "/redirect-to"
  3805. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3806. SSLClient cli(REDIR_HOST);
  3807. cli.set_follow_location(true);
  3808. auto res = retry_service_failures([&] {
  3809. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3810. });
  3811. SKIP_ON_SERVICE_FAILURE(res);
  3812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3813. EXPECT_EQ(StatusCode::OK_200, res->status);
  3814. }
  3815. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3816. SSLClient cli(REDIR_HOST);
  3817. cli.set_follow_location(true);
  3818. Params params;
  3819. params.emplace("url", "http://example.com");
  3820. params.emplace("status_code", "302");
  3821. auto res = retry_service_failures(
  3822. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  3823. SKIP_ON_SERVICE_FAILURE(res);
  3824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3825. EXPECT_EQ(StatusCode::OK_200, res->status);
  3826. }
  3827. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3828. SSLClient cli(REDIR_HOST);
  3829. cli.set_follow_location(true);
  3830. Params params;
  3831. params.emplace("url", "http://example.com");
  3832. auto res = retry_service_failures([&] {
  3833. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3834. });
  3835. SKIP_ON_SERVICE_FAILURE(res);
  3836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3837. EXPECT_EQ(StatusCode::OK_200, res->status);
  3838. }
  3839. TEST(UrlWithSpace, Redirect_Online) {
  3840. SSLClient cli("edge.forgecdn.net");
  3841. cli.set_follow_location(true);
  3842. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3844. EXPECT_EQ(StatusCode::OK_200, res->status);
  3845. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3846. }
  3847. #endif
  3848. #if !defined(_WIN32) && !defined(_WIN64)
  3849. TEST(ReceiveSignals, Signal) {
  3850. auto setupSignalHandlers = []() {
  3851. struct sigaction act;
  3852. sigemptyset(&act.sa_mask);
  3853. act.sa_flags = SA_SIGINFO;
  3854. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3855. switch (sig) {
  3856. case SIGINT:
  3857. default: break;
  3858. }
  3859. };
  3860. ::sigaction(SIGINT, &act, nullptr);
  3861. };
  3862. Server svr;
  3863. int port = 0;
  3864. auto thread = std::thread([&]() {
  3865. setupSignalHandlers();
  3866. port = svr.bind_to_any_port(HOST);
  3867. svr.listen_after_bind();
  3868. });
  3869. auto se = detail::scope_exit([&] {
  3870. svr.stop();
  3871. thread.join();
  3872. ASSERT_FALSE(svr.is_running());
  3873. });
  3874. svr.wait_until_ready();
  3875. ASSERT_TRUE(svr.is_running());
  3876. pthread_kill(thread.native_handle(), SIGINT);
  3877. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3878. ASSERT_TRUE(svr.is_running());
  3879. }
  3880. #endif
  3881. TEST(RedirectToDifferentPort, Redirect) {
  3882. Server svr1;
  3883. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3884. res.set_content("Hello World!", "text/plain");
  3885. });
  3886. int svr1_port = 0;
  3887. auto thread1 = std::thread([&]() {
  3888. svr1_port = svr1.bind_to_any_port(HOST);
  3889. svr1.listen_after_bind();
  3890. });
  3891. Server svr2;
  3892. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3893. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3894. });
  3895. int svr2_port = 0;
  3896. auto thread2 = std::thread([&]() {
  3897. svr2_port = svr2.bind_to_any_port(HOST);
  3898. svr2.listen_after_bind();
  3899. });
  3900. auto se = detail::scope_exit([&] {
  3901. svr2.stop();
  3902. thread2.join();
  3903. svr1.stop();
  3904. thread1.join();
  3905. ASSERT_FALSE(svr2.is_running());
  3906. ASSERT_FALSE(svr1.is_running());
  3907. });
  3908. svr1.wait_until_ready();
  3909. svr2.wait_until_ready();
  3910. Client cli("localhost", svr2_port);
  3911. cli.set_follow_location(true);
  3912. auto res = cli.Get("/2");
  3913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3914. EXPECT_EQ(StatusCode::OK_200, res->status);
  3915. EXPECT_EQ("Hello World!", res->body);
  3916. }
  3917. // GET /redir on one server redirects to /target on another port, so the
  3918. // client follows it with a new client.
  3919. static Result
  3920. GetThroughRedirectToDifferentPort(Server::Handler target,
  3921. const std::function<void(Client &)> &setup,
  3922. const Headers &headers = Headers()) {
  3923. Server target_svr;
  3924. target_svr.Get("/target", target);
  3925. int target_port = 0;
  3926. auto target_thread = std::thread([&]() {
  3927. target_port = target_svr.bind_to_any_port(HOST);
  3928. target_svr.listen_after_bind();
  3929. });
  3930. Server origin_svr;
  3931. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3932. res.set_redirect(
  3933. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3934. });
  3935. int origin_port = 0;
  3936. auto origin_thread = std::thread([&]() {
  3937. origin_port = origin_svr.bind_to_any_port(HOST);
  3938. origin_svr.listen_after_bind();
  3939. });
  3940. auto se = detail::scope_exit([&] {
  3941. origin_svr.stop();
  3942. origin_thread.join();
  3943. target_svr.stop();
  3944. target_thread.join();
  3945. });
  3946. target_svr.wait_until_ready();
  3947. origin_svr.wait_until_ready();
  3948. Client cli("localhost", origin_port);
  3949. cli.set_follow_location(true);
  3950. setup(cli);
  3951. return cli.Get("/redir", headers);
  3952. }
  3953. static void
  3954. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3955. std::string captured_authorization;
  3956. auto result = GetThroughRedirectToDifferentPort(
  3957. [&](const Request &req, Response &res) {
  3958. captured_authorization = req.get_header_value("Authorization");
  3959. res.set_content("OK", "text/plain");
  3960. },
  3961. set_auth);
  3962. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3963. EXPECT_EQ(StatusCode::OK_200, result->status);
  3964. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3965. EXPECT_TRUE(captured_authorization.empty());
  3966. }
  3967. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3968. TestDoNotForwardCredentialsOnRedirect(
  3969. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3970. }
  3971. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3972. TestDoNotForwardCredentialsOnRedirect(
  3973. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3974. }
  3975. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3976. std::string captured_cookie;
  3977. auto result = GetThroughRedirectToDifferentPort(
  3978. [&](const Request &req, Response &res) {
  3979. captured_cookie = req.get_header_value("Cookie");
  3980. res.set_content("OK", "text/plain");
  3981. },
  3982. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3983. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3984. EXPECT_EQ(StatusCode::OK_200, result->status);
  3985. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3986. EXPECT_TRUE(captured_cookie.empty());
  3987. }
  3988. TEST(RedirectToSamePort, ForwardCookie) {
  3989. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3990. // header so that ordinary session flows keep working.
  3991. Server svr;
  3992. std::string captured_cookie;
  3993. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3994. res.set_redirect("/target", 302);
  3995. });
  3996. svr.Get("/target", [&](const Request &req, Response &res) {
  3997. captured_cookie = req.get_header_value("Cookie");
  3998. res.set_content("OK", "text/plain");
  3999. });
  4000. auto port = svr.bind_to_any_port(HOST);
  4001. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4002. auto se = detail::scope_exit([&] {
  4003. svr.stop();
  4004. thread.join();
  4005. ASSERT_FALSE(svr.is_running());
  4006. });
  4007. svr.wait_until_ready();
  4008. Client cli(HOST, port);
  4009. cli.set_follow_location(true);
  4010. Headers headers = {{"Cookie", "session_id=SECRET"}};
  4011. auto res = cli.Get("/redir", headers);
  4012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4013. EXPECT_EQ(StatusCode::OK_200, res->status);
  4014. EXPECT_EQ("session_id=SECRET", captured_cookie);
  4015. }
  4016. TEST(RedirectToSamePort, HostNameIsCaseInsensitive) {
  4017. // "LOCALHOST" names the same host as "localhost" (RFC 3986 3.2.2), so the
  4018. // redirect stays on this origin and keeps its credentials and cookies.
  4019. Server svr;
  4020. std::string captured_authorization;
  4021. std::string captured_cookie;
  4022. int port = 0;
  4023. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4024. res.set_redirect("http://LOCALHOST:" + std::to_string(port) + "/target",
  4025. 302);
  4026. });
  4027. svr.Get("/target", [&](const Request &req, Response &res) {
  4028. captured_authorization = req.get_header_value("Authorization");
  4029. captured_cookie = req.get_header_value("Cookie");
  4030. res.set_content("OK", "text/plain");
  4031. });
  4032. port = svr.bind_to_any_port(HOST);
  4033. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4034. auto se = detail::scope_exit([&] {
  4035. svr.stop();
  4036. thread.join();
  4037. ASSERT_FALSE(svr.is_running());
  4038. });
  4039. svr.wait_until_ready();
  4040. Client cli(HOST, port);
  4041. cli.set_follow_location(true);
  4042. cli.set_basic_auth("admin", "secret");
  4043. Headers headers = {{"Cookie", "session_id=SECRET"}};
  4044. auto res = cli.Get("/redir", headers);
  4045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4046. EXPECT_EQ(StatusCode::OK_200, res->status);
  4047. EXPECT_EQ("Basic YWRtaW46c2VjcmV0", captured_authorization);
  4048. EXPECT_EQ("session_id=SECRET", captured_cookie);
  4049. }
  4050. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  4051. // The Location alone names the next target, on any origin.
  4052. Server target_svr;
  4053. std::string cross_target;
  4054. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  4055. cross_target = req.target;
  4056. res.set_content("OK", "text/plain");
  4057. });
  4058. auto target_port = target_svr.bind_to_any_port(HOST);
  4059. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  4060. Server origin_svr;
  4061. std::string same_target;
  4062. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  4063. res.set_redirect(
  4064. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  4065. });
  4066. origin_svr.Get("/same", [&](const Request &, Response &res) {
  4067. res.set_redirect("/landing", 302);
  4068. });
  4069. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  4070. same_target = req.target;
  4071. res.set_content("OK", "text/plain");
  4072. });
  4073. auto origin_port = origin_svr.bind_to_any_port(HOST);
  4074. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  4075. auto se = detail::scope_exit([&] {
  4076. origin_svr.stop();
  4077. origin_thread.join();
  4078. target_svr.stop();
  4079. target_thread.join();
  4080. });
  4081. target_svr.wait_until_ready();
  4082. origin_svr.wait_until_ready();
  4083. Client cli("localhost", origin_port);
  4084. cli.set_follow_location(true);
  4085. Request req;
  4086. req.method = "GET";
  4087. req.params = {{"api_key", "SECRET"}};
  4088. req.path = "/cross";
  4089. auto res = cli.send(req);
  4090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4091. EXPECT_EQ("/landing", cross_target);
  4092. req.path = "/same";
  4093. res = cli.send(req);
  4094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4095. EXPECT_EQ("/landing", same_target);
  4096. }
  4097. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  4098. std::string authorization;
  4099. std::string trace_id;
  4100. auto result = GetThroughRedirectToDifferentPort(
  4101. [&](const Request &req, Response &res) {
  4102. authorization = req.get_header_value("Authorization");
  4103. trace_id = req.get_header_value("X-Trace-Id");
  4104. res.set_content("OK", "text/plain");
  4105. },
  4106. [](Client &cli) {
  4107. cli.set_default_headers(
  4108. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  4109. });
  4110. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4111. EXPECT_EQ(StatusCode::OK_200, result->status);
  4112. // Like a header given with the request, a default one goes along unless it
  4113. // carries credentials (RFC 9110 15.4).
  4114. EXPECT_TRUE(authorization.empty());
  4115. EXPECT_EQ("42", trace_id);
  4116. }
  4117. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  4118. auto result = GetThroughRedirectToDifferentPort(
  4119. [](const Request &, Response &res) {
  4120. res.set_content(std::string(2048, 'x'), "text/plain");
  4121. },
  4122. [](Client &cli) { cli.set_payload_max_length(1024); });
  4123. EXPECT_FALSE(result);
  4124. }
  4125. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  4126. auto result = GetThroughRedirectToDifferentPort(
  4127. [](const Request &req, Response &res) {
  4128. // Answer after a second, or once the client gives up.
  4129. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  4130. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4131. }
  4132. res.set_content("late", "text/plain");
  4133. },
  4134. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  4135. ASSERT_FALSE(result);
  4136. EXPECT_EQ(Error::Read, result.error());
  4137. }
  4138. #ifdef CPPHTTPLIB_SSL_ENABLED
  4139. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  4140. auto result = GetThroughRedirectToDifferentPort(
  4141. [](const Request &, Response &res) {
  4142. res.status = StatusCode::Unauthorized_401;
  4143. res.set_header("WWW-Authenticate",
  4144. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  4145. },
  4146. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  4147. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4148. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  4149. }
  4150. #endif
  4151. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  4152. Server svr;
  4153. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4154. // Port number that overflows int — should not crash
  4155. res.set_redirect("http://localhost:99999999999999999999/target");
  4156. });
  4157. auto port = svr.bind_to_any_port(HOST);
  4158. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4159. auto se = detail::scope_exit([&] {
  4160. svr.stop();
  4161. thread.join();
  4162. ASSERT_FALSE(svr.is_running());
  4163. });
  4164. svr.wait_until_ready();
  4165. Client cli(HOST, port);
  4166. cli.set_follow_location(true);
  4167. auto res = cli.Get("/redir");
  4168. // Should fail gracefully, not crash (no valid response due to bad port)
  4169. EXPECT_FALSE(res);
  4170. }
  4171. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  4172. Server svr;
  4173. auto port = svr.bind_to_any_port(HOST);
  4174. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4175. // The server's own port followed by junk must not be followed
  4176. res.set_redirect("http://" + std::string(HOST) + ":" +
  4177. std::to_string(port) + "junk/target");
  4178. });
  4179. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4180. res.set_content("target", "text/plain");
  4181. });
  4182. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4183. auto se = detail::scope_exit([&] {
  4184. svr.stop();
  4185. thread.join();
  4186. ASSERT_FALSE(svr.is_running());
  4187. });
  4188. svr.wait_until_ready();
  4189. Client cli(HOST, port);
  4190. cli.set_follow_location(true);
  4191. auto res = cli.Get("/redir");
  4192. EXPECT_FALSE(res);
  4193. }
  4194. TEST(RedirectToDifferentPort, BareHostAndPortIsNotFollowed) {
  4195. Server target_svr;
  4196. std::atomic<int> target_hits{0};
  4197. target_svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4198. target_hits++;
  4199. res.set_content("target", "text/plain");
  4200. });
  4201. target_svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4202. res.set_content("target", "text/plain");
  4203. });
  4204. int target_port = 0;
  4205. auto target_thread = std::thread([&]() {
  4206. target_port = target_svr.bind_to_any_port("127.0.0.1");
  4207. target_svr.listen_after_bind();
  4208. });
  4209. Server origin_svr;
  4210. origin_svr.Get("/redir", [&](const Request &req, Response &res) {
  4211. res.set_redirect(req.get_param_value("to"));
  4212. });
  4213. int origin_port = 0;
  4214. auto origin_thread = std::thread([&]() {
  4215. origin_port = origin_svr.bind_to_any_port(HOST);
  4216. origin_svr.listen_after_bind();
  4217. });
  4218. auto se = detail::scope_exit([&] {
  4219. origin_svr.stop();
  4220. origin_thread.join();
  4221. target_svr.stop();
  4222. target_thread.join();
  4223. ASSERT_FALSE(origin_svr.is_running());
  4224. ASSERT_FALSE(target_svr.is_running());
  4225. });
  4226. target_svr.wait_until_ready();
  4227. origin_svr.wait_until_ready();
  4228. auto port = std::to_string(target_port);
  4229. for (const auto &to :
  4230. {"localhost:" + port, "127.0.0.1:" + port, "localhost:" + port + "/"}) {
  4231. Client cli(HOST, origin_port);
  4232. cli.set_follow_location(true);
  4233. auto res = cli.Get("/redir?to=" + encode_query_component(to));
  4234. EXPECT_FALSE(res) << to;
  4235. }
  4236. EXPECT_EQ(0, target_hits);
  4237. Client cli(HOST, origin_port);
  4238. cli.set_follow_location(true);
  4239. auto res = cli.Get("/redir?to=" +
  4240. encode_query_component("//127.0.0.1:" + port + "/target"));
  4241. ASSERT_TRUE(res) << to_string(res.error());
  4242. EXPECT_EQ(StatusCode::OK_200, res->status);
  4243. EXPECT_EQ("target", res->body);
  4244. }
  4245. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  4246. Server svr;
  4247. std::atomic<bool> followed{false};
  4248. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  4249. res.status = StatusCode::NotModified_304;
  4250. res.set_header("Location", "/target");
  4251. });
  4252. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  4253. res.status = StatusCode::UseProxy_305;
  4254. res.set_header("Location", "/target");
  4255. });
  4256. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4257. followed = true;
  4258. res.set_content("target", "text/plain");
  4259. });
  4260. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4261. auto se = detail::scope_exit([&] {
  4262. svr.stop();
  4263. th.join();
  4264. ASSERT_FALSE(svr.is_running());
  4265. });
  4266. svr.wait_until_ready();
  4267. Client cli("localhost", PORT);
  4268. cli.set_follow_location(true);
  4269. auto res = cli.Get("/304");
  4270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4271. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  4272. res = cli.Get("/305");
  4273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4274. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  4275. EXPECT_FALSE(followed);
  4276. }
  4277. TEST(RedirectFromPageWithContent, Redirect) {
  4278. Server svr;
  4279. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4280. res.set_content("___", "text/plain");
  4281. res.set_redirect("/2");
  4282. });
  4283. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  4284. res.set_content("Hello World!", "text/plain");
  4285. });
  4286. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4287. auto se = detail::scope_exit([&] {
  4288. svr.stop();
  4289. th.join();
  4290. ASSERT_FALSE(svr.is_running());
  4291. });
  4292. svr.wait_until_ready();
  4293. {
  4294. Client cli("localhost", PORT);
  4295. cli.set_follow_location(true);
  4296. std::string body;
  4297. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4298. body.append(data, data_length);
  4299. return true;
  4300. });
  4301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4302. EXPECT_EQ(StatusCode::OK_200, res->status);
  4303. EXPECT_EQ("Hello World!", body);
  4304. }
  4305. {
  4306. Client cli("localhost", PORT);
  4307. std::string body;
  4308. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4309. body.append(data, data_length);
  4310. return true;
  4311. });
  4312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4313. EXPECT_EQ(StatusCode::Found_302, res->status);
  4314. EXPECT_EQ("___", body);
  4315. }
  4316. }
  4317. // A server can close the connection after a request with "Connection: close"
  4318. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  4319. // redirected request must go out on a new connection.
  4320. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  4321. #ifndef _WIN32
  4322. signal(SIGPIPE, SIG_IGN);
  4323. #endif
  4324. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  4325. default_socket_options(srv);
  4326. sockaddr_in addr{};
  4327. addr.sin_family = AF_INET;
  4328. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  4329. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  4330. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4331. ASSERT_EQ(0, ::listen(srv, 2));
  4332. auto send_text = [](socket_t sock, const std::string &text) {
  4333. ::send(sock,
  4334. #ifdef _WIN32
  4335. static_cast<const char *>(text.c_str()),
  4336. static_cast<int>(text.size()),
  4337. #else
  4338. text.c_str(), text.size(),
  4339. #endif
  4340. 0);
  4341. };
  4342. auto reused = false;
  4343. auto server_thread = std::thread([&] {
  4344. char buf[4096];
  4345. auto first = ::accept(srv, nullptr, nullptr);
  4346. if (first == INVALID_SOCKET) { return; }
  4347. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4348. ::recv(first, buf, sizeof(buf), 0);
  4349. send_text(
  4350. first,
  4351. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  4352. auto next = first;
  4353. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  4354. reused = true;
  4355. } else {
  4356. detail::close_socket(first);
  4357. next = ::accept(srv, nullptr, nullptr);
  4358. if (next == INVALID_SOCKET) { return; }
  4359. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4360. ::recv(next, buf, sizeof(buf), 0);
  4361. }
  4362. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  4363. "Connection: close\r\n\r\nok");
  4364. detail::close_socket(next);
  4365. });
  4366. Client cli("127.0.0.1", PORT + 2);
  4367. cli.set_follow_location(true);
  4368. cli.set_read_timeout(5, 0);
  4369. auto res = cli.Get("/1");
  4370. server_thread.join();
  4371. detail::close_socket(srv);
  4372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4373. EXPECT_EQ(StatusCode::OK_200, res->status);
  4374. EXPECT_EQ("ok", res->body);
  4375. EXPECT_FALSE(reused);
  4376. }
  4377. TEST(RedirectFromPageWithContentIP6, Redirect) {
  4378. Server svr;
  4379. auto port_str = std::to_string(PORT);
  4380. auto redirect_url = "http://[::1]:" + port_str + "/2";
  4381. auto expected_host = "[::1]:" + port_str;
  4382. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4383. res.set_content("___", "text/plain");
  4384. // res.set_redirect("/2");
  4385. res.set_redirect(redirect_url);
  4386. });
  4387. svr.Get("/2", [&](const Request &req, Response &res) {
  4388. auto host_header = req.headers.find("Host");
  4389. ASSERT_TRUE(host_header != req.headers.end());
  4390. EXPECT_EQ(expected_host, host_header->second);
  4391. res.set_content("Hello World!", "text/plain");
  4392. });
  4393. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  4394. auto se = detail::scope_exit([&] {
  4395. svr.stop();
  4396. th.join();
  4397. ASSERT_FALSE(svr.is_running());
  4398. });
  4399. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4400. // actually starts anything, so the condition !svr.is_running() will
  4401. // always remain true, and the loop never stops.
  4402. // This basically counts how many milliseconds have passed since the
  4403. // call to svr.listen(), and if after 5 seconds nothing started yet
  4404. // aborts the test.
  4405. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4406. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4407. ASSERT_LT(milliseconds, 5000U);
  4408. }
  4409. {
  4410. Client cli("::1", PORT);
  4411. cli.set_follow_location(true);
  4412. std::string body;
  4413. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4414. body.append(data, data_length);
  4415. return true;
  4416. });
  4417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4418. EXPECT_EQ(StatusCode::OK_200, res->status);
  4419. EXPECT_EQ("Hello World!", body);
  4420. }
  4421. {
  4422. Client cli("::1", PORT);
  4423. std::string body;
  4424. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4425. body.append(data, data_length);
  4426. return true;
  4427. });
  4428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4429. EXPECT_EQ(StatusCode::Found_302, res->status);
  4430. EXPECT_EQ("___", body);
  4431. }
  4432. }
  4433. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4434. Server svr;
  4435. svr.Get("/foo", [](const Request &req, Response &res) {
  4436. auto a = req.params.find("a");
  4437. if (a != req.params.end()) {
  4438. res.set_content((*a).second, "text/plain");
  4439. res.status = StatusCode::OK_200;
  4440. } else {
  4441. res.status = StatusCode::BadRequest_400;
  4442. }
  4443. });
  4444. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4445. auto se = detail::scope_exit([&] {
  4446. svr.stop();
  4447. thread.join();
  4448. ASSERT_FALSE(svr.is_running());
  4449. });
  4450. svr.wait_until_ready();
  4451. {
  4452. Client cli(HOST, PORT);
  4453. cli.set_path_encode(false);
  4454. auto res = cli.Get("/foo?a=explicitly+encoded");
  4455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4456. EXPECT_EQ(StatusCode::OK_200, res->status);
  4457. // This expects it back with a space, as the `+` won't have been
  4458. // url-encoded, and server-side the params get decoded turning `+`
  4459. // into spaces.
  4460. EXPECT_EQ("explicitly encoded", res->body);
  4461. }
  4462. }
  4463. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4464. // When path encoding is disabled the client must transmit the supplied
  4465. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4466. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4467. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4468. // than a space (0x20). Assert on the raw wire target to catch this.
  4469. Server svr;
  4470. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4471. svr.Get("/foo", [&](const Request &req, Response &res) {
  4472. EXPECT_EQ(expected_target, req.target);
  4473. res.status = StatusCode::OK_200;
  4474. });
  4475. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4476. auto se = detail::scope_exit([&] {
  4477. svr.stop();
  4478. thread.join();
  4479. ASSERT_FALSE(svr.is_running());
  4480. });
  4481. svr.wait_until_ready();
  4482. {
  4483. Client cli(HOST, PORT);
  4484. cli.set_path_encode(false);
  4485. auto res = cli.Get(expected_target.c_str());
  4486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4487. EXPECT_EQ(StatusCode::OK_200, res->status);
  4488. }
  4489. }
  4490. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4491. // `open_stream()` used to skip the path encoding that the buffered send
  4492. // path applies, so the same `path` produced different bytes in the request
  4493. // line depending on which API was used. Assert the two agree.
  4494. Server svr;
  4495. std::string target;
  4496. svr.Get(".*", [&](const Request &req, Response &res) {
  4497. target = req.target;
  4498. res.status = StatusCode::OK_200;
  4499. });
  4500. auto port = svr.bind_to_any_port(HOST);
  4501. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4502. auto se = detail::scope_exit([&] {
  4503. svr.stop();
  4504. thread.join();
  4505. ASSERT_FALSE(svr.is_running());
  4506. });
  4507. svr.wait_until_ready();
  4508. struct {
  4509. const char *path;
  4510. const char *expected;
  4511. } cases[] = {
  4512. {"/a b?x=1", "/a%20b?x=1"},
  4513. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4514. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4515. };
  4516. for (const auto &c : cases) {
  4517. Client cli(HOST, port);
  4518. target.clear();
  4519. auto res = cli.Get(c.path);
  4520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4521. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4522. auto buffered_target = target;
  4523. target.clear();
  4524. auto handle = cli.open_stream("GET", c.path);
  4525. EXPECT_TRUE(handle.is_valid())
  4526. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4527. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4528. }
  4529. }
  4530. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4531. // The `set_path_encode(false)` contract — transmit the supplied target
  4532. // verbatim — must hold for the streaming API too.
  4533. Server svr;
  4534. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4535. std::string target;
  4536. svr.Get("/foo", [&](const Request &req, Response &res) {
  4537. target = req.target;
  4538. res.status = StatusCode::OK_200;
  4539. });
  4540. auto port = svr.bind_to_any_port(HOST);
  4541. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4542. auto se = detail::scope_exit([&] {
  4543. svr.stop();
  4544. thread.join();
  4545. ASSERT_FALSE(svr.is_running());
  4546. });
  4547. svr.wait_until_ready();
  4548. {
  4549. Client cli(HOST, port);
  4550. cli.set_path_encode(false);
  4551. auto handle = cli.open_stream("GET", expected_target);
  4552. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4553. EXPECT_EQ(expected_target, target);
  4554. }
  4555. }
  4556. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4557. // With path encoding enabled a CR/LF in the target is percent-encoded
  4558. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4559. // write_request_line still backstops `set_path_encode(false)`, which is
  4560. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4561. Server svr;
  4562. // Captured before routing: the decoded path contains a newline, which a
  4563. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4564. std::string target;
  4565. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4566. target = req.target;
  4567. res.status = StatusCode::OK_200;
  4568. return Server::HandlerResponse::Handled;
  4569. });
  4570. auto port = svr.bind_to_any_port(HOST);
  4571. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4572. auto se = detail::scope_exit([&] {
  4573. svr.stop();
  4574. thread.join();
  4575. ASSERT_FALSE(svr.is_running());
  4576. });
  4577. svr.wait_until_ready();
  4578. {
  4579. Client cli(HOST, port);
  4580. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4581. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4582. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4583. }
  4584. }
  4585. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4586. // Every control character is percent-encoded, not just CR/LF, so the target
  4587. // passes the request-target check in write_request_line.
  4588. Server svr;
  4589. std::string target;
  4590. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4591. target = req.target;
  4592. res.status = StatusCode::OK_200;
  4593. return Server::HandlerResponse::Handled;
  4594. });
  4595. auto port = svr.bind_to_any_port(HOST);
  4596. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4597. auto se = detail::scope_exit([&] {
  4598. svr.stop();
  4599. thread.join();
  4600. ASSERT_FALSE(svr.is_running());
  4601. });
  4602. svr.wait_until_ready();
  4603. {
  4604. Client cli(HOST, port);
  4605. auto res = cli.Get("/a\tb\x1b\x7f");
  4606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4607. EXPECT_EQ("/a%09b%1B%7F", target);
  4608. }
  4609. }
  4610. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4611. // Nothing may reach the wire: a raw CR/LF target would split the request
  4612. // line and inject headers.
  4613. Server svr;
  4614. // Pre-routing so that "not called" means nothing reached the server at all,
  4615. // rather than merely failing to match a handler pattern.
  4616. auto handler_called = false;
  4617. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4618. handler_called = true;
  4619. res.status = StatusCode::OK_200;
  4620. return Server::HandlerResponse::Handled;
  4621. });
  4622. auto port = svr.bind_to_any_port(HOST);
  4623. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4624. auto se = detail::scope_exit([&] {
  4625. svr.stop();
  4626. thread.join();
  4627. ASSERT_FALSE(svr.is_running());
  4628. });
  4629. svr.wait_until_ready();
  4630. {
  4631. Client cli(HOST, port);
  4632. cli.set_path_encode(false);
  4633. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4634. EXPECT_FALSE(handle.is_valid());
  4635. EXPECT_EQ(Error::Write, handle.error);
  4636. EXPECT_FALSE(handler_called);
  4637. }
  4638. }
  4639. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4640. // Which of the two branches runs is decided by whether the query component
  4641. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4642. // an empty query and must still fall back to building one from
  4643. // `req.params`, while a non-empty query must win over `req.params`.
  4644. Server svr;
  4645. std::string target;
  4646. svr.Get("/foo", [&](const Request &req, Response &res) {
  4647. target = req.target;
  4648. res.status = StatusCode::OK_200;
  4649. });
  4650. auto port = svr.bind_to_any_port(HOST);
  4651. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4652. auto se = detail::scope_exit([&] {
  4653. svr.stop();
  4654. thread.join();
  4655. ASSERT_FALSE(svr.is_running());
  4656. });
  4657. svr.wait_until_ready();
  4658. {
  4659. // Trailing `?` -> empty query component -> `req.params` is used.
  4660. Client cli(HOST, port);
  4661. Request req;
  4662. req.method = "GET";
  4663. req.path = "/foo?";
  4664. req.params.emplace("a", "1");
  4665. target.clear();
  4666. auto res = cli.send(req);
  4667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4668. EXPECT_EQ("/foo?a=1", target);
  4669. }
  4670. {
  4671. // Non-empty query in `req.path` -> `req.params` is not appended.
  4672. Client cli(HOST, port);
  4673. Request req;
  4674. req.method = "GET";
  4675. req.path = "/foo?b=2";
  4676. req.params.emplace("a", "1");
  4677. target.clear();
  4678. auto res = cli.send(req);
  4679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4680. EXPECT_EQ("/foo?b=2", target);
  4681. }
  4682. }
  4683. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4684. Server svr;
  4685. svr.Get("/", [](const Request &req, Response &) {
  4686. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4687. });
  4688. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4689. auto se = detail::scope_exit([&] {
  4690. svr.stop();
  4691. thread.join();
  4692. ASSERT_FALSE(svr.is_running());
  4693. });
  4694. svr.wait_until_ready();
  4695. {
  4696. Client cli(HOST, PORT);
  4697. cli.set_path_encode(false);
  4698. auto res = cli.Get("/?something=%0A");
  4699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4700. EXPECT_EQ(StatusCode::OK_200, res->status);
  4701. }
  4702. }
  4703. TEST(BindServerTest, BindDualStack) {
  4704. Server svr;
  4705. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4706. res.set_content("Hello World!", "text/plain");
  4707. });
  4708. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4709. auto se = detail::scope_exit([&] {
  4710. svr.stop();
  4711. thread.join();
  4712. ASSERT_FALSE(svr.is_running());
  4713. });
  4714. svr.wait_until_ready();
  4715. {
  4716. Client cli("127.0.0.1", PORT);
  4717. auto res = cli.Get("/1");
  4718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4719. EXPECT_EQ(StatusCode::OK_200, res->status);
  4720. EXPECT_EQ("Hello World!", res->body);
  4721. }
  4722. {
  4723. Client cli("::1", PORT);
  4724. auto res = cli.Get("/1");
  4725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4726. EXPECT_EQ(StatusCode::OK_200, res->status);
  4727. EXPECT_EQ("Hello World!", res->body);
  4728. }
  4729. }
  4730. TEST(BindServerTest, BindAndListenSeparately) {
  4731. Server svr;
  4732. int port = svr.bind_to_any_port("0.0.0.0");
  4733. ASSERT_TRUE(svr.is_valid());
  4734. ASSERT_TRUE(port > 0);
  4735. svr.stop();
  4736. }
  4737. // Reports whether anything is still listening on a loopback port. A plain
  4738. // connect() is used instead of a Client request because a socket left bound by
  4739. // mistake accepts the connection into its backlog and never answers, which
  4740. // would hang the test instead of failing it.
  4741. static bool is_loopback_port_accepting(int port) {
  4742. sockaddr_in addr{};
  4743. addr.sin_family = AF_INET;
  4744. addr.sin_port = htons(static_cast<uint16_t>(port));
  4745. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4746. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4747. EXPECT_NE(sock, INVALID_SOCKET);
  4748. if (sock == INVALID_SOCKET) { return false; }
  4749. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4750. static_cast<socklen_t>(sizeof(addr)));
  4751. detail::close_socket(sock);
  4752. return ret == 0;
  4753. }
  4754. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4755. Server svr;
  4756. auto port = svr.bind_to_any_port("127.0.0.1");
  4757. ASSERT_TRUE(port > 0);
  4758. svr.stop();
  4759. // bind_to_any_port() already called listen(2), so until stop() closed the
  4760. // descriptor the port kept accepting connections into the backlog. ASSERT
  4761. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4762. // below blocks forever in the accept loop.
  4763. ASSERT_FALSE(is_loopback_port_accepting(port));
  4764. // Nothing is left to accept on, so listen_after_bind() must report failure
  4765. // instead of returning success without ever serving.
  4766. EXPECT_FALSE(svr.listen_after_bind());
  4767. // The failed listen marks the server decommissioned, so a waiter returns
  4768. // instead of spinning forever.
  4769. svr.wait_until_ready();
  4770. }
  4771. #ifdef CPPHTTPLIB_SSL_ENABLED
  4772. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4773. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4774. CLIENT_CA_CERT_DIR);
  4775. int port = svr.bind_to_any_port("0.0.0.0");
  4776. ASSERT_TRUE(svr.is_valid());
  4777. ASSERT_TRUE(port > 0);
  4778. svr.stop();
  4779. }
  4780. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4781. // or a rejected CustomRoute() registration would not stop the server binding.
  4782. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4783. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4784. CLIENT_CA_CERT_DIR);
  4785. ASSERT_TRUE(svr.is_valid());
  4786. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4787. EXPECT_FALSE(svr.is_valid());
  4788. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4789. }
  4790. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4791. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4792. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4793. int port = svr.bind_to_any_port("0.0.0.0");
  4794. ASSERT_TRUE(svr.is_valid());
  4795. ASSERT_TRUE(port > 0);
  4796. svr.stop();
  4797. }
  4798. TEST(BindServerTest, UpdateCertsPem) {
  4799. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4800. int port = svr.bind_to_any_port("0.0.0.0");
  4801. ASSERT_TRUE(svr.is_valid());
  4802. ASSERT_TRUE(port > 0);
  4803. // Read PEM files
  4804. std::string cert_pem, key_pem, ca_pem;
  4805. read_file(SERVER_CERT_FILE, cert_pem);
  4806. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4807. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4808. // Update server certificates using PEM API
  4809. ASSERT_TRUE(
  4810. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4811. ASSERT_TRUE(svr.is_valid());
  4812. svr.stop();
  4813. }
  4814. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4815. // Start server with client CA (enables client auth)
  4816. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4817. ASSERT_TRUE(svr.is_valid());
  4818. bool handler_called = false;
  4819. svr.Get("/test", [&](const Request &req, Response &res) {
  4820. handler_called = true;
  4821. // Verify client certificate is present
  4822. auto cert = req.peer_cert();
  4823. EXPECT_TRUE(static_cast<bool>(cert));
  4824. res.set_content("ok", "text/plain");
  4825. });
  4826. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4827. auto se = detail::scope_exit([&] {
  4828. svr.stop();
  4829. t.join();
  4830. ASSERT_FALSE(svr.is_running());
  4831. });
  4832. svr.wait_until_ready();
  4833. // Read PEM files
  4834. std::string cert_pem, key_pem, ca_pem;
  4835. read_file(SERVER_CERT_FILE, cert_pem);
  4836. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4837. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4838. // Update server certificates and client CA using PEM API while server running
  4839. ASSERT_TRUE(
  4840. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4841. // Connect with client certificate
  4842. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4843. cli.enable_server_certificate_verification(false);
  4844. cli.set_connection_timeout(30);
  4845. auto res = cli.Get("/test");
  4846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4847. ASSERT_EQ(StatusCode::OK_200, res->status);
  4848. ASSERT_TRUE(handler_called);
  4849. EXPECT_EQ("ok", res->body);
  4850. }
  4851. // Puts a CA that did not sign the client's certificate in the old one's place.
  4852. static bool replace_client_ca(SSLServer &svr) {
  4853. std::string cert_pem, key_pem, ca_pem;
  4854. read_file(SERVER_CERT_FILE, cert_pem);
  4855. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4856. read_file(SERVER_CERT2_FILE, ca_pem);
  4857. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4858. ca_pem.c_str());
  4859. }
  4860. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4861. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4862. ASSERT_TRUE(svr.is_valid());
  4863. svr.Get("/test", [](const Request &, Response &res) {
  4864. res.set_content("ok", "text/plain");
  4865. });
  4866. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4867. auto se = detail::scope_exit([&] {
  4868. svr.stop();
  4869. t.join();
  4870. ASSERT_FALSE(svr.is_running());
  4871. });
  4872. svr.wait_until_ready();
  4873. auto get = [] {
  4874. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4875. cli.enable_server_certificate_verification(false);
  4876. return cli.Get("/test");
  4877. };
  4878. ASSERT_TRUE(get());
  4879. ASSERT_TRUE(replace_client_ca(svr));
  4880. EXPECT_FALSE(get());
  4881. }
  4882. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4883. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4884. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4885. ASSERT_TRUE(svr.is_valid());
  4886. tls::set_verify_callback(svr.tls_context(),
  4887. [](const tls::VerifyContext &) -> bool {
  4888. throw std::runtime_error("verify");
  4889. });
  4890. svr.Get("/test", [](const Request &, Response &res) {
  4891. res.set_content("ok", "text/plain");
  4892. });
  4893. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4894. auto se = detail::scope_exit([&] {
  4895. svr.stop();
  4896. t.join();
  4897. ASSERT_FALSE(svr.is_running());
  4898. });
  4899. svr.wait_until_ready();
  4900. auto get = [] {
  4901. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4902. cli.enable_server_certificate_verification(false);
  4903. return cli.Get("/test");
  4904. };
  4905. EXPECT_FALSE(get());
  4906. // The handshake is over, so an update does not wait for it.
  4907. std::string cert_pem, key_pem;
  4908. read_file(SERVER_CERT_FILE, cert_pem);
  4909. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4910. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4911. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4912. return v.preverify_ok;
  4913. });
  4914. auto res = get();
  4915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4916. EXPECT_EQ("ok", res->body);
  4917. }
  4918. #endif
  4919. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4920. // Sends each request over a new connection with a client certificate,
  4921. // resuming the session of the one before when there is one.
  4922. class ResumingClient {
  4923. public:
  4924. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4925. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4926. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4927. SSL_FILETYPE_PEM);
  4928. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4929. // callback, not through SSL_get1_session().
  4930. SSL_CTX_set_app_data(ctx_, this);
  4931. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4932. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4933. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4934. auto self = static_cast<ResumingClient *>(
  4935. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4936. SSL_SESSION_free(self->session_);
  4937. self->session_ = session;
  4938. return 1; // Keeps the reference
  4939. });
  4940. }
  4941. ~ResumingClient() {
  4942. SSL_SESSION_free(session_);
  4943. SSL_CTX_free(ctx_);
  4944. }
  4945. // Tells whether the request was answered.
  4946. bool get() {
  4947. auto error = Error::Success;
  4948. auto sock = detail::create_client_socket(
  4949. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4950. /*connection_timeout_sec=*/5, 0,
  4951. /*read_timeout_sec=*/5, 0,
  4952. /*write_timeout_sec=*/5, 0, std::string(), error);
  4953. if (sock == INVALID_SOCKET) { return false; }
  4954. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4955. auto ssl = SSL_new(ctx_);
  4956. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4957. SSL_set_fd(ssl, static_cast<int>(sock));
  4958. if (session_) { SSL_set_session(ssl, session_); }
  4959. if (SSL_connect(ssl) != 1) { return false; }
  4960. reused_ = SSL_session_reused(ssl) == 1;
  4961. // Reading the response also takes in a TLS 1.3 session ticket.
  4962. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4963. "Connection: close\r\n\r\n";
  4964. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4965. std::string res;
  4966. char buf[256];
  4967. int n;
  4968. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4969. res.append(buf, static_cast<size_t>(n));
  4970. }
  4971. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4972. SSL_shutdown(ssl);
  4973. return res.find("200 OK") != std::string::npos;
  4974. }
  4975. // Whether the last connection resumed a session
  4976. bool reused() const { return reused_; }
  4977. private:
  4978. SSL_CTX *ctx_;
  4979. SSL_SESSION *session_ = nullptr;
  4980. bool reused_ = false;
  4981. };
  4982. // A client that resumes its session gets through, but not once the client CA
  4983. // has changed, as a resumed session does not show the certificate again.
  4984. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4985. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4986. ASSERT_TRUE(svr.is_valid());
  4987. svr.Get("/test", [](const Request &, Response &res) {
  4988. res.set_content("ok", "text/plain");
  4989. });
  4990. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4991. auto se = detail::scope_exit([&] {
  4992. svr.stop();
  4993. t.join();
  4994. ASSERT_FALSE(svr.is_running());
  4995. });
  4996. svr.wait_until_ready();
  4997. ResumingClient cli;
  4998. ASSERT_TRUE(cli.get());
  4999. ASSERT_TRUE(cli.get());
  5000. EXPECT_TRUE(cli.reused());
  5001. ASSERT_TRUE(replace_client_ca(svr));
  5002. EXPECT_FALSE(cli.get());
  5003. }
  5004. // A resumed session does not show the certificate again, so the server does
  5005. // not resume one with a verify callback to run on it.
  5006. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  5007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  5008. ASSERT_TRUE(svr.is_valid());
  5009. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  5010. return v.preverify_ok;
  5011. });
  5012. svr.Get("/test", [](const Request &, Response &res) {
  5013. res.set_content("ok", "text/plain");
  5014. });
  5015. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5016. auto se = detail::scope_exit([&] {
  5017. svr.stop();
  5018. t.join();
  5019. ASSERT_FALSE(svr.is_running());
  5020. });
  5021. svr.wait_until_ready();
  5022. ResumingClient cli;
  5023. ASSERT_TRUE(cli.get());
  5024. ASSERT_TRUE(cli.get());
  5025. EXPECT_FALSE(cli.reused());
  5026. }
  5027. #endif
  5028. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  5029. // wolfSSL shares its session cache between contexts, so a resumed session
  5030. // could carry a client certificate checked against another server's CA, or
  5031. // against a client CA since replaced.
  5032. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  5033. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  5034. ASSERT_TRUE(svr.is_valid());
  5035. // Trusts a CA that did not sign the client's certificate.
  5036. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  5037. ASSERT_TRUE(other.is_valid());
  5038. for (auto s : {&svr, &other}) {
  5039. s->Get("/test", [](const Request &, Response &res) {
  5040. res.set_content("ok", "text/plain");
  5041. });
  5042. }
  5043. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5044. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  5045. auto se = detail::scope_exit([&] {
  5046. other.stop();
  5047. svr.stop();
  5048. t2.join();
  5049. t.join();
  5050. });
  5051. svr.wait_until_ready();
  5052. other.wait_until_ready();
  5053. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  5054. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  5055. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  5056. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  5057. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  5058. ASSERT_EQ(WOLFSSL_SUCCESS,
  5059. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  5060. WOLFSSL_FILETYPE_PEM));
  5061. WOLFSSL_SESSION *session = nullptr;
  5062. auto session_se = detail::scope_exit([&] {
  5063. if (session) { wolfSSL_SESSION_free(session); }
  5064. });
  5065. // A request over a new connection, resuming `session` when there is one and
  5066. // keeping the connection's own in its place. Tells whether it was answered.
  5067. auto get = [&](int port) {
  5068. auto error = Error::Success;
  5069. auto sock = detail::create_client_socket(
  5070. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  5071. /*connection_timeout_sec=*/5, 0,
  5072. /*read_timeout_sec=*/5, 0,
  5073. /*write_timeout_sec=*/5, 0, std::string(), error);
  5074. if (sock == INVALID_SOCKET) { return false; }
  5075. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  5076. auto ssl = wolfSSL_new(ctx);
  5077. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  5078. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  5079. if (session) { wolfSSL_set_session(ssl, session); }
  5080. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  5081. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  5082. "Connection: close\r\n\r\n";
  5083. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  5084. std::string res;
  5085. char buf[256];
  5086. int n;
  5087. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  5088. res.append(buf, static_cast<size_t>(n));
  5089. }
  5090. wolfSSL_shutdown(ssl);
  5091. if (session) { wolfSSL_SESSION_free(session); }
  5092. session = wolfSSL_get1_session(ssl);
  5093. return res.find("200 OK") != std::string::npos;
  5094. };
  5095. ASSERT_TRUE(get(PORT));
  5096. EXPECT_FALSE(get(PORT + 1));
  5097. ASSERT_TRUE(get(PORT));
  5098. ASSERT_TRUE(replace_client_ca(svr));
  5099. EXPECT_FALSE(get(PORT));
  5100. }
  5101. #endif
  5102. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  5103. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5104. ASSERT_TRUE(svr.is_valid());
  5105. // Keep-alive parking would wait for the ClientHello without a handshake.
  5106. svr.set_keep_alive_parking(false);
  5107. svr.Get("/test", [](const Request &, Response &res) {
  5108. res.set_content("ok", "text/plain");
  5109. });
  5110. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5111. auto se = detail::scope_exit([&] {
  5112. svr.stop();
  5113. t.join();
  5114. ASSERT_FALSE(svr.is_running());
  5115. });
  5116. svr.wait_until_ready();
  5117. // A connection that sends no ClientHello keeps its handshake in progress,
  5118. // once the server has had a moment to start it.
  5119. auto error = Error::Success;
  5120. auto sock = detail::create_client_socket(
  5121. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5122. /*connection_timeout_sec=*/5, 0,
  5123. /*read_timeout_sec=*/5, 0,
  5124. /*write_timeout_sec=*/5, 0, std::string(), error);
  5125. ASSERT_NE(INVALID_SOCKET, sock);
  5126. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5127. std::string cert_pem, key_pem;
  5128. read_file(SERVER_CERT_FILE, cert_pem);
  5129. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  5130. auto update = std::async(std::launch::async, [&]() {
  5131. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  5132. });
  5133. EXPECT_EQ(std::future_status::timeout,
  5134. update.wait_for(std::chrono::milliseconds(200)));
  5135. detail::close_socket(sock);
  5136. EXPECT_TRUE(update.get());
  5137. SSLClient cli(HOST, PORT);
  5138. cli.enable_server_certificate_verification(false);
  5139. auto res = cli.Get("/test");
  5140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5141. EXPECT_EQ(StatusCode::OK_200, res->status);
  5142. }
  5143. TEST(SSLClientServerTest, StopDoesNotWaitForHandshakeInProgress) {
  5144. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5145. ASSERT_TRUE(svr.is_valid());
  5146. // Keep-alive parking would wait for the ClientHello without a handshake.
  5147. svr.set_keep_alive_parking(false);
  5148. svr.set_read_timeout(10, 0);
  5149. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5150. auto se = detail::scope_exit([&] {
  5151. svr.stop();
  5152. if (t.joinable()) { t.join(); }
  5153. });
  5154. svr.wait_until_ready();
  5155. // A connection that sends no ClientHello keeps its handshake in progress,
  5156. // once the server has had a moment to start it.
  5157. auto error = Error::Success;
  5158. auto sock = detail::create_client_socket(
  5159. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5160. /*connection_timeout_sec=*/5, 0,
  5161. /*read_timeout_sec=*/5, 0,
  5162. /*write_timeout_sec=*/5, 0, std::string(), error);
  5163. ASSERT_NE(INVALID_SOCKET, sock);
  5164. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  5165. auto start = std::chrono::steady_clock::now();
  5166. svr.stop();
  5167. t.join();
  5168. auto elapsed = std::chrono::steady_clock::now() - start;
  5169. detail::close_socket(sock);
  5170. EXPECT_LT(elapsed, std::chrono::seconds(3));
  5171. }
  5172. #endif
  5173. TEST(ErrorHandlerTest, ContentLength) {
  5174. Server svr;
  5175. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5176. res.status = StatusCode::OK_200;
  5177. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5178. "text/html"); // <= Content-Length still 13
  5179. });
  5180. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5181. res.set_content("Hello World!\n", "text/plain");
  5182. res.status = 524;
  5183. });
  5184. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5185. auto se = detail::scope_exit([&] {
  5186. svr.stop();
  5187. thread.join();
  5188. ASSERT_FALSE(svr.is_running());
  5189. });
  5190. svr.wait_until_ready();
  5191. {
  5192. Client cli(HOST, PORT);
  5193. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5195. EXPECT_EQ(StatusCode::OK_200, res->status);
  5196. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5197. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5198. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5199. }
  5200. }
  5201. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5202. TEST(ExceptionTest, WithoutExceptionHandler) {
  5203. Server svr;
  5204. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  5205. throw std::runtime_error("exception...");
  5206. });
  5207. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  5208. throw std::runtime_error("exception\r\n...");
  5209. });
  5210. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5211. auto se = detail::scope_exit([&] {
  5212. svr.stop();
  5213. listen_thread.join();
  5214. ASSERT_FALSE(svr.is_running());
  5215. });
  5216. svr.wait_until_ready();
  5217. Client cli("localhost", PORT);
  5218. {
  5219. auto res = cli.Get("/exception");
  5220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5221. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5222. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5223. }
  5224. {
  5225. auto res = cli.Get("/unknown");
  5226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5227. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5228. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5229. }
  5230. }
  5231. TEST(ExceptionTest, WithExceptionHandler) {
  5232. Server svr;
  5233. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  5234. std::exception_ptr ep) {
  5235. EXPECT_FALSE(ep == nullptr);
  5236. try {
  5237. std::rethrow_exception(ep);
  5238. } catch (std::exception &e) {
  5239. EXPECT_EQ("abc", std::string(e.what()));
  5240. } catch (...) {}
  5241. res.status = StatusCode::InternalServerError_500;
  5242. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5243. "text/html"); // <= Content-Length still 13 at this point
  5244. });
  5245. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5246. res.set_content("Hello World!\n", "text/plain");
  5247. throw std::runtime_error("abc");
  5248. });
  5249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5250. auto se = detail::scope_exit([&] {
  5251. svr.stop();
  5252. thread.join();
  5253. ASSERT_FALSE(svr.is_running());
  5254. });
  5255. svr.wait_until_ready();
  5256. for (size_t i = 0; i < 10; i++) {
  5257. Client cli(HOST, PORT);
  5258. for (size_t j = 0; j < 100; j++) {
  5259. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5261. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5262. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5263. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5264. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5265. }
  5266. cli.set_keep_alive(true);
  5267. for (size_t j = 0; j < 100; j++) {
  5268. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5270. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5271. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5272. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5273. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5274. }
  5275. }
  5276. }
  5277. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5278. Server svr;
  5279. svr.set_exception_handler(
  5280. [](const Request &, Response &res, std::exception_ptr) {
  5281. res.set_content("oops", "text/plain");
  5282. });
  5283. svr.Get("/throw", [](const Request &, Response &) {
  5284. throw std::runtime_error("throw");
  5285. });
  5286. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5287. res.status = StatusCode::Created_201;
  5288. throw std::runtime_error("created-then-throw");
  5289. });
  5290. auto port = svr.bind_to_any_port(HOST);
  5291. ASSERT_GT(port, 0);
  5292. thread t = thread([&] { svr.listen_after_bind(); });
  5293. auto se = detail::scope_exit([&] {
  5294. svr.stop();
  5295. t.join();
  5296. ASSERT_FALSE(svr.is_running());
  5297. });
  5298. svr.wait_until_ready();
  5299. Client cli(HOST, port);
  5300. for (auto path : {"/throw", "/created-then-throw"}) {
  5301. auto res = cli.Get(path);
  5302. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5303. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5304. }
  5305. }
  5306. TEST(ExceptionTest, AndErrorHandler) {
  5307. Server svr;
  5308. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5309. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5310. });
  5311. svr.set_exception_handler(
  5312. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5313. EXPECT_FALSE(ep == nullptr);
  5314. try {
  5315. std::rethrow_exception(ep);
  5316. } catch (std::exception &e) {
  5317. res.set_content(e.what(), "text/html");
  5318. } catch (...) {}
  5319. res.status = StatusCode::InternalServerError_500;
  5320. });
  5321. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5322. throw std::runtime_error("EXCEPTION");
  5323. });
  5324. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5325. res.set_content("ERROR", "text/html");
  5326. res.status = StatusCode::InternalServerError_500;
  5327. });
  5328. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5329. auto se = detail::scope_exit([&] {
  5330. svr.stop();
  5331. thread.join();
  5332. ASSERT_FALSE(svr.is_running());
  5333. });
  5334. svr.wait_until_ready();
  5335. Client cli(HOST, PORT);
  5336. {
  5337. auto res = cli.Get("/exception");
  5338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5339. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5340. EXPECT_EQ("EXCEPTION", res->body);
  5341. }
  5342. {
  5343. auto res = cli.Get("/error");
  5344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5345. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5346. EXPECT_EQ("ERROR", res->body);
  5347. }
  5348. {
  5349. auto res = cli.Get("/invalid");
  5350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5351. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5352. EXPECT_EQ("NOT_FOUND", res->body);
  5353. }
  5354. }
  5355. #endif
  5356. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5357. // An exception from a user callback outside process_request()'s try/catch
  5358. // used to unwind into the task queue - which does not catch - and terminate
  5359. // the process. Each test below runs the server on a single worker thread: a
  5360. // guard that catches the exception but still loses the thread would otherwise
  5361. // be hidden by a spare worker serving the follow-up request. Note that a
  5362. // regression here aborts the whole test binary rather than failing one test.
  5363. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5364. Server svr;
  5365. svr.new_task_queue = [] { return new ThreadPool(1); };
  5366. std::atomic<int> reported{0};
  5367. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5368. if (err == Error::UserCallbackException) { reported++; }
  5369. });
  5370. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5371. res.set_content_provider(
  5372. 1024, "text/plain",
  5373. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5374. sink.write("hello", 5);
  5375. throw std::runtime_error("from the content provider");
  5376. });
  5377. });
  5378. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5379. res.set_content("ok", "text/plain");
  5380. });
  5381. auto port = svr.bind_to_any_port(HOST);
  5382. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5383. auto se = detail::scope_exit([&] {
  5384. svr.stop();
  5385. listen_thread.join();
  5386. ASSERT_FALSE(svr.is_running());
  5387. });
  5388. svr.wait_until_ready();
  5389. {
  5390. Client cli(HOST, port);
  5391. cli.set_read_timeout(5, 0);
  5392. EXPECT_FALSE(cli.Get("/throw"));
  5393. }
  5394. EXPECT_TRUE(svr.is_running());
  5395. EXPECT_EQ(1, reported.load());
  5396. // A request on a fresh connection is still served.
  5397. {
  5398. Client cli(HOST, port);
  5399. auto res = cli.Get("/ok");
  5400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5401. EXPECT_EQ(StatusCode::OK_200, res->status);
  5402. EXPECT_EQ("ok", res->body);
  5403. }
  5404. }
  5405. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5406. Server svr;
  5407. svr.new_task_queue = [] { return new ThreadPool(1); };
  5408. std::atomic<bool> should_throw{true};
  5409. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5410. res.set_content("hi", "text/plain");
  5411. });
  5412. svr.set_post_routing_handler(
  5413. [&](const Request & /*req*/, Response & /*res*/) {
  5414. if (should_throw) {
  5415. throw std::runtime_error("from the post-routing handler");
  5416. }
  5417. });
  5418. auto port = svr.bind_to_any_port(HOST);
  5419. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5420. auto se = detail::scope_exit([&] {
  5421. svr.stop();
  5422. listen_thread.join();
  5423. ASSERT_FALSE(svr.is_running());
  5424. });
  5425. svr.wait_until_ready();
  5426. {
  5427. Client cli(HOST, port);
  5428. cli.set_read_timeout(5, 0);
  5429. EXPECT_FALSE(cli.Get("/hi"));
  5430. }
  5431. EXPECT_TRUE(svr.is_running());
  5432. should_throw = false;
  5433. {
  5434. Client cli(HOST, port);
  5435. auto res = cli.Get("/hi");
  5436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5437. EXPECT_EQ(StatusCode::OK_200, res->status);
  5438. EXPECT_EQ("hi", res->body);
  5439. }
  5440. }
  5441. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5442. // The guard reports the caught exception through the error logger, which is
  5443. // a user callback too. A logger that throws has to be contained as well, or
  5444. // the process would terminate from inside the catch.
  5445. Server svr;
  5446. svr.new_task_queue = [] { return new ThreadPool(1); };
  5447. std::atomic<int> reported{0};
  5448. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5449. if (err == Error::UserCallbackException) {
  5450. reported++;
  5451. throw std::runtime_error("from the error logger");
  5452. }
  5453. });
  5454. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5455. res.set_content_provider(
  5456. 1024, "text/plain",
  5457. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5458. sink.write("hello", 5);
  5459. throw std::runtime_error("from the content provider");
  5460. });
  5461. });
  5462. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5463. res.set_content("ok", "text/plain");
  5464. });
  5465. auto port = svr.bind_to_any_port(HOST);
  5466. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5467. auto se = detail::scope_exit([&] {
  5468. svr.stop();
  5469. listen_thread.join();
  5470. ASSERT_FALSE(svr.is_running());
  5471. });
  5472. svr.wait_until_ready();
  5473. {
  5474. Client cli(HOST, port);
  5475. cli.set_read_timeout(5, 0);
  5476. EXPECT_FALSE(cli.Get("/throw"));
  5477. }
  5478. EXPECT_TRUE(svr.is_running());
  5479. EXPECT_EQ(1, reported.load());
  5480. {
  5481. Client cli(HOST, port);
  5482. auto res = cli.Get("/ok");
  5483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5484. EXPECT_EQ(StatusCode::OK_200, res->status);
  5485. EXPECT_EQ("ok", res->body);
  5486. }
  5487. }
  5488. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5489. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5490. // so the exception unwinds through the ws::WebSocket object on its way to
  5491. // the guard. None of the HTTP cases above cross that.
  5492. Server svr;
  5493. svr.new_task_queue = [] { return new ThreadPool(1); };
  5494. std::atomic<int> reported{0};
  5495. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5496. if (err == Error::UserCallbackException) { reported++; }
  5497. });
  5498. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5499. throw std::runtime_error("from the WebSocket handler");
  5500. });
  5501. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5502. res.set_content("ok", "text/plain");
  5503. });
  5504. auto port = svr.bind_to_any_port(HOST);
  5505. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5506. auto se = detail::scope_exit([&] {
  5507. svr.stop();
  5508. listen_thread.join();
  5509. ASSERT_FALSE(svr.is_running());
  5510. });
  5511. svr.wait_until_ready();
  5512. {
  5513. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5514. "/ws");
  5515. auto res = client.connect();
  5516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5517. // The server dropped the connection instead of dying.
  5518. std::string msg;
  5519. EXPECT_FALSE(client.read(msg));
  5520. client.close();
  5521. }
  5522. EXPECT_TRUE(svr.is_running());
  5523. EXPECT_EQ(1, reported.load());
  5524. {
  5525. Client cli(HOST, port);
  5526. auto res = cli.Get("/ok");
  5527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5528. EXPECT_EQ(StatusCode::OK_200, res->status);
  5529. EXPECT_EQ("ok", res->body);
  5530. }
  5531. }
  5532. #ifdef CPPHTTPLIB_SSL_ENABLED
  5533. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5534. // SSLServer::process_and_close_socket() is a separate overload with its own
  5535. // guard, so it is exercised on its own.
  5536. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5537. ASSERT_TRUE(svr.is_valid());
  5538. svr.new_task_queue = [] { return new ThreadPool(1); };
  5539. std::atomic<int> reported{0};
  5540. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5541. if (err == Error::UserCallbackException) { reported++; }
  5542. });
  5543. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5544. res.set_content_provider(
  5545. 1024, "text/plain",
  5546. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5547. sink.write("hello", 5);
  5548. throw std::runtime_error("from the content provider");
  5549. });
  5550. });
  5551. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5552. res.set_content("ok", "text/plain");
  5553. });
  5554. auto port = svr.bind_to_any_port(HOST);
  5555. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5556. auto se = detail::scope_exit([&] {
  5557. svr.stop();
  5558. listen_thread.join();
  5559. ASSERT_FALSE(svr.is_running());
  5560. });
  5561. svr.wait_until_ready();
  5562. {
  5563. SSLClient cli(HOST, port);
  5564. cli.enable_server_certificate_verification(false);
  5565. cli.set_read_timeout(5, 0);
  5566. EXPECT_FALSE(cli.Get("/throw"));
  5567. }
  5568. EXPECT_TRUE(svr.is_running());
  5569. EXPECT_EQ(1, reported.load());
  5570. {
  5571. SSLClient cli(HOST, port);
  5572. cli.enable_server_certificate_verification(false);
  5573. auto res = cli.Get("/ok");
  5574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5575. EXPECT_EQ(StatusCode::OK_200, res->status);
  5576. EXPECT_EQ("ok", res->body);
  5577. }
  5578. }
  5579. #endif
  5580. #endif
  5581. TEST(NoContentTest, ContentLength) {
  5582. Server svr;
  5583. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5584. res.status = StatusCode::NoContent_204;
  5585. });
  5586. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5587. auto se = detail::scope_exit([&] {
  5588. svr.stop();
  5589. thread.join();
  5590. ASSERT_FALSE(svr.is_running());
  5591. });
  5592. svr.wait_until_ready();
  5593. {
  5594. Client cli(HOST, PORT);
  5595. auto res = cli.Get("/hi");
  5596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5597. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5598. // RFC 9110 8.6: none in a 204 response
  5599. EXPECT_FALSE(res->has_header("Content-Length"));
  5600. }
  5601. }
  5602. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5603. Server svr;
  5604. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5605. res.set_header("Content-Length", "5");
  5606. res.set_content("hello world", "text/plain");
  5607. });
  5608. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5609. // A body that reads as the last chunk, were it taken as chunked
  5610. res.set_header("Transfer-Encoding", "chunked");
  5611. res.set_content("0\r\n\r\n", "text/plain");
  5612. });
  5613. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5614. res.set_header("Content-Length", "2");
  5615. res.set_content_provider(5, "text/plain",
  5616. [](size_t offset, size_t length, DataSink &sink) {
  5617. sink.write(&"hello"[offset], length);
  5618. return true;
  5619. });
  5620. });
  5621. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5622. res.set_header("Content-Length", "1234");
  5623. });
  5624. thread t = thread([&] { svr.listen(HOST, PORT); });
  5625. auto se = detail::scope_exit([&] {
  5626. svr.stop();
  5627. t.join();
  5628. ASSERT_FALSE(svr.is_running());
  5629. });
  5630. svr.wait_until_ready();
  5631. Client cli(HOST, PORT);
  5632. cli.set_read_timeout(1, 0);
  5633. auto expect_body = [&](const Result &res, const std::string &body) {
  5634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5635. EXPECT_EQ(body, res->body);
  5636. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5637. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5638. };
  5639. Headers identity{{"Accept-Encoding", ""}};
  5640. expect_body(cli.Get("/body", identity), "hello world");
  5641. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5642. expect_body(cli.Get("/body",
  5643. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5644. "he");
  5645. expect_body(cli.Get("/provider", identity), "hello");
  5646. expect_body(cli.Get("/empty", identity), "");
  5647. // A HEAD response may give the length of the body a GET would get.
  5648. auto res = cli.Head("/empty");
  5649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5650. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5651. }
  5652. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5653. Server svr;
  5654. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5655. res.set_content("short", "text/plain");
  5656. });
  5657. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5658. res.body += " with a footer";
  5659. res.set_header("Transfer-Encoding", "chunked");
  5660. });
  5661. thread t = thread([&] { svr.listen(HOST, PORT); });
  5662. auto se = detail::scope_exit([&] {
  5663. svr.stop();
  5664. t.join();
  5665. ASSERT_FALSE(svr.is_running());
  5666. });
  5667. svr.wait_until_ready();
  5668. Client cli(HOST, PORT);
  5669. cli.set_read_timeout(1, 0);
  5670. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5672. EXPECT_EQ("short with a footer", res->body);
  5673. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5674. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5675. }
  5676. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5677. Server svr;
  5678. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5679. res.set_header("Content-Length", "3");
  5680. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5681. sink.write("abc", 3);
  5682. sink.done();
  5683. return true;
  5684. });
  5685. });
  5686. thread t = thread([&] { svr.listen(HOST, PORT); });
  5687. auto se = detail::scope_exit([&] {
  5688. svr.stop();
  5689. t.join();
  5690. ASSERT_FALSE(svr.is_running());
  5691. });
  5692. svr.wait_until_ready();
  5693. Client cli(HOST, PORT);
  5694. cli.set_keep_alive(true);
  5695. auto res = cli.Get("/");
  5696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5697. EXPECT_EQ("abc", res->body);
  5698. EXPECT_FALSE(res->has_header("Content-Length"));
  5699. EXPECT_EQ("close", res->get_header_value("Connection"));
  5700. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5701. // No body to delimit
  5702. auto head = cli.Head("/");
  5703. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5704. EXPECT_FALSE(head->has_header("Connection"));
  5705. }
  5706. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5707. #ifdef CPPHTTPLIB_SSL_ENABLED
  5708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5709. ASSERT_TRUE(svr.is_valid());
  5710. #else
  5711. Server svr;
  5712. #endif
  5713. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5714. if (req.path == "/routing_handler") {
  5715. res.set_header("PRE_ROUTING", "on");
  5716. res.set_content("Routing Handler", "text/plain");
  5717. return httplib::Server::HandlerResponse::Handled;
  5718. }
  5719. return httplib::Server::HandlerResponse::Unhandled;
  5720. });
  5721. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5722. res.set_content("Error", "text/html");
  5723. });
  5724. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5725. if (req.path == "/routing_handler") {
  5726. res.set_header("POST_ROUTING", "on");
  5727. }
  5728. });
  5729. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5730. res.set_content("Hello World!\n", "text/plain");
  5731. });
  5732. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5733. auto se = detail::scope_exit([&] {
  5734. svr.stop();
  5735. thread.join();
  5736. ASSERT_FALSE(svr.is_running());
  5737. });
  5738. svr.wait_until_ready();
  5739. {
  5740. #ifdef CPPHTTPLIB_SSL_ENABLED
  5741. SSLClient cli(HOST, PORT);
  5742. cli.enable_server_certificate_verification(false);
  5743. #else
  5744. Client cli(HOST, PORT);
  5745. #endif
  5746. auto res = cli.Get("/routing_handler");
  5747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5748. EXPECT_EQ(StatusCode::OK_200, res->status);
  5749. EXPECT_EQ("Routing Handler", res->body);
  5750. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5751. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5752. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5753. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5754. }
  5755. {
  5756. #ifdef CPPHTTPLIB_SSL_ENABLED
  5757. SSLClient cli(HOST, PORT);
  5758. cli.enable_server_certificate_verification(false);
  5759. #else
  5760. Client cli(HOST, PORT);
  5761. #endif
  5762. auto res = cli.Get("/hi");
  5763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5764. EXPECT_EQ(StatusCode::OK_200, res->status);
  5765. EXPECT_EQ("Hello World!\n", res->body);
  5766. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5767. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5768. }
  5769. {
  5770. #ifdef CPPHTTPLIB_SSL_ENABLED
  5771. SSLClient cli(HOST, PORT);
  5772. cli.enable_server_certificate_verification(false);
  5773. #else
  5774. Client cli(HOST, PORT);
  5775. #endif
  5776. auto res = cli.Get("/aaa");
  5777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5778. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5779. EXPECT_EQ("Error", res->body);
  5780. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5781. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5782. }
  5783. }
  5784. TEST(RequestHandlerTest, PreRequestHandler) {
  5785. auto route_path = "/user/:user";
  5786. Server svr;
  5787. svr.Get("/hi", [](const Request &, Response &res) {
  5788. res.set_content("hi", "text/plain");
  5789. });
  5790. svr.Get(route_path, [](const Request &req, Response &res) {
  5791. res.set_content(req.path_params.at("user"), "text/plain");
  5792. });
  5793. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5794. if (req.matched_route == route_path) {
  5795. auto user = req.path_params.at("user");
  5796. if (user != "john") {
  5797. res.status = StatusCode::Forbidden_403;
  5798. res.set_content("error", "text/html");
  5799. return Server::HandlerResponse::Handled;
  5800. }
  5801. }
  5802. return Server::HandlerResponse::Unhandled;
  5803. });
  5804. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5805. auto se = detail::scope_exit([&] {
  5806. svr.stop();
  5807. thread.join();
  5808. ASSERT_FALSE(svr.is_running());
  5809. });
  5810. svr.wait_until_ready();
  5811. Client cli(HOST, PORT);
  5812. {
  5813. auto res = cli.Get("/hi");
  5814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5815. EXPECT_EQ(StatusCode::OK_200, res->status);
  5816. EXPECT_EQ("hi", res->body);
  5817. }
  5818. {
  5819. auto res = cli.Get("/user/john");
  5820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5821. EXPECT_EQ(StatusCode::OK_200, res->status);
  5822. EXPECT_EQ("john", res->body);
  5823. }
  5824. {
  5825. auto res = cli.Get("/user/invalid-user");
  5826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5827. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5828. EXPECT_EQ("error", res->body);
  5829. }
  5830. }
  5831. // The pre-request handler must run before the request body is read, so a
  5832. // rejected request never forces the server to buffer a (potentially large)
  5833. // body. Here the posted body is larger than the payload limit: if the body
  5834. // were read first the server would answer 413, but because the pre-request
  5835. // handler runs first it answers 403 and the body is never read.
  5836. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5837. Server svr;
  5838. svr.set_payload_max_length(8);
  5839. auto handler_ran = false;
  5840. svr.Post("/reject", [&](const Request &req, Response &res) {
  5841. handler_ran = true;
  5842. res.set_content(req.body, "text/plain");
  5843. });
  5844. svr.Post("/accept", [](const Request &req, Response &res) {
  5845. res.set_content(req.body, "text/plain");
  5846. });
  5847. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5848. if (req.matched_route == "/reject") {
  5849. res.status = StatusCode::Forbidden_403;
  5850. res.set_content("denied", "text/plain");
  5851. return Server::HandlerResponse::Handled;
  5852. }
  5853. return Server::HandlerResponse::Unhandled;
  5854. });
  5855. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5856. auto se = detail::scope_exit([&] {
  5857. svr.stop();
  5858. thread.join();
  5859. ASSERT_FALSE(svr.is_running());
  5860. });
  5861. svr.wait_until_ready();
  5862. Client cli(HOST, PORT);
  5863. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5864. // rejects with 403 before the body is read, so 413 is never reached.
  5865. {
  5866. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5868. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5869. EXPECT_EQ("denied", res->body);
  5870. EXPECT_FALSE(handler_ran);
  5871. }
  5872. // An approved route still reads the body and enforces the payload limit.
  5873. {
  5874. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5876. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5877. }
  5878. }
  5879. TEST(UserDataTest, BasicOperations) {
  5880. httplib::UserData ud;
  5881. // Initially empty
  5882. EXPECT_FALSE(ud.has("key"));
  5883. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5884. // set and get
  5885. ud.set("key", 42);
  5886. EXPECT_TRUE(ud.has("key"));
  5887. auto *p = ud.get<int>("key");
  5888. ASSERT_NE(nullptr, p);
  5889. EXPECT_EQ(42, *p);
  5890. // Type mismatch → nullptr
  5891. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5892. // Overwrite with different type
  5893. ud.set("key", std::string("hello"));
  5894. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5895. auto *s = ud.get<std::string>("key");
  5896. ASSERT_NE(nullptr, s);
  5897. EXPECT_EQ("hello", *s);
  5898. // erase
  5899. ud.erase("key");
  5900. EXPECT_FALSE(ud.has("key"));
  5901. // clear
  5902. ud.set("a", 1);
  5903. ud.set("b", 2);
  5904. ud.clear();
  5905. EXPECT_FALSE(ud.has("a"));
  5906. EXPECT_FALSE(ud.has("b"));
  5907. }
  5908. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5909. struct AuthCtx {
  5910. std::string user_id;
  5911. };
  5912. Server svr;
  5913. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5914. res.user_data.set("auth", AuthCtx{"alice"});
  5915. return Server::HandlerResponse::Unhandled;
  5916. });
  5917. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5918. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5919. ASSERT_NE(nullptr, ctx);
  5920. res.set_content("Hello " + ctx->user_id, "text/plain");
  5921. });
  5922. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5923. auto se = detail::scope_exit([&] {
  5924. svr.stop();
  5925. thread.join();
  5926. ASSERT_FALSE(svr.is_running());
  5927. });
  5928. svr.wait_until_ready();
  5929. Client cli(HOST, PORT);
  5930. auto res = cli.Get("/me");
  5931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5932. EXPECT_EQ(StatusCode::OK_200, res->status);
  5933. EXPECT_EQ("Hello alice", res->body);
  5934. }
  5935. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5936. struct RoleCtx {
  5937. std::string role;
  5938. };
  5939. Server svr;
  5940. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5941. res.user_data.set("role", RoleCtx{"admin"});
  5942. return Server::HandlerResponse::Unhandled;
  5943. });
  5944. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5945. auto *ctx = res.user_data.get<RoleCtx>("role");
  5946. ASSERT_NE(nullptr, ctx);
  5947. res.set_content(ctx->role, "text/plain");
  5948. });
  5949. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5950. auto se = detail::scope_exit([&] {
  5951. svr.stop();
  5952. thread.join();
  5953. ASSERT_FALSE(svr.is_running());
  5954. });
  5955. svr.wait_until_ready();
  5956. Client cli(HOST, PORT);
  5957. auto res = cli.Get("/role");
  5958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5959. EXPECT_EQ(StatusCode::OK_200, res->status);
  5960. EXPECT_EQ("admin", res->body);
  5961. }
  5962. TEST(InvalidFormatTest, StatusCode) {
  5963. Server svr;
  5964. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5965. res.set_content("Hello World!\n", "text/plain");
  5966. res.status = 9999; // Status should be a three-digit code...
  5967. });
  5968. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5969. auto se = detail::scope_exit([&] {
  5970. svr.stop();
  5971. thread.join();
  5972. ASSERT_FALSE(svr.is_running());
  5973. });
  5974. svr.wait_until_ready();
  5975. {
  5976. Client cli(HOST, PORT);
  5977. auto res = cli.Get("/hi");
  5978. ASSERT_FALSE(res);
  5979. }
  5980. }
  5981. TEST(URLFragmentTest, WithFragment) {
  5982. Server svr;
  5983. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5984. EXPECT_TRUE(req.target == "/hi");
  5985. });
  5986. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5987. auto se = detail::scope_exit([&] {
  5988. svr.stop();
  5989. thread.join();
  5990. ASSERT_FALSE(svr.is_running());
  5991. });
  5992. svr.wait_until_ready();
  5993. {
  5994. Client cli(HOST, PORT);
  5995. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5996. EXPECT_TRUE(res);
  5997. EXPECT_EQ(StatusCode::OK_200, res->status);
  5998. res = cli.Get("/hi%23key1=val1=key2=val2");
  5999. EXPECT_TRUE(res);
  6000. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6001. }
  6002. }
  6003. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  6004. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  6005. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  6006. Server svr;
  6007. std::vector<std::string> targets;
  6008. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  6009. targets.push_back(req.target);
  6010. });
  6011. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6012. auto se = detail::scope_exit([&] {
  6013. svr.stop();
  6014. thread.join();
  6015. ASSERT_FALSE(svr.is_running());
  6016. });
  6017. svr.wait_until_ready();
  6018. Client cli(HOST, PORT);
  6019. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  6020. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  6021. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  6022. // A '?' after the '#' belongs to the fragment, not to the query.
  6023. Request req;
  6024. req.method = "GET";
  6025. req.path = "/hi#f?x=1";
  6026. req.params.emplace("a", "1");
  6027. Response res;
  6028. auto error = Error::Success;
  6029. EXPECT_TRUE(cli.send(req, res, error));
  6030. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  6031. "/hi?a=1"}),
  6032. targets);
  6033. }
  6034. TEST(HeaderWriter, SetHeaderWriter) {
  6035. Server svr;
  6036. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  6037. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  6038. return detail::write_headers(strm, hdrs);
  6039. });
  6040. svr.Get("/hi", [](const Request &req, Response &res) {
  6041. auto it = req.headers.find("CustomClientHeader");
  6042. EXPECT_TRUE(it != req.headers.end());
  6043. EXPECT_EQ(it->second, "CustomClientValue");
  6044. res.set_content("Hello World!\n", "text/plain");
  6045. });
  6046. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6047. auto se = detail::scope_exit([&] {
  6048. svr.stop();
  6049. thread.join();
  6050. ASSERT_FALSE(svr.is_running());
  6051. });
  6052. svr.wait_until_ready();
  6053. {
  6054. Client cli(HOST, PORT);
  6055. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  6056. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  6057. return detail::write_headers(strm, hdrs);
  6058. });
  6059. auto res = cli.Get("/hi");
  6060. EXPECT_TRUE(res);
  6061. EXPECT_EQ(StatusCode::OK_200, res->status);
  6062. auto it = res->headers.find("CustomServerHeader");
  6063. EXPECT_TRUE(it != res->headers.end());
  6064. EXPECT_EQ(it->second, "CustomServerValue");
  6065. }
  6066. }
  6067. class ServerTest : public ::testing::Test {
  6068. protected:
  6069. ServerTest()
  6070. : cli_(HOST, PORT)
  6071. #ifdef CPPHTTPLIB_SSL_ENABLED
  6072. ,
  6073. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6074. #endif
  6075. {
  6076. #ifdef CPPHTTPLIB_SSL_ENABLED
  6077. cli_.enable_server_certificate_verification(false);
  6078. #endif
  6079. // Allow LARGE_DATA (100MB) responses
  6080. cli_.set_payload_max_length(200 * 1024 * 1024);
  6081. }
  6082. virtual void SetUp() {
  6083. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  6084. svr_.set_payload_max_length(200 * 1024 * 1024);
  6085. svr_.set_mount_point("/", "./www");
  6086. svr_.set_mount_point("/mount", "./www2");
  6087. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  6088. svr_.Get("/hi",
  6089. [&](const Request & /*req*/, Response &res) {
  6090. res.set_content("Hello World!", "text/plain");
  6091. })
  6092. .Get("/file_content",
  6093. [&](const Request & /*req*/, Response &res) {
  6094. res.set_file_content("./www/dir/test.html");
  6095. })
  6096. .Get("/file_content_with_content_type",
  6097. [&](const Request & /*req*/, Response &res) {
  6098. res.set_file_content("./www/file", "text/plain");
  6099. })
  6100. .Get("/invalid_file_content",
  6101. [&](const Request & /*req*/, Response &res) {
  6102. res.set_file_content("./www/dir/invalid_file_path");
  6103. })
  6104. .Get("/http_response_splitting",
  6105. [&](const Request & /*req*/, Response &res) {
  6106. res.set_header("a", "1\r\nSet-Cookie: a=1");
  6107. EXPECT_EQ(0U, res.headers.size());
  6108. EXPECT_FALSE(res.has_header("a"));
  6109. res.set_header("a", "1\nSet-Cookie: a=1");
  6110. EXPECT_EQ(0U, res.headers.size());
  6111. EXPECT_FALSE(res.has_header("a"));
  6112. res.set_header("a", "1\rSet-Cookie: a=1");
  6113. EXPECT_EQ(0U, res.headers.size());
  6114. EXPECT_FALSE(res.has_header("a"));
  6115. res.set_header("a\r\nb", "0");
  6116. EXPECT_EQ(0U, res.headers.size());
  6117. EXPECT_FALSE(res.has_header("a"));
  6118. res.set_header("a\rb", "0");
  6119. EXPECT_EQ(0U, res.headers.size());
  6120. EXPECT_FALSE(res.has_header("a"));
  6121. res.set_header("a\nb", "0");
  6122. EXPECT_EQ(0U, res.headers.size());
  6123. EXPECT_FALSE(res.has_header("a"));
  6124. res.set_redirect("1\r\nSet-Cookie: a=1");
  6125. EXPECT_EQ(0U, res.headers.size());
  6126. EXPECT_FALSE(res.has_header("Location"));
  6127. })
  6128. .Get("/slow",
  6129. [&](const Request & /*req*/, Response &res) {
  6130. std::this_thread::sleep_for(std::chrono::seconds(4));
  6131. res.set_content("slow", "text/plain");
  6132. })
  6133. #if 0
  6134. .Post("/slowpost",
  6135. [&](const Request & /*req*/, Response &res) {
  6136. std::this_thread::sleep_for(std::chrono::seconds(2));
  6137. res.set_content("slow", "text/plain");
  6138. })
  6139. #endif
  6140. .Get("/remote_addr",
  6141. [&](const Request &req, Response &res) {
  6142. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  6143. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  6144. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6145. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  6146. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  6147. #endif
  6148. res.set_content(req.remote_addr, "text/plain");
  6149. })
  6150. .Get("/local_addr",
  6151. [&](const Request &req, Response &res) {
  6152. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  6153. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  6154. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6155. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  6156. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  6157. #endif
  6158. auto local_addr = req.local_addr;
  6159. auto local_port = std::to_string(req.local_port);
  6160. res.set_content(local_addr.append(":").append(local_port),
  6161. "text/plain");
  6162. })
  6163. .Get("/endwith%",
  6164. [&](const Request & /*req*/, Response &res) {
  6165. res.set_content("Hello World!", "text/plain");
  6166. })
  6167. .Get("/a\\+\\+b",
  6168. [&](const Request &req, Response &res) {
  6169. ASSERT_TRUE(req.has_param("a +b"));
  6170. auto val = req.get_param_value("a +b");
  6171. res.set_content(val, "text/plain");
  6172. })
  6173. .Get("/", [&](const Request & /*req*/,
  6174. Response &res) { res.set_redirect("/hi"); })
  6175. .Post("/1",
  6176. [](const Request & /*req*/, Response &res) {
  6177. res.set_redirect("/2", StatusCode::SeeOther_303);
  6178. })
  6179. .Get("/2",
  6180. [](const Request & /*req*/, Response &res) {
  6181. res.set_content("redirected.", "text/plain");
  6182. res.status = StatusCode::OK_200;
  6183. })
  6184. .Post("/person",
  6185. [&](const Request &req, Response &res) {
  6186. if (req.has_param("name") && req.has_param("note")) {
  6187. persons_[req.get_param_value("name")] =
  6188. req.get_param_value("note");
  6189. } else {
  6190. res.status = StatusCode::BadRequest_400;
  6191. }
  6192. })
  6193. .Put("/person",
  6194. [&](const Request &req, Response &res) {
  6195. if (req.has_param("name") && req.has_param("note")) {
  6196. persons_[req.get_param_value("name")] =
  6197. req.get_param_value("note");
  6198. } else {
  6199. res.status = StatusCode::BadRequest_400;
  6200. }
  6201. })
  6202. .Get("/person/(.*)",
  6203. [&](const Request &req, Response &res) {
  6204. string name = req.matches[1];
  6205. if (persons_.find(name) != persons_.end()) {
  6206. auto note = persons_[name];
  6207. res.set_content(note, "text/plain");
  6208. } else {
  6209. res.status = StatusCode::NotFound_404;
  6210. }
  6211. })
  6212. .Delete("/person",
  6213. [&](const Request &req, Response &res) {
  6214. if (req.has_param("name")) {
  6215. string name = req.get_param_value("name");
  6216. if (persons_.find(name) != persons_.end()) {
  6217. persons_.erase(name);
  6218. res.set_content("DELETED", "text/plain");
  6219. } else {
  6220. res.status = StatusCode::NotFound_404;
  6221. }
  6222. } else {
  6223. res.status = StatusCode::BadRequest_400;
  6224. }
  6225. })
  6226. .Post("/x-www-form-urlencoded-json",
  6227. [&](const Request &req, Response &res) {
  6228. auto json = req.get_param_value("json");
  6229. ASSERT_EQ(JSON_DATA, json);
  6230. res.set_content(json, "appliation/json");
  6231. res.status = StatusCode::OK_200;
  6232. })
  6233. .Get("/streamed-chunked",
  6234. [&](const Request & /*req*/, Response &res) {
  6235. res.set_chunked_content_provider(
  6236. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  6237. sink.os << "123";
  6238. sink.os << "456";
  6239. sink.os << "789";
  6240. sink.done();
  6241. return true;
  6242. });
  6243. })
  6244. .Get("/streamed-chunked-with-prohibited-trailer",
  6245. [&](const Request & /*req*/, Response &res) {
  6246. auto i = new int(0);
  6247. // Declare both a prohibited trailer (Content-Length) and an
  6248. // allowed one
  6249. res.set_header("Trailer", "Content-Length, X-Allowed");
  6250. res.set_chunked_content_provider(
  6251. "text/plain",
  6252. [i](size_t /*offset*/, DataSink &sink) {
  6253. switch (*i) {
  6254. case 0: sink.os << "123"; break;
  6255. case 1: sink.os << "456"; break;
  6256. case 2: sink.os << "789"; break;
  6257. case 3: {
  6258. sink.done_with_trailer(
  6259. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  6260. } break;
  6261. }
  6262. (*i)++;
  6263. return true;
  6264. },
  6265. [i](bool success) {
  6266. EXPECT_TRUE(success);
  6267. delete i;
  6268. });
  6269. })
  6270. .Get("/streamed-chunked2",
  6271. [&](const Request & /*req*/, Response &res) {
  6272. auto i = new int(0);
  6273. res.set_chunked_content_provider(
  6274. "text/plain",
  6275. [i](size_t /*offset*/, DataSink &sink) {
  6276. switch (*i) {
  6277. case 0: sink.os << "123"; break;
  6278. case 1: sink.os << "456"; break;
  6279. case 2: sink.os << "789"; break;
  6280. case 3: sink.done(); break;
  6281. }
  6282. (*i)++;
  6283. return true;
  6284. },
  6285. [i](bool success) {
  6286. EXPECT_TRUE(success);
  6287. delete i;
  6288. });
  6289. })
  6290. .Get("/streamed-chunked-with-trailer",
  6291. [&](const Request & /*req*/, Response &res) {
  6292. auto i = new int(0);
  6293. res.set_header("Trailer", "Dummy1, Dummy2");
  6294. res.set_chunked_content_provider(
  6295. "text/plain",
  6296. [i](size_t /*offset*/, DataSink &sink) {
  6297. switch (*i) {
  6298. case 0: sink.os << "123"; break;
  6299. case 1: sink.os << "456"; break;
  6300. case 2: sink.os << "789"; break;
  6301. case 3: {
  6302. sink.done_with_trailer(
  6303. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6304. } break;
  6305. }
  6306. (*i)++;
  6307. return true;
  6308. },
  6309. [i](bool success) {
  6310. EXPECT_TRUE(success);
  6311. delete i;
  6312. });
  6313. })
  6314. .Get("/streamed",
  6315. [&](const Request & /*req*/, Response &res) {
  6316. res.set_content_provider(
  6317. 6, "text/plain",
  6318. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6319. sink.os << (offset < 3 ? "a" : "b");
  6320. return true;
  6321. });
  6322. })
  6323. .Get("/streamed-without-length",
  6324. [&](const Request & /*req*/, Response &res) {
  6325. auto data = new std::string("abcdefg");
  6326. res.set_content_provider(
  6327. "text/plain",
  6328. [data](size_t offset, DataSink &sink) {
  6329. if (offset < data->size()) {
  6330. sink.os << data->substr(offset);
  6331. }
  6332. sink.done();
  6333. return true;
  6334. },
  6335. [data](bool success) {
  6336. EXPECT_TRUE(success);
  6337. delete data;
  6338. });
  6339. })
  6340. .Get("/streamed-with-range",
  6341. [&](const Request &req, Response &res) {
  6342. auto data = new std::string("abcdefg");
  6343. // An explicit status keeps the server from picking the 206 it
  6344. // would otherwise choose for a ranged request, so the response
  6345. // is not a partial representation.
  6346. auto status = req.get_param_value("status");
  6347. if (status == "200") {
  6348. res.status = StatusCode::OK_200;
  6349. } else if (status == "403") {
  6350. res.status = StatusCode::Forbidden_403;
  6351. }
  6352. res.set_content_provider(
  6353. data->size(), "text/plain",
  6354. [data](size_t offset, size_t length, DataSink &sink) {
  6355. size_t DATA_CHUNK_SIZE = 4;
  6356. const auto &d = *data;
  6357. auto out_len =
  6358. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6359. auto ret =
  6360. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6361. EXPECT_TRUE(ret);
  6362. return true;
  6363. },
  6364. [data, &req](bool success) {
  6365. EXPECT_EQ(success, !req.has_param("error"));
  6366. delete data;
  6367. });
  6368. })
  6369. .Get("/streamed-cancel",
  6370. [&](const Request & /*req*/, Response &res) {
  6371. res.set_content_provider(
  6372. size_t(-1), "text/plain",
  6373. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6374. sink.os << "data_chunk";
  6375. return true;
  6376. });
  6377. })
  6378. .Get("/regex-with-delimiter",
  6379. [&](const Request &req, Response & /*res*/) {
  6380. ASSERT_TRUE(req.has_param("key"));
  6381. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6382. })
  6383. .Get("/with-range",
  6384. [&](const Request & /*req*/, Response &res) {
  6385. res.set_content("abcdefg", "text/plain");
  6386. })
  6387. .Get("/test-start-time",
  6388. [&](const Request &req, Response & /*res*/) {
  6389. EXPECT_NE(req.start_time_,
  6390. std::chrono::steady_clock::time_point::min());
  6391. })
  6392. .Get("/with-range-customized-response",
  6393. [&](const Request & /*req*/, Response &res) {
  6394. res.status = StatusCode::BadRequest_400;
  6395. res.set_content(JSON_DATA, "application/json");
  6396. })
  6397. .Post("/chunked",
  6398. [&](const Request &req, Response & /*res*/) {
  6399. EXPECT_EQ(req.body, "dechunked post body");
  6400. })
  6401. .Post("/large-chunked",
  6402. [&](const Request &req, Response & /*res*/) {
  6403. std::string expected(6 * 30 * 1024u, 'a');
  6404. EXPECT_EQ(req.body, expected);
  6405. })
  6406. .Post("/multipart",
  6407. [&](const Request &req, Response & /*res*/) {
  6408. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6409. req.form.get_field_count("text2") +
  6410. req.form.get_field_count("file3") +
  6411. req.form.get_field_count("file4"));
  6412. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6413. req.form.get_file_count("file2"));
  6414. ASSERT_TRUE(!req.form.has_file("???"));
  6415. ASSERT_TRUE(!req.form.has_field("???"));
  6416. ASSERT_TRUE(req.body.empty());
  6417. {
  6418. const auto &text = req.form.get_field("text1");
  6419. EXPECT_EQ("text default", text);
  6420. }
  6421. {
  6422. const auto &text = req.form.get_field("text2");
  6423. EXPECT_EQ("aωb", text);
  6424. }
  6425. {
  6426. const auto &file = req.form.get_file("file1");
  6427. EXPECT_EQ("hello.txt", file.filename);
  6428. EXPECT_EQ("text/plain", file.content_type);
  6429. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6430. }
  6431. {
  6432. const auto &file = req.form.get_file("file2");
  6433. EXPECT_EQ("world.json", file.filename);
  6434. EXPECT_EQ("application/json", file.content_type);
  6435. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6436. }
  6437. {
  6438. const auto &text = req.form.get_field("file3");
  6439. EXPECT_EQ(0u, text.size());
  6440. }
  6441. {
  6442. const auto &text = req.form.get_field("file4");
  6443. EXPECT_EQ(0u, text.size());
  6444. }
  6445. })
  6446. .Post("/multipart/multi_file_values",
  6447. [&](const Request &req, Response & /*res*/) {
  6448. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6449. req.form.get_field_count("multi_text1"));
  6450. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6451. ASSERT_TRUE(!req.form.has_file("???"));
  6452. ASSERT_TRUE(!req.form.has_field("???"));
  6453. ASSERT_TRUE(req.body.empty());
  6454. {
  6455. const auto &text = req.form.get_field("text");
  6456. EXPECT_EQ("default text", text);
  6457. }
  6458. {
  6459. const auto &text1_values = req.form.get_fields("multi_text1");
  6460. EXPECT_EQ(2u, text1_values.size());
  6461. EXPECT_EQ("aaaaa", text1_values[0]);
  6462. EXPECT_EQ("bbbbb", text1_values[1]);
  6463. }
  6464. {
  6465. const auto &file1_values = req.form.get_files("multi_file1");
  6466. EXPECT_EQ(2u, file1_values.size());
  6467. auto file1 = file1_values[0];
  6468. EXPECT_EQ(file1.filename, "hello.txt");
  6469. EXPECT_EQ(file1.content_type, "text/plain");
  6470. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6471. auto file2 = file1_values[1];
  6472. EXPECT_EQ(file2.filename, "world.json");
  6473. EXPECT_EQ(file2.content_type, "application/json");
  6474. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6475. }
  6476. })
  6477. .Post("/empty",
  6478. [&](const Request &req, Response &res) {
  6479. EXPECT_EQ(req.body, "");
  6480. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6481. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6482. res.set_content("empty", "text/plain");
  6483. })
  6484. .Post("/empty-no-content-type",
  6485. [&](const Request &req, Response &res) {
  6486. EXPECT_EQ(req.body, "");
  6487. EXPECT_FALSE(req.has_header("Content-Type"));
  6488. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6489. res.set_content("empty-no-content-type", "text/plain");
  6490. })
  6491. .Post("/path-only",
  6492. [&](const Request &req, Response &res) {
  6493. EXPECT_EQ(req.body, "");
  6494. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6495. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6496. res.set_content("path-only", "text/plain");
  6497. })
  6498. .Post("/path-headers-only",
  6499. [&](const Request &req, Response &res) {
  6500. EXPECT_EQ(req.body, "");
  6501. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6502. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6503. EXPECT_EQ("world", req.get_header_value("hello"));
  6504. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6505. res.set_content("path-headers-only", "text/plain");
  6506. })
  6507. .Post("/post-large",
  6508. [&](const Request &req, Response &res) {
  6509. EXPECT_EQ(req.body, LARGE_DATA);
  6510. res.set_content(req.body, "text/plain");
  6511. })
  6512. .Post("/post-loopback",
  6513. [&](const Request &, Response &res,
  6514. ContentReader const &content_reader) {
  6515. std::string body;
  6516. content_reader([&](const char *data, size_t data_length) {
  6517. body.append(data, data_length);
  6518. return true;
  6519. });
  6520. res.set_content(body, "text/plain");
  6521. })
  6522. .Put("/put-loopback",
  6523. [&](const Request &, Response &res,
  6524. ContentReader const &content_reader) {
  6525. std::string body;
  6526. content_reader([&](const char *data, size_t data_length) {
  6527. body.append(data, data_length);
  6528. return true;
  6529. });
  6530. res.set_content(body, "text/plain");
  6531. })
  6532. .Patch("/patch-loopback",
  6533. [&](const Request &, Response &res,
  6534. ContentReader const &content_reader) {
  6535. std::string body;
  6536. content_reader([&](const char *data, size_t data_length) {
  6537. body.append(data, data_length);
  6538. return true;
  6539. });
  6540. res.set_content(body, "text/plain");
  6541. })
  6542. .Put("/empty-no-content-type",
  6543. [&](const Request &req, Response &res) {
  6544. EXPECT_EQ(req.body, "");
  6545. EXPECT_FALSE(req.has_header("Content-Type"));
  6546. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6547. res.set_content("empty-no-content-type", "text/plain");
  6548. })
  6549. .Put("/put",
  6550. [&](const Request &req, Response &res) {
  6551. EXPECT_EQ(req.body, "PUT");
  6552. res.set_content(req.body, "text/plain");
  6553. })
  6554. .Put("/put-large",
  6555. [&](const Request &req, Response &res) {
  6556. EXPECT_EQ(req.body, LARGE_DATA);
  6557. res.set_content(req.body, "text/plain");
  6558. })
  6559. .Patch("/patch",
  6560. [&](const Request &req, Response &res) {
  6561. EXPECT_EQ(req.body, "PATCH");
  6562. res.set_content(req.body, "text/plain");
  6563. })
  6564. .Delete("/delete",
  6565. [&](const Request & /*req*/, Response &res) {
  6566. res.set_content("DELETE", "text/plain");
  6567. })
  6568. .Delete("/delete-body",
  6569. [&](const Request &req, Response &res) {
  6570. EXPECT_EQ(req.body, "content");
  6571. res.set_content(req.body, "text/plain");
  6572. })
  6573. .Options(R"(\*)",
  6574. [&](const Request & /*req*/, Response &res) {
  6575. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6576. })
  6577. .CustomRoute("PROPFIND", "/dav/:id",
  6578. [&](const Request &req, Response &res) {
  6579. res.set_header("x-body-size",
  6580. std::to_string(req.body.size()));
  6581. res.set_header("x-matched-route", req.matched_route);
  6582. res.set_header("x-dav-id", req.path_params.at("id"));
  6583. res.status = StatusCode::MultiStatus_207;
  6584. res.set_content(req.body, "application/xml");
  6585. })
  6586. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6587. [&](const Request &req, Response &res) {
  6588. res.set_header("x-dav-match", req.matches[1]);
  6589. res.status = StatusCode::MultiStatus_207;
  6590. })
  6591. .CustomRoute("MKCOL", "/dav-mkcol",
  6592. [&](const Request &req, Response &res) {
  6593. EXPECT_TRUE(req.body.empty());
  6594. res.status = StatusCode::Created_201;
  6595. })
  6596. .CustomRoute(
  6597. "REPORT", "/dav-report",
  6598. [&](const Request & /*req*/, Response &res,
  6599. const ContentReader &content_reader) {
  6600. std::string body;
  6601. content_reader([&](const char *data, size_t data_length) {
  6602. body.append(data, data_length);
  6603. return true;
  6604. });
  6605. res.set_header("x-body-size", std::to_string(body.size()));
  6606. res.status = StatusCode::MultiStatus_207;
  6607. res.set_content(body, "application/xml");
  6608. })
  6609. .Get("/request-target",
  6610. [&](const Request &req, Response & /*res*/) {
  6611. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6612. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6613. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6614. })
  6615. .Get("/long-query-value",
  6616. [&](const Request &req, Response & /*res*/) {
  6617. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6618. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6619. })
  6620. .Get("/too-long-query-value",
  6621. [&](const Request &req, Response & /*res*/) {
  6622. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6623. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6624. })
  6625. .Get("/array-param",
  6626. [&](const Request &req, Response & /*res*/) {
  6627. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6628. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6629. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6630. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6631. })
  6632. .Get("/array-param-values",
  6633. [&](const Request &req, Response & /*res*/) {
  6634. auto values = req.get_param_values("array");
  6635. EXPECT_EQ(3u, values.size());
  6636. EXPECT_EQ("value1", values[0]);
  6637. EXPECT_EQ("value2", values[1]);
  6638. EXPECT_EQ("value3", values[2]);
  6639. auto empty = req.get_param_values("nonexistent");
  6640. EXPECT_TRUE(empty.empty());
  6641. })
  6642. .Post("/validate-no-multiple-headers",
  6643. [&](const Request &req, Response & /*res*/) {
  6644. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6645. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6646. })
  6647. .Post("/content_receiver",
  6648. [&](const Request &req, Response &res,
  6649. const ContentReader &content_reader) {
  6650. if (req.is_multipart_form_data()) {
  6651. std::vector<FormData> items;
  6652. content_reader(
  6653. [&](const FormData &file) {
  6654. items.push_back(file);
  6655. return true;
  6656. },
  6657. [&](const char *data, size_t data_length) {
  6658. items.back().content.append(data, data_length);
  6659. return true;
  6660. });
  6661. EXPECT_EQ(5u, items.size());
  6662. {
  6663. const auto &file = get_file_value(items, "text1");
  6664. EXPECT_TRUE(file.filename.empty());
  6665. EXPECT_EQ("text default", file.content);
  6666. }
  6667. {
  6668. const auto &file = get_file_value(items, "text2");
  6669. EXPECT_TRUE(file.filename.empty());
  6670. EXPECT_EQ("aωb", file.content);
  6671. }
  6672. {
  6673. const auto &file = get_file_value(items, "file1");
  6674. EXPECT_EQ("hello.txt", file.filename);
  6675. EXPECT_EQ("text/plain", file.content_type);
  6676. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6677. }
  6678. {
  6679. const auto &file = get_file_value(items, "file2");
  6680. EXPECT_EQ("world.json", file.filename);
  6681. EXPECT_EQ("application/json", file.content_type);
  6682. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6683. }
  6684. {
  6685. const auto &file = get_file_value(items, "file3");
  6686. EXPECT_TRUE(file.filename.empty());
  6687. EXPECT_EQ("application/octet-stream", file.content_type);
  6688. EXPECT_EQ(0u, file.content.size());
  6689. }
  6690. } else {
  6691. std::string body;
  6692. content_reader([&](const char *data, size_t data_length) {
  6693. EXPECT_EQ(7U, data_length);
  6694. body.append(data, data_length);
  6695. return true;
  6696. });
  6697. EXPECT_EQ(body, "content");
  6698. res.set_content(body, "text/plain");
  6699. }
  6700. })
  6701. .Put("/content_receiver",
  6702. [&](const Request & /*req*/, Response &res,
  6703. const ContentReader &content_reader) {
  6704. std::string body;
  6705. content_reader([&](const char *data, size_t data_length) {
  6706. body.append(data, data_length);
  6707. return true;
  6708. });
  6709. EXPECT_EQ(body, "content");
  6710. res.set_content(body, "text/plain");
  6711. })
  6712. .Patch("/content_receiver",
  6713. [&](const Request & /*req*/, Response &res,
  6714. const ContentReader &content_reader) {
  6715. std::string body;
  6716. content_reader([&](const char *data, size_t data_length) {
  6717. body.append(data, data_length);
  6718. return true;
  6719. });
  6720. EXPECT_EQ(body, "content");
  6721. res.set_content(body, "text/plain");
  6722. })
  6723. .Post("/query-string-and-body",
  6724. [&](const Request &req, Response & /*res*/) {
  6725. ASSERT_TRUE(req.has_param("key"));
  6726. EXPECT_EQ(req.get_param_value("key"), "value");
  6727. EXPECT_EQ(req.body, "content");
  6728. })
  6729. .Get("/last-request",
  6730. [&](const Request &req, Response & /*res*/) {
  6731. EXPECT_EQ("close", req.get_header_value("Connection"));
  6732. })
  6733. .Get(R"(/redirect/(\d+))",
  6734. [&](const Request &req, Response &res) {
  6735. auto num = std::stoi(req.matches[1]) + 1;
  6736. std::string url = "/redirect/" + std::to_string(num);
  6737. res.set_redirect(url);
  6738. })
  6739. .Post("/binary",
  6740. [&](const Request &req, Response &res) {
  6741. EXPECT_EQ(4U, req.body.size());
  6742. EXPECT_EQ("application/octet-stream",
  6743. req.get_header_value("Content-Type"));
  6744. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6745. res.set_content(req.body, "application/octet-stream");
  6746. })
  6747. .Put("/binary",
  6748. [&](const Request &req, Response &res) {
  6749. EXPECT_EQ(4U, req.body.size());
  6750. EXPECT_EQ("application/octet-stream",
  6751. req.get_header_value("Content-Type"));
  6752. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6753. res.set_content(req.body, "application/octet-stream");
  6754. })
  6755. .Patch("/binary",
  6756. [&](const Request &req, Response &res) {
  6757. EXPECT_EQ(4U, req.body.size());
  6758. EXPECT_EQ("application/octet-stream",
  6759. req.get_header_value("Content-Type"));
  6760. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6761. res.set_content(req.body, "application/octet-stream");
  6762. })
  6763. .Delete("/binary",
  6764. [&](const Request &req, Response &res) {
  6765. EXPECT_EQ(4U, req.body.size());
  6766. EXPECT_EQ("application/octet-stream",
  6767. req.get_header_value("Content-Type"));
  6768. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6769. res.set_content(req.body, "application/octet-stream");
  6770. })
  6771. .Get("/issue1772",
  6772. [&](const Request & /*req*/, Response &res) {
  6773. res.status = 401;
  6774. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6775. })
  6776. .Delete("/issue609",
  6777. [](const httplib::Request &, httplib::Response &res,
  6778. const httplib::ContentReader &) {
  6779. res.set_content("ok", "text/plain");
  6780. })
  6781. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6782. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6783. .Get("/compress",
  6784. [&](const Request & /*req*/, Response &res) {
  6785. res.set_content(
  6786. "12345678901234567890123456789012345678901234567890123456789"
  6787. "01234567890123456789012345678901234567890",
  6788. "text/plain");
  6789. })
  6790. .Get("/compress-with-charset",
  6791. [&](const Request & /*req*/, Response &res) {
  6792. res.set_content(
  6793. "12345678901234567890123456789012345678901234567890123456789"
  6794. "01234567890123456789012345678901234567890",
  6795. "application/json; charset=utf-8");
  6796. })
  6797. .Get("/nocompress",
  6798. [&](const Request & /*req*/, Response &res) {
  6799. res.set_content(
  6800. "12345678901234567890123456789012345678901234567890123456789"
  6801. "01234567890123456789012345678901234567890",
  6802. "application/octet-stream");
  6803. })
  6804. .Post("/compress-multipart",
  6805. [&](const Request &req, Response & /*res*/) {
  6806. EXPECT_EQ(2u, req.form.fields.size());
  6807. ASSERT_TRUE(!req.form.has_field("???"));
  6808. {
  6809. const auto &text = req.form.get_field("key1");
  6810. EXPECT_EQ("test", text);
  6811. }
  6812. {
  6813. const auto &text = req.form.get_field("key2");
  6814. EXPECT_EQ("--abcdefg123", text);
  6815. }
  6816. })
  6817. #endif
  6818. ;
  6819. persons_["john"] = "programmer";
  6820. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6821. svr_.wait_until_ready();
  6822. }
  6823. virtual void TearDown() {
  6824. svr_.stop();
  6825. if (!request_threads_.empty()) {
  6826. std::this_thread::sleep_for(std::chrono::seconds(1));
  6827. for (auto &t : request_threads_) {
  6828. t.join();
  6829. }
  6830. }
  6831. t_.join();
  6832. }
  6833. map<string, string> persons_;
  6834. #ifdef CPPHTTPLIB_SSL_ENABLED
  6835. SSLClient cli_;
  6836. SSLServer svr_;
  6837. #else
  6838. Client cli_;
  6839. Server svr_;
  6840. #endif
  6841. thread t_;
  6842. std::vector<thread> request_threads_;
  6843. };
  6844. TEST_F(ServerTest, GetMethod200) {
  6845. auto res = cli_.Get("/hi");
  6846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6847. EXPECT_EQ("HTTP/1.1", res->version);
  6848. EXPECT_EQ(StatusCode::OK_200, res->status);
  6849. EXPECT_EQ("OK", res->reason);
  6850. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6851. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6852. EXPECT_EQ("Hello World!", res->body);
  6853. }
  6854. TEST_F(ServerTest, GetEmptyFile) {
  6855. auto res = cli_.Get("/empty_file");
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. EXPECT_EQ(StatusCode::OK_200, res->status);
  6858. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6859. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6860. EXPECT_EQ("", res->body);
  6861. }
  6862. TEST_F(ServerTest, GetFileContent) {
  6863. auto res = cli_.Get("/file_content");
  6864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6865. EXPECT_EQ(StatusCode::OK_200, res->status);
  6866. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6867. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6868. EXPECT_EQ("test.html", res->body);
  6869. }
  6870. TEST_F(ServerTest, GetFileContentWithRange) {
  6871. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6873. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6874. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6875. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6876. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6877. EXPECT_EQ("est", res->body);
  6878. }
  6879. TEST_F(ServerTest, GetFileContentWithContentType) {
  6880. auto res = cli_.Get("/file_content_with_content_type");
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. EXPECT_EQ(StatusCode::OK_200, res->status);
  6883. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6884. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6885. EXPECT_EQ("file\n", res->body);
  6886. }
  6887. TEST_F(ServerTest, GetInvalidFileContent) {
  6888. auto res = cli_.Get("/invalid_file_content");
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6891. }
  6892. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6893. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6895. EXPECT_EQ("HTTP/1.1", res->version);
  6896. EXPECT_EQ(StatusCode::OK_200, res->status);
  6897. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6898. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6899. EXPECT_EQ("Hello World!", res->body);
  6900. }
  6901. TEST_F(ServerTest, GetMethod302) {
  6902. auto res = cli_.Get("/");
  6903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6904. EXPECT_EQ(StatusCode::Found_302, res->status);
  6905. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6906. }
  6907. TEST_F(ServerTest, GetMethod302Redirect) {
  6908. cli_.set_follow_location(true);
  6909. auto res = cli_.Get("/");
  6910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6911. EXPECT_EQ(StatusCode::OK_200, res->status);
  6912. EXPECT_EQ("Hello World!", res->body);
  6913. EXPECT_EQ("/hi", res->location);
  6914. }
  6915. TEST_F(ServerTest, GetMethod404) {
  6916. auto res = cli_.Get("/invalid");
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6919. }
  6920. TEST_F(ServerTest, HeadMethod200) {
  6921. auto res = cli_.Head("/hi");
  6922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6923. EXPECT_EQ(StatusCode::OK_200, res->status);
  6924. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6925. EXPECT_TRUE(res->body.empty());
  6926. }
  6927. TEST_F(ServerTest, HeadMethod200Static) {
  6928. auto res = cli_.Head("/mount/dir/index.html");
  6929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6930. EXPECT_EQ(StatusCode::OK_200, res->status);
  6931. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6932. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6933. EXPECT_TRUE(res->body.empty());
  6934. }
  6935. TEST_F(ServerTest, HeadMethod404) {
  6936. auto res = cli_.Head("/invalid");
  6937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6938. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6939. EXPECT_TRUE(res->body.empty());
  6940. }
  6941. TEST_F(ServerTest, GetMethodPersonJohn) {
  6942. auto res = cli_.Get("/person/john");
  6943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6944. EXPECT_EQ(StatusCode::OK_200, res->status);
  6945. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6946. EXPECT_EQ("programmer", res->body);
  6947. }
  6948. TEST_F(ServerTest, PostMethod1) {
  6949. auto res = cli_.Get("/person/john1");
  6950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6951. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6952. res = cli_.Post("/person", "name=john1&note=coder",
  6953. "application/x-www-form-urlencoded");
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. ASSERT_EQ(StatusCode::OK_200, res->status);
  6956. res = cli_.Get("/person/john1");
  6957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6958. ASSERT_EQ(StatusCode::OK_200, res->status);
  6959. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6960. ASSERT_EQ("coder", res->body);
  6961. }
  6962. TEST_F(ServerTest, PostMethod2) {
  6963. auto res = cli_.Get("/person/john2");
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6966. Params params;
  6967. params.emplace("name", "john2");
  6968. params.emplace("note", "coder");
  6969. res = cli_.Post("/person", params);
  6970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6971. ASSERT_EQ(StatusCode::OK_200, res->status);
  6972. res = cli_.Get("/person/john2");
  6973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6974. ASSERT_EQ(StatusCode::OK_200, res->status);
  6975. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6976. ASSERT_EQ("coder", res->body);
  6977. }
  6978. TEST_F(ServerTest, PutMethod3) {
  6979. auto res = cli_.Get("/person/john3");
  6980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6981. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6982. Params params;
  6983. params.emplace("name", "john3");
  6984. params.emplace("note", "coder");
  6985. res = cli_.Put("/person", params);
  6986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6987. ASSERT_EQ(StatusCode::OK_200, res->status);
  6988. res = cli_.Get("/person/john3");
  6989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6990. ASSERT_EQ(StatusCode::OK_200, res->status);
  6991. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6992. ASSERT_EQ("coder", res->body);
  6993. }
  6994. TEST_F(ServerTest, DeleteMethod1) {
  6995. auto res = cli_.Get("/person/john4");
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6998. Params params;
  6999. params.emplace("name", "john4");
  7000. params.emplace("note", "coder");
  7001. res = cli_.Post("/person", params);
  7002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7003. ASSERT_EQ(StatusCode::OK_200, res->status);
  7004. res = cli_.Get("/person/john4");
  7005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7006. ASSERT_EQ(StatusCode::OK_200, res->status);
  7007. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  7008. ASSERT_EQ("coder", res->body);
  7009. Params delete_params;
  7010. delete_params.emplace("name", "john4");
  7011. res = cli_.Delete("/person", delete_params);
  7012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7013. ASSERT_EQ(StatusCode::OK_200, res->status);
  7014. ASSERT_EQ("DELETED", res->body);
  7015. res = cli_.Get("/person/john4");
  7016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7017. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  7018. }
  7019. TEST_F(ServerTest, DeleteMethod2) {
  7020. auto res = cli_.Get("/person/john5");
  7021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7022. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  7023. Params params;
  7024. params.emplace("name", "john5");
  7025. params.emplace("note", "developer");
  7026. res = cli_.Post("/person", params);
  7027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7028. ASSERT_EQ(StatusCode::OK_200, res->status);
  7029. res = cli_.Get("/person/john5");
  7030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7031. ASSERT_EQ(StatusCode::OK_200, res->status);
  7032. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  7033. ASSERT_EQ("developer", res->body);
  7034. Params delete_params;
  7035. delete_params.emplace("name", "john5");
  7036. Headers headers;
  7037. headers.emplace("Custom-Header", "test-value");
  7038. res = cli_.Delete("/person", headers, delete_params);
  7039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7040. ASSERT_EQ(StatusCode::OK_200, res->status);
  7041. ASSERT_EQ("DELETED", res->body);
  7042. res = cli_.Get("/person/john5");
  7043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7044. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  7045. }
  7046. TEST_F(ServerTest, DeleteMethod3) {
  7047. auto res = cli_.Get("/person/john6");
  7048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7049. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  7050. Params params;
  7051. params.emplace("name", "john6");
  7052. params.emplace("note", "tester");
  7053. res = cli_.Post("/person", params);
  7054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7055. ASSERT_EQ(StatusCode::OK_200, res->status);
  7056. res = cli_.Get("/person/john6");
  7057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7058. ASSERT_EQ(StatusCode::OK_200, res->status);
  7059. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  7060. ASSERT_EQ("tester", res->body);
  7061. Params delete_params;
  7062. delete_params.emplace("name", "john6");
  7063. Headers headers;
  7064. headers.emplace("Custom-Header", "test-value");
  7065. res = cli_.Delete("/person", headers, delete_params, nullptr);
  7066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7067. ASSERT_EQ(StatusCode::OK_200, res->status);
  7068. ASSERT_EQ("DELETED", res->body);
  7069. res = cli_.Get("/person/john6");
  7070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7071. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  7072. }
  7073. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  7074. Params params;
  7075. params.emplace("json", JSON_DATA);
  7076. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  7077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7078. ASSERT_EQ(StatusCode::OK_200, res->status);
  7079. ASSERT_EQ(JSON_DATA, res->body);
  7080. }
  7081. TEST_F(ServerTest, PostEmptyContent) {
  7082. auto res = cli_.Post("/empty", "", "text/plain");
  7083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7084. ASSERT_EQ(StatusCode::OK_200, res->status);
  7085. ASSERT_EQ("empty", res->body);
  7086. }
  7087. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  7088. auto res = cli_.Post("/empty-no-content-type");
  7089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7090. ASSERT_EQ(StatusCode::OK_200, res->status);
  7091. ASSERT_EQ("empty-no-content-type", res->body);
  7092. }
  7093. TEST_F(ServerTest, PostPathOnly) {
  7094. auto res = cli_.Post("/path-only");
  7095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7096. ASSERT_EQ(StatusCode::OK_200, res->status);
  7097. ASSERT_EQ("path-only", res->body);
  7098. }
  7099. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  7100. auto res = cli_.Post("/path-headers-only",
  7101. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  7102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7103. ASSERT_EQ(StatusCode::OK_200, res->status);
  7104. ASSERT_EQ("path-headers-only", res->body);
  7105. }
  7106. TEST_F(ServerTest, PostLarge) {
  7107. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  7108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7109. ASSERT_EQ(StatusCode::OK_200, res->status);
  7110. EXPECT_EQ(LARGE_DATA, res->body);
  7111. }
  7112. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  7113. auto res = cli_.Put("/empty-no-content-type");
  7114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7115. ASSERT_EQ(StatusCode::OK_200, res->status);
  7116. ASSERT_EQ("empty-no-content-type", res->body);
  7117. }
  7118. TEST_F(ServerTest, GetMethodDir) {
  7119. auto res = cli_.Get("/dir/");
  7120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7121. EXPECT_EQ(StatusCode::OK_200, res->status);
  7122. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7123. auto body = R"(<html>
  7124. <head>
  7125. </head>
  7126. <body>
  7127. <a href="/dir/test.html">Test</a>
  7128. <a href="/hi">hi</a>
  7129. </body>
  7130. </html>
  7131. )";
  7132. EXPECT_EQ(body, res->body);
  7133. }
  7134. TEST_F(ServerTest, GetMethodDirTest) {
  7135. auto res = cli_.Get("/dir/test.html");
  7136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7137. EXPECT_EQ(StatusCode::OK_200, res->status);
  7138. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7139. EXPECT_EQ("test.html", res->body);
  7140. }
  7141. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  7142. auto res = cli_.Get("/dir/../dir/test.html");
  7143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7144. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7145. }
  7146. TEST_F(ServerTest, GetMethodInvalidPath) {
  7147. auto res = cli_.Get("/dir/../test.html");
  7148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7149. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7150. }
  7151. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  7152. auto res = cli_.Get("/../www/dir/test.html");
  7153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7154. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7155. }
  7156. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  7157. auto res = cli_.Get("/dir/../../www/dir/test.html");
  7158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7159. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7160. }
  7161. TEST_F(ServerTest, GetMethodDirMountTest) {
  7162. auto res = cli_.Get("/mount/dir/test.html");
  7163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7164. EXPECT_EQ(StatusCode::OK_200, res->status);
  7165. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7166. EXPECT_EQ("test.html", res->body);
  7167. }
  7168. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  7169. auto res = cli_.Get("/mount/dir/../dir/test.html");
  7170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7171. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7172. }
  7173. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  7174. auto res = cli_.Get("/mount/dir/../test.html");
  7175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7176. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7177. }
  7178. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  7179. auto res = cli_.Get("/mount/dir/test.html%00.js");
  7180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7181. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7182. }
  7183. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  7184. auto res = cli_.Get("/mount/../www2/dir/test.html");
  7185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7186. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7187. }
  7188. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  7189. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  7190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7191. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7192. }
  7193. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  7194. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7197. }
  7198. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  7199. auto res = cli_.Get("/mount/dir");
  7200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7201. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7202. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  7203. }
  7204. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  7205. auto res = cli_.Get("//dir");
  7206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7207. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7208. EXPECT_FALSE(res->has_header("Location"));
  7209. }
  7210. TEST_F(ServerTest, PostMethod303) {
  7211. auto res = cli_.Post("/1", "body", "text/plain");
  7212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7213. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  7214. EXPECT_EQ("/2", res->get_header_value("Location"));
  7215. }
  7216. TEST_F(ServerTest, PostMethod303Redirect) {
  7217. cli_.set_follow_location(true);
  7218. auto res = cli_.Post("/1", "body", "text/plain");
  7219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7220. EXPECT_EQ(StatusCode::OK_200, res->status);
  7221. EXPECT_EQ("redirected.", res->body);
  7222. EXPECT_EQ("/2", res->location);
  7223. }
  7224. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  7225. auto res = cli_.Get("/dir/test.abcde");
  7226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7227. EXPECT_EQ(StatusCode::OK_200, res->status);
  7228. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7229. EXPECT_EQ("abcde", res->body);
  7230. }
  7231. TEST_F(ServerTest, StaticFileRange) {
  7232. auto res =
  7233. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7236. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7237. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7238. EXPECT_EQ(true, res->has_header("Content-Range"));
  7239. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7240. EXPECT_EQ(std::string("cd"), res->body);
  7241. }
  7242. TEST_F(ServerTest, StaticFileRanges) {
  7243. auto res = cli_.Get("/dir/test.abcde",
  7244. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  7245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7246. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7247. EXPECT_TRUE(
  7248. res->get_header_value("Content-Type")
  7249. .find(
  7250. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  7251. 0);
  7252. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  7253. }
  7254. TEST_F(ServerTest, StaticFileRangeHead) {
  7255. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  7256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7257. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7258. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7259. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7260. EXPECT_EQ(true, res->has_header("Content-Range"));
  7261. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7262. }
  7263. TEST_F(ServerTest, StaticFileRangeBigFile) {
  7264. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7266. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7267. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7268. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7269. EXPECT_EQ(true, res->has_header("Content-Range"));
  7270. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7271. res->get_header_value("Content-Range"));
  7272. EXPECT_EQ("LAST\n", res->body);
  7273. }
  7274. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7275. auto res =
  7276. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  7277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7278. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7279. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7280. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  7281. EXPECT_EQ(true, res->has_header("Content-Range"));
  7282. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7283. }
  7284. TEST_F(ServerTest, StaticFileBigFile) {
  7285. auto res = cli_.Get("/dir/1MB.txt");
  7286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7287. EXPECT_EQ(StatusCode::OK_200, res->status);
  7288. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7289. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7290. }
  7291. TEST_F(ServerTest, InvalidBaseDirMount) {
  7292. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7293. }
  7294. TEST_F(ServerTest, Binary) {
  7295. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7296. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7297. "application/octet-stream");
  7298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7299. ASSERT_EQ(StatusCode::OK_200, res->status);
  7300. ASSERT_EQ(4U, res->body.size());
  7301. res = cli_.Put("/binary", binary.data(), binary.size(),
  7302. "application/octet-stream");
  7303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7304. ASSERT_EQ(StatusCode::OK_200, res->status);
  7305. ASSERT_EQ(4U, res->body.size());
  7306. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7307. "application/octet-stream");
  7308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7309. ASSERT_EQ(StatusCode::OK_200, res->status);
  7310. ASSERT_EQ(4U, res->body.size());
  7311. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7312. "application/octet-stream");
  7313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7314. ASSERT_EQ(StatusCode::OK_200, res->status);
  7315. ASSERT_EQ(4U, res->body.size());
  7316. }
  7317. TEST_F(ServerTest, BinaryString) {
  7318. auto binary = std::string("\x00\x01\x02\x03", 4);
  7319. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  7320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7321. ASSERT_EQ(StatusCode::OK_200, res->status);
  7322. ASSERT_EQ(4U, res->body.size());
  7323. res = cli_.Put("/binary", binary, "application/octet-stream");
  7324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7325. ASSERT_EQ(StatusCode::OK_200, res->status);
  7326. ASSERT_EQ(4U, res->body.size());
  7327. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7329. ASSERT_EQ(StatusCode::OK_200, res->status);
  7330. ASSERT_EQ(4U, res->body.size());
  7331. res = cli_.Delete("/binary", binary, "application/octet-stream");
  7332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7333. ASSERT_EQ(StatusCode::OK_200, res->status);
  7334. ASSERT_EQ(4U, res->body.size());
  7335. }
  7336. TEST_F(ServerTest, EmptyRequest) {
  7337. auto res = cli_.Get("");
  7338. ASSERT_TRUE(!res);
  7339. EXPECT_EQ(Error::Connection, res.error());
  7340. }
  7341. TEST_F(ServerTest, LongRequest) {
  7342. std::string request;
  7343. for (size_t i = 0; i < 545; i++) {
  7344. request += "/TooLongRequest";
  7345. }
  7346. request += "OK";
  7347. auto res = cli_.Get(request.c_str());
  7348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7349. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7350. }
  7351. TEST_F(ServerTest, TooLongRequest) {
  7352. std::string request;
  7353. for (size_t i = 0; i < 546; i++) {
  7354. request += "/TooLongRequest";
  7355. }
  7356. request += "_NG";
  7357. auto start = std::chrono::high_resolution_clock::now();
  7358. cli_.set_keep_alive(true);
  7359. auto res = cli_.Get(request.c_str());
  7360. auto end = std::chrono::high_resolution_clock::now();
  7361. auto elapsed =
  7362. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7363. .count();
  7364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7365. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7366. EXPECT_LE(elapsed, 1000);
  7367. EXPECT_EQ("close", res->get_header_value("Connection"));
  7368. EXPECT_FALSE(cli_.is_socket_open());
  7369. }
  7370. TEST_F(ServerTest, AlmostTooLongRequest) {
  7371. // test for #2046 - URI length check shouldn't include other content on req
  7372. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7373. // leading /, space, HTTP/1.1)
  7374. std::string request =
  7375. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7376. auto res = cli_.Get(request.c_str());
  7377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7378. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7379. }
  7380. TEST_F(ServerTest, LongHeader) {
  7381. Request req;
  7382. req.method = "GET";
  7383. req.path = "/hi";
  7384. std::string host_and_port;
  7385. host_and_port += HOST;
  7386. host_and_port += ":";
  7387. host_and_port += std::to_string(PORT);
  7388. req.headers.emplace("Host", host_and_port.c_str());
  7389. req.headers.emplace("Accept", "*/*");
  7390. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7391. req.headers.emplace(
  7392. "Header-Name",
  7393. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7394. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7395. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7396. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7397. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7398. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7399. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7400. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7401. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7402. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7403. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7404. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7405. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7406. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7407. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7408. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7409. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7410. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7411. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7412. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7413. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7414. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7415. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7416. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7417. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7418. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7419. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7420. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7421. "@@@@@@@@@@@@@@@@");
  7422. auto res = std::make_shared<Response>();
  7423. auto error = Error::Success;
  7424. auto ret = cli_.send(req, *res, error);
  7425. ASSERT_TRUE(ret);
  7426. EXPECT_EQ(StatusCode::OK_200, res->status);
  7427. }
  7428. TEST_F(ServerTest, LongQueryValue) {
  7429. auto start = std::chrono::high_resolution_clock::now();
  7430. cli_.set_keep_alive(true);
  7431. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7432. auto end = std::chrono::high_resolution_clock::now();
  7433. auto elapsed =
  7434. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7435. .count();
  7436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7437. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7438. EXPECT_LE(elapsed, 1000);
  7439. EXPECT_EQ("close", res->get_header_value("Connection"));
  7440. EXPECT_FALSE(cli_.is_socket_open());
  7441. }
  7442. TEST_F(ServerTest, TooLongQueryValue) {
  7443. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7444. ASSERT_FALSE(res);
  7445. EXPECT_EQ(Error::Read, res.error());
  7446. }
  7447. TEST_F(ServerTest, TooLongHeader) {
  7448. Request req;
  7449. req.method = "GET";
  7450. req.path = "/hi";
  7451. std::string host_and_port;
  7452. host_and_port += HOST;
  7453. host_and_port += ":";
  7454. host_and_port += std::to_string(PORT);
  7455. req.headers.emplace("Host", host_and_port.c_str());
  7456. req.headers.emplace("Accept", "*/*");
  7457. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7458. req.headers.emplace(
  7459. "Header-Name",
  7460. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7461. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7462. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7463. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7464. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7465. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7466. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7467. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7468. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7469. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7470. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7471. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7472. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7473. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7474. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7475. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7476. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7477. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7478. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7479. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7480. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7481. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7482. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7483. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7484. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7485. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7486. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7487. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7488. "@@@@@@@@@@@@@@@@@");
  7489. auto res = std::make_shared<Response>();
  7490. auto error = Error::Success;
  7491. auto ret = cli_.send(req, *res, error);
  7492. ASSERT_TRUE(ret);
  7493. EXPECT_EQ(StatusCode::OK_200, res->status);
  7494. }
  7495. TEST_F(ServerTest, HeaderCountAtLimit) {
  7496. // Test with headers just under the 100 limit
  7497. httplib::Headers headers;
  7498. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7499. // This should keep us just under the 100 header limit
  7500. for (int i = 0; i < 95; i++) {
  7501. std::string name = "X-Test-Header-" + std::to_string(i);
  7502. std::string value = "value" + std::to_string(i);
  7503. headers.emplace(name, value);
  7504. }
  7505. // This should work fine as we're under the limit
  7506. auto res = cli_.Get("/hi", headers);
  7507. EXPECT_TRUE(res);
  7508. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7509. }
  7510. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7511. // Test with many headers to exceed the 100 limit
  7512. httplib::Headers headers;
  7513. // Add 150 headers to definitely exceed the 100 limit
  7514. for (int i = 0; i < 150; i++) {
  7515. std::string name = "X-Test-Header-" + std::to_string(i);
  7516. std::string value = "value" + std::to_string(i);
  7517. headers.emplace(name, value);
  7518. }
  7519. // This should fail due to exceeding header count limit
  7520. cli_.set_keep_alive(true);
  7521. auto res = cli_.Get("/hi", headers);
  7522. // The server should respond with 400 Bad Request
  7523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7524. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7525. EXPECT_EQ("close", res->get_header_value("Connection"));
  7526. EXPECT_FALSE(cli_.is_socket_open());
  7527. }
  7528. TEST_F(ServerTest, PercentEncoding) {
  7529. auto res = cli_.Get("/e%6edwith%");
  7530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7531. EXPECT_EQ(StatusCode::OK_200, res->status);
  7532. }
  7533. TEST_F(ServerTest, PercentEncodingUnicode) {
  7534. auto res = cli_.Get("/e%u006edwith%");
  7535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7536. EXPECT_EQ(StatusCode::OK_200, res->status);
  7537. }
  7538. TEST_F(ServerTest, InvalidPercentEncoding) {
  7539. auto res = cli_.Get("/%endwith%");
  7540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7541. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7542. }
  7543. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7544. auto res = cli_.Get("/%uendwith%");
  7545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7546. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7547. }
  7548. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7549. auto res = cli_.Get("/hello?aaa=bbb%");
  7550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7551. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7552. }
  7553. TEST_F(ServerTest, PlusSignEncoding) {
  7554. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7556. EXPECT_EQ(StatusCode::OK_200, res->status);
  7557. EXPECT_EQ("a +b", res->body);
  7558. }
  7559. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7560. // This test simulates a potential DoS attack using many headers
  7561. // to verify our security fix prevents memory exhaustion
  7562. httplib::Headers attack_headers;
  7563. // Attempt to add many headers like an attacker would (200 headers to far
  7564. // exceed limit)
  7565. for (int i = 0; i < 200; i++) {
  7566. std::string name = "X-Attack-Header-" + std::to_string(i);
  7567. std::string value = "attack_payload_" + std::to_string(i);
  7568. attack_headers.emplace(name, value);
  7569. }
  7570. // Try to POST with excessive headers
  7571. cli_.set_keep_alive(true);
  7572. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7573. // Should either fail or return 400 Bad Request due to security limit
  7574. if (res) {
  7575. // If we get a response, it should be 400 Bad Request
  7576. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7577. EXPECT_EQ("close", res->get_header_value("Connection"));
  7578. }
  7579. EXPECT_FALSE(cli_.is_socket_open());
  7580. }
  7581. TEST_F(ServerTest, MultipartFormData) {
  7582. UploadFormDataItems items = {
  7583. {"text1", "text default", "", ""},
  7584. {"text2", "aωb", "", ""},
  7585. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7586. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7587. {"file3", "", "", "application/octet-stream"},
  7588. {"file4", "", "", " application/json tmp-string "}};
  7589. auto res = cli_.Post("/multipart", items);
  7590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7591. EXPECT_EQ(StatusCode::OK_200, res->status);
  7592. }
  7593. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7594. UploadFormDataItems items = {
  7595. {"text", "default text", "", ""},
  7596. {"multi_text1", "aaaaa", "", ""},
  7597. {"multi_text1", "bbbbb", "", ""},
  7598. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7599. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7600. "application/json"},
  7601. };
  7602. auto res = cli_.Post("/multipart/multi_file_values", items);
  7603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7604. EXPECT_EQ(StatusCode::OK_200, res->status);
  7605. }
  7606. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7607. auto res = cli_.Get("/hi");
  7608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7609. EXPECT_EQ(StatusCode::OK_200, res->status);
  7610. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7611. EXPECT_EQ("Hello World!", res->body);
  7612. }
  7613. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7614. Request req;
  7615. req.method = "POST";
  7616. req.path = "/chunked";
  7617. std::string host_and_port;
  7618. host_and_port += HOST;
  7619. host_and_port += ":";
  7620. host_and_port += std::to_string(PORT);
  7621. req.headers.emplace("Host", host_and_port.c_str());
  7622. req.headers.emplace("Accept", "*/*");
  7623. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7624. req.headers.emplace("Content-Type", "text/plain");
  7625. req.headers.emplace("Content-Length", "0");
  7626. req.headers.emplace(
  7627. "Transfer-Encoding",
  7628. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7629. // Client does not chunk, so make a chunked body manually.
  7630. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7631. auto res = std::make_shared<Response>();
  7632. auto error = Error::Success;
  7633. auto ret = cli_.send(req, *res, error);
  7634. ASSERT_TRUE(ret);
  7635. EXPECT_EQ(StatusCode::OK_200, res->status);
  7636. }
  7637. template <typename ClientT>
  7638. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7639. int expected_status) {
  7640. Request req;
  7641. req.method = "POST";
  7642. req.path = "/chunked";
  7643. std::string host_and_port;
  7644. host_and_port += HOST;
  7645. host_and_port += ":";
  7646. host_and_port += std::to_string(PORT);
  7647. req.headers.emplace("Host", host_and_port.c_str());
  7648. req.headers.emplace("Content-Length", "0");
  7649. req.headers.emplace("Transfer-Encoding", "chunked");
  7650. req.body = body;
  7651. auto res = std::make_shared<Response>();
  7652. auto error = Error::Success;
  7653. ASSERT_TRUE(cli.send(req, *res, error));
  7654. EXPECT_EQ(expected_status, res->status);
  7655. }
  7656. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7657. // rather than treat them as valid lengths.
  7658. template <typename ClientT>
  7659. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7660. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7661. }
  7662. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7663. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7664. }
  7665. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7666. expect_chunked_body_rejected(
  7667. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7668. }
  7669. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7670. // chunk-size line carries no CR, LF or other control character ahead of its
  7671. // terminator. Such a line must be refused rather than read as extension text.
  7672. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7673. expect_chunked_body_rejected(
  7674. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7675. }
  7676. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7677. expect_chunked_body_rejected(
  7678. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7679. }
  7680. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7681. expect_chunked_body_rejected(
  7682. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7683. }
  7684. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7685. // The literal stays split: a hex escape consumes every hex digit that
  7686. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7687. expect_chunked_body_rejected(
  7688. cli_, "4;a\x01"
  7689. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7690. }
  7691. // The bytes around chunk data are no payload, so they cannot ride on the
  7692. // payload limit
  7693. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7694. // Small enough that the whole request is sent before the server turns it
  7695. // down, yet past the limit by the last chunks
  7696. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7697. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7698. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7699. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7700. SCOPED_TRACE(size_line.substr(0, 2));
  7701. std::string body;
  7702. for (auto c : std::string("dechunked post body")) {
  7703. body += size_line + "\r\n" + c + "\r\n";
  7704. }
  7705. body += "0\r\n\r\n";
  7706. expect_chunked_body_rejected(cli_, body.c_str());
  7707. }
  7708. }
  7709. TEST_F(ServerTest, AcceptsChunkExtension) {
  7710. expect_chunked_body_status(cli_,
  7711. "4;name=value\r\ndech\r\n"
  7712. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7713. "0;last\r\n\r\n",
  7714. StatusCode::OK_200);
  7715. }
  7716. TEST_F(ServerTest, GetStreamed2) {
  7717. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7720. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7721. EXPECT_EQ(true, res->has_header("Content-Range"));
  7722. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7723. EXPECT_EQ(std::string("ab"), res->body);
  7724. }
  7725. TEST_F(ServerTest, GetStreamed) {
  7726. auto res = cli_.Get("/streamed");
  7727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7728. EXPECT_EQ(StatusCode::OK_200, res->status);
  7729. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7730. EXPECT_EQ(std::string("aaabbb"), res->body);
  7731. }
  7732. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7733. auto res = cli_.Get("/streamed-without-length",
  7734. Headers{make_range_header({{0, -1}})});
  7735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7736. EXPECT_EQ(StatusCode::OK_200, res->status);
  7737. EXPECT_EQ(false, res->has_header("Content-Length"));
  7738. EXPECT_EQ(false, res->has_header("Content-Range"));
  7739. EXPECT_EQ(std::string("abcdefg"), res->body);
  7740. }
  7741. TEST_F(ServerTest, GetStreamedWithRange1) {
  7742. auto res =
  7743. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7745. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7746. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7747. EXPECT_EQ(true, res->has_header("Content-Range"));
  7748. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7749. EXPECT_EQ(std::string("def"), res->body);
  7750. }
  7751. TEST_F(ServerTest, GetStreamedWithRange2) {
  7752. auto res =
  7753. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7755. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7756. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7757. EXPECT_EQ(true, res->has_header("Content-Range"));
  7758. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7759. EXPECT_EQ(std::string("bcdefg"), res->body);
  7760. }
  7761. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7762. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7764. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7765. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7766. EXPECT_EQ(true, res->has_header("Content-Range"));
  7767. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7768. EXPECT_EQ(std::string("efg"), res->body);
  7769. }
  7770. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7771. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7772. // the entire representation.
  7773. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7774. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7776. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7777. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7778. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7779. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7780. }
  7781. }
  7782. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7783. auto res =
  7784. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7786. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7787. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7788. EXPECT_EQ(false, res->has_header("Content-Range"));
  7789. EXPECT_EQ(0U, res->body.size());
  7790. }
  7791. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7792. // Only a 206 is served as a partial representation. Under any other status
  7793. // `apply_ranges()` reported the full content length, so the body must match
  7794. // that header, and the content provider must never be asked for an offset
  7795. // outside the representation.
  7796. auto check = [&](int status, const char *range) {
  7797. auto path =
  7798. std::string("/streamed-with-range?status=") + std::to_string(status);
  7799. auto ctx = path + " Range: " + range;
  7800. auto res = cli_.Get(path, Headers{{"Range", range}});
  7801. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7802. EXPECT_EQ(status, res->status) << ctx;
  7803. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7804. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7805. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7806. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7807. };
  7808. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7809. check(403, "bytes=3-5");
  7810. // The offset is far past the representation.
  7811. check(403, "bytes=100000-100200");
  7812. // `first_pos` is still -1 here, and the bounds asserts in
  7813. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7814. check(403, "bytes=-3");
  7815. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7816. // multipart branch would have written one that is empty.
  7817. check(403, "bytes=1-2, 4-5");
  7818. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7819. // covers the whole representation.
  7820. check(200, "bytes=3-5");
  7821. check(200, "bytes=1-2, 4-5");
  7822. }
  7823. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7824. auto res =
  7825. cli_.Get("/streamed-with-range",
  7826. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7827. "92233720368547758079223372036854775807"}});
  7828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7829. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7830. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7831. EXPECT_EQ(false, res->has_header("Content-Range"));
  7832. EXPECT_EQ(0U, res->body.size());
  7833. }
  7834. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7835. auto res = cli_.Get(
  7836. "/with-range",
  7837. Headers{{"Range",
  7838. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7839. {"Accept-Encoding", ""}});
  7840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7841. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7842. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7843. EXPECT_EQ(true, res->has_header("Content-Range"));
  7844. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7845. EXPECT_EQ(std::string("abcdefg"), res->body);
  7846. }
  7847. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7848. auto res = cli_.Get("/with-range", Headers{
  7849. {"Range", "bytes=0-"},
  7850. {"Accept-Encoding", ""},
  7851. });
  7852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7853. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7854. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7855. EXPECT_EQ(true, res->has_header("Content-Range"));
  7856. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7857. EXPECT_EQ(std::string("abcdefg"), res->body);
  7858. }
  7859. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7860. auto res = cli_.Get("/streamed-with-range",
  7861. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7863. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7864. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7865. EXPECT_EQ(false, res->has_header("Content-Range"));
  7866. EXPECT_EQ(267U, res->body.size());
  7867. // Check that both range contents are present
  7868. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7869. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7870. // Check that Content-Range headers are present for both ranges
  7871. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7872. std::string::npos);
  7873. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7874. std::string::npos);
  7875. }
  7876. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7877. Ranges ranges;
  7878. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7879. ranges.emplace_back(0, -1);
  7880. }
  7881. auto res = cli_.Get("/streamed-with-range?error",
  7882. Headers{{make_range_header(ranges)}});
  7883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7884. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7885. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7886. EXPECT_EQ(false, res->has_header("Content-Range"));
  7887. EXPECT_EQ(0U, res->body.size());
  7888. }
  7889. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7890. auto res = cli_.Get("/streamed-with-range",
  7891. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7893. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7894. EXPECT_EQ(5U, res->body.size());
  7895. // Check that overlapping ranges are coalesced into a single range
  7896. EXPECT_EQ("bcdef", res->body);
  7897. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7898. // Should be single range, not multipart
  7899. EXPECT_TRUE(res->has_header("Content-Range"));
  7900. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7901. }
  7902. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7903. auto res = cli_.Get("/streamed-with-range",
  7904. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7906. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7907. EXPECT_EQ(268U, res->body.size());
  7908. // Check that both range contents are present
  7909. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7910. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7911. // Check that Content-Range headers are present for both ranges
  7912. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7913. std::string::npos);
  7914. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7915. std::string::npos);
  7916. }
  7917. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7918. auto res = cli_.Get("/streamed-with-range",
  7919. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7921. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7922. EXPECT_EQ(269U, res->body.size());
  7923. // Check that both duplicate range contents are present
  7924. size_t first_abc = res->body.find("abc\r\n");
  7925. EXPECT_TRUE(first_abc != std::string::npos);
  7926. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7927. EXPECT_TRUE(second_abc != std::string::npos);
  7928. // Check that Content-Range headers are present for both ranges
  7929. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7930. EXPECT_TRUE(first_range != std::string::npos);
  7931. size_t second_range =
  7932. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7933. EXPECT_TRUE(second_range != std::string::npos);
  7934. }
  7935. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7936. auto res =
  7937. cli_.Get("/streamed-with-range?error",
  7938. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7940. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7941. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7942. EXPECT_EQ(false, res->has_header("Content-Range"));
  7943. EXPECT_EQ(0U, res->body.size());
  7944. }
  7945. TEST_F(ServerTest, GetStreamedEndless) {
  7946. uint64_t offset = 0;
  7947. auto res = cli_.Get("/streamed-cancel",
  7948. [&](const char * /*data*/, uint64_t data_length) {
  7949. if (offset < 100) {
  7950. offset += data_length;
  7951. return true;
  7952. }
  7953. return false;
  7954. });
  7955. ASSERT_TRUE(!res);
  7956. EXPECT_EQ(Error::Canceled, res.error());
  7957. }
  7958. TEST_F(ServerTest, ClientStop) {
  7959. std::atomic_size_t count{4};
  7960. std::vector<std::thread> threads;
  7961. for (auto i = count.load(); i != 0; --i) {
  7962. threads.emplace_back([&]() {
  7963. auto res = cli_.Get("/streamed-cancel",
  7964. [&](const char *, uint64_t) { return true; });
  7965. --count;
  7966. ASSERT_TRUE(!res);
  7967. EXPECT_TRUE(res.error() == Error::Canceled ||
  7968. res.error() == Error::Read || res.error() == Error::Write);
  7969. });
  7970. }
  7971. std::this_thread::sleep_for(std::chrono::seconds(2));
  7972. while (count != 0) {
  7973. cli_.stop();
  7974. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7975. }
  7976. for (auto &t : threads) {
  7977. t.join();
  7978. }
  7979. }
  7980. TEST_F(ServerTest, GetWithRange1) {
  7981. auto res = cli_.Get("/with-range", Headers{
  7982. make_range_header({{3, 5}}),
  7983. {"Accept-Encoding", ""},
  7984. });
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7987. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7988. EXPECT_EQ(true, res->has_header("Content-Range"));
  7989. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7990. EXPECT_EQ(std::string("def"), res->body);
  7991. }
  7992. TEST_F(ServerTest, GetWithRange2) {
  7993. auto res = cli_.Get("/with-range", Headers{
  7994. make_range_header({{1, -1}}),
  7995. {"Accept-Encoding", ""},
  7996. });
  7997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7998. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7999. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8000. EXPECT_EQ(true, res->has_header("Content-Range"));
  8001. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  8002. EXPECT_EQ(std::string("bcdefg"), res->body);
  8003. }
  8004. TEST_F(ServerTest, GetWithRange3) {
  8005. auto res = cli_.Get("/with-range", Headers{
  8006. make_range_header({{0, 0}}),
  8007. {"Accept-Encoding", ""},
  8008. });
  8009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8010. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8011. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  8012. EXPECT_EQ(true, res->has_header("Content-Range"));
  8013. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  8014. EXPECT_EQ(std::string("a"), res->body);
  8015. }
  8016. TEST_F(ServerTest, GetWithRange4) {
  8017. auto res = cli_.Get("/with-range", Headers{
  8018. make_range_header({{-1, 2}}),
  8019. {"Accept-Encoding", ""},
  8020. });
  8021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8022. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8023. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8024. EXPECT_EQ(true, res->has_header("Content-Range"));
  8025. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  8026. EXPECT_EQ(std::string("fg"), res->body);
  8027. }
  8028. TEST_F(ServerTest, GetWithRange5) {
  8029. auto res = cli_.Get("/with-range", Headers{
  8030. make_range_header({{0, 5}}),
  8031. {"Accept-Encoding", ""},
  8032. });
  8033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8034. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8035. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8036. EXPECT_EQ(true, res->has_header("Content-Range"));
  8037. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  8038. EXPECT_EQ(std::string("abcdef"), res->body);
  8039. }
  8040. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8041. TEST_F(ServerTest, GetWithRangeAcceptEncoding) {
  8042. cli_.set_decompress(false);
  8043. auto res = cli_.Get("/with-range", Headers{{"Range", "bytes=1-3"},
  8044. {"Accept-Encoding", "gzip"}});
  8045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8046. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8047. EXPECT_EQ("bytes 1-3/7", res->get_header_value("Content-Range"));
  8048. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  8049. EXPECT_EQ("bcd", res->body);
  8050. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8051. }
  8052. #endif
  8053. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  8054. auto res =
  8055. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  8056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8057. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  8058. }
  8059. TEST_F(ServerTest, GetWithRangeMultipart) {
  8060. auto res =
  8061. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  8062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8063. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8064. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  8065. EXPECT_EQ(false, res->has_header("Content-Range"));
  8066. EXPECT_EQ(267U, res->body.size());
  8067. }
  8068. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  8069. // RFC 9110 14.1.1: the set is satisfiable when any of its ranges is, and the
  8070. // unsatisfiable ones are left out of the response.
  8071. auto res = cli_.Get("/with-range",
  8072. Headers{make_range_header({{-1, 2}, {10000, 30000}}),
  8073. {"Accept-Encoding", ""}});
  8074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8075. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8076. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8077. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  8078. EXPECT_EQ(std::string("fg"), res->body);
  8079. }
  8080. TEST_F(ServerTest, GetWithRangeMultipartSkipsUnsatisfiableRange) {
  8081. auto res =
  8082. cli_.Get("/with-range",
  8083. Headers{{make_range_header({{1, 2}, {10000, 30000}, {4, 5}})}});
  8084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8085. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8086. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  8087. EXPECT_EQ(false, res->has_header("Content-Range"));
  8088. EXPECT_EQ(267U, res->body.size());
  8089. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  8090. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  8091. }
  8092. TEST_F(ServerTest, GetWithRangeMultipartNoneSatisfiable) {
  8093. for (auto range : {"bytes=7-, -0", "bytes=10000-30000, 7-8"}) {
  8094. auto res = cli_.Get("/with-range", Headers{{"Range", range}});
  8095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8096. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status) << range;
  8097. }
  8098. }
  8099. TEST_F(ServerTest, GetStreamedWithRangeSkipsUnsatisfiableRange) {
  8100. auto res =
  8101. cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=7-, 2-3"}});
  8102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8103. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8104. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8105. EXPECT_EQ("bytes 2-3/7", res->get_header_value("Content-Range"));
  8106. EXPECT_EQ(std::string("cd"), res->body);
  8107. }
  8108. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  8109. auto res = cli_.Get("/with-range-customized-response",
  8110. Headers{{make_range_header({{1, 2}})}});
  8111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8112. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8113. EXPECT_EQ(true, res->has_header("Content-Length"));
  8114. EXPECT_EQ(false, res->has_header("Content-Range"));
  8115. EXPECT_EQ(JSON_DATA, res->body);
  8116. }
  8117. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  8118. auto res = cli_.Get("/with-range-customized-response",
  8119. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  8120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8121. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8122. EXPECT_EQ(true, res->has_header("Content-Length"));
  8123. EXPECT_EQ(false, res->has_header("Content-Range"));
  8124. EXPECT_EQ(JSON_DATA, res->body);
  8125. }
  8126. TEST_F(ServerTest, Issue1772) {
  8127. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  8128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8129. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  8130. }
  8131. TEST_F(ServerTest, Issue609) {
  8132. auto res = cli_.Delete("/issue609");
  8133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8134. EXPECT_EQ(StatusCode::OK_200, res->status);
  8135. EXPECT_EQ(std::string("ok"), res->body);
  8136. }
  8137. TEST_F(ServerTest, GetStreamedChunked) {
  8138. auto res = cli_.Get("/streamed-chunked");
  8139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8140. EXPECT_EQ(StatusCode::OK_200, res->status);
  8141. EXPECT_EQ(std::string("123456789"), res->body);
  8142. }
  8143. TEST_F(ServerTest, GetStreamedChunked2) {
  8144. auto res = cli_.Get("/streamed-chunked2");
  8145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8146. EXPECT_EQ(StatusCode::OK_200, res->status);
  8147. EXPECT_EQ(std::string("123456789"), res->body);
  8148. }
  8149. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  8150. auto res = cli_.Get("/streamed-chunked-with-trailer");
  8151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8152. EXPECT_EQ(StatusCode::OK_200, res->status);
  8153. EXPECT_EQ(std::string("123456789"), res->body);
  8154. EXPECT_TRUE(res->has_header("Trailer"));
  8155. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  8156. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  8157. // Trailers are now stored separately from headers (security fix)
  8158. EXPECT_EQ(2U, res->trailers.size());
  8159. EXPECT_TRUE(res->has_trailer("Dummy1"));
  8160. EXPECT_TRUE(res->has_trailer("Dummy2"));
  8161. EXPECT_FALSE(res->has_trailer("Dummy3"));
  8162. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  8163. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  8164. // Verify trailers are NOT in headers (security verification)
  8165. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  8166. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  8167. }
  8168. TEST_F(ServerTest, LargeChunkedPost) {
  8169. Request req;
  8170. req.method = "POST";
  8171. req.path = "/large-chunked";
  8172. std::string host_and_port;
  8173. host_and_port += HOST;
  8174. host_and_port += ":";
  8175. host_and_port += std::to_string(PORT);
  8176. req.headers.emplace("Host", host_and_port.c_str());
  8177. req.headers.emplace("Accept", "*/*");
  8178. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  8179. req.headers.emplace("Content-Type", "text/plain");
  8180. req.headers.emplace("Content-Length", "0");
  8181. req.headers.emplace("Transfer-Encoding", "chunked");
  8182. std::string long_string(30 * 1024u, 'a');
  8183. std::string chunk = "7800\r\n" + long_string + "\r\n";
  8184. // Attempt to make a large enough post to exceed OS buffers, to test that
  8185. // the server handles short reads if the full chunk data isn't available.
  8186. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  8187. auto res = std::make_shared<Response>();
  8188. auto error = Error::Success;
  8189. auto ret = cli_.send(req, *res, error);
  8190. ASSERT_TRUE(ret);
  8191. EXPECT_EQ(StatusCode::OK_200, res->status);
  8192. }
  8193. TEST_F(ServerTest, GetMethodRemoteAddr) {
  8194. auto res = cli_.Get("/remote_addr");
  8195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8196. EXPECT_EQ(StatusCode::OK_200, res->status);
  8197. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8198. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  8199. }
  8200. TEST_F(ServerTest, GetMethodLocalAddr) {
  8201. auto res = cli_.Get("/local_addr");
  8202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8203. EXPECT_EQ(StatusCode::OK_200, res->status);
  8204. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8205. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  8206. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  8207. }
  8208. TEST_F(ServerTest, HTTPResponseSplitting) {
  8209. auto res = cli_.Get("/http_response_splitting");
  8210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8211. EXPECT_EQ(StatusCode::OK_200, res->status);
  8212. }
  8213. TEST_F(ServerTest, SlowRequest) {
  8214. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8215. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8216. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8217. }
  8218. #if 0
  8219. TEST_F(ServerTest, SlowPost) {
  8220. char buffer[64 * 1024];
  8221. memset(buffer, 0x42, sizeof(buffer));
  8222. auto res = cli_.Post(
  8223. "/slowpost", 64 * 1024 * 1024,
  8224. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8225. auto ret = sink.write(buffer, sizeof(buffer));
  8226. EXPECT_TRUE(ret);
  8227. return true;
  8228. },
  8229. "text/plain");
  8230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8231. EXPECT_EQ(StatusCode::OK_200, res->status);
  8232. }
  8233. TEST_F(ServerTest, SlowPostFail) {
  8234. char buffer[64 * 1024];
  8235. memset(buffer, 0x42, sizeof(buffer));
  8236. cli_.set_write_timeout(std::chrono::seconds(0));
  8237. auto res = cli_.Post(
  8238. "/slowpost", 64 * 1024 * 1024,
  8239. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8240. sink.write(buffer, sizeof(buffer));
  8241. return true;
  8242. },
  8243. "text/plain");
  8244. ASSERT_TRUE(!res);
  8245. EXPECT_EQ(Error::Write, res.error());
  8246. }
  8247. #endif
  8248. TEST_F(ServerTest, Put) {
  8249. auto res = cli_.Put("/put", "PUT", "text/plain");
  8250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8251. EXPECT_EQ(StatusCode::OK_200, res->status);
  8252. EXPECT_EQ("PUT", res->body);
  8253. }
  8254. TEST_F(ServerTest, PutWithContentProvider) {
  8255. auto res = cli_.Put(
  8256. "/put", 3,
  8257. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8258. sink.os << "PUT";
  8259. return true;
  8260. },
  8261. "text/plain");
  8262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8263. EXPECT_EQ(StatusCode::OK_200, res->status);
  8264. EXPECT_EQ("PUT", res->body);
  8265. }
  8266. TEST_F(ServerTest, PostWithContentProviderAbort) {
  8267. auto res = cli_.Post(
  8268. "/post", 42,
  8269. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8270. return false;
  8271. },
  8272. "text/plain");
  8273. ASSERT_TRUE(!res);
  8274. EXPECT_EQ(Error::Canceled, res.error());
  8275. }
  8276. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  8277. auto res = cli_.Put(
  8278. "/put",
  8279. [](size_t /*offset*/, DataSink &sink) {
  8280. sink.os << "PUT";
  8281. sink.done();
  8282. return true;
  8283. },
  8284. "text/plain");
  8285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8286. EXPECT_EQ(StatusCode::OK_200, res->status);
  8287. EXPECT_EQ("PUT", res->body);
  8288. }
  8289. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  8290. auto res = cli_.Post(
  8291. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8292. "text/plain");
  8293. ASSERT_TRUE(!res);
  8294. EXPECT_EQ(Error::Canceled, res.error());
  8295. }
  8296. TEST_F(ServerTest, PostLoopBack) {
  8297. std::string body;
  8298. auto res = cli_.Post(
  8299. "/post-loopback", 9,
  8300. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8301. EXPECT_EQ(9u, length);
  8302. sink.write("123", 3);
  8303. sink.write("456", 3);
  8304. sink.write("789", 3);
  8305. return true;
  8306. },
  8307. "text/plain",
  8308. [&body](const char *data, size_t data_length) {
  8309. body.append(data, data_length);
  8310. return true;
  8311. });
  8312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8313. EXPECT_EQ(StatusCode::OK_200, res->status);
  8314. EXPECT_EQ("123456789", body);
  8315. }
  8316. TEST_F(ServerTest, PutLoopBack) {
  8317. std::string body;
  8318. auto res = cli_.Put(
  8319. "/put-loopback", 9,
  8320. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8321. EXPECT_EQ(9u, length);
  8322. sink.write("123", 3);
  8323. sink.write("456", 3);
  8324. sink.write("789", 3);
  8325. return true;
  8326. },
  8327. "text/plain",
  8328. [&body](const char *data, size_t data_length) {
  8329. body.append(data, data_length);
  8330. return true;
  8331. });
  8332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8333. EXPECT_EQ(StatusCode::OK_200, res->status);
  8334. EXPECT_EQ("123456789", body);
  8335. }
  8336. TEST_F(ServerTest, PatchLoopBack) {
  8337. std::string body;
  8338. auto res = cli_.Patch(
  8339. "/patch-loopback", 9,
  8340. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8341. EXPECT_EQ(9u, length);
  8342. sink.write("123", 3);
  8343. sink.write("456", 3);
  8344. sink.write("789", 3);
  8345. return true;
  8346. },
  8347. "text/plain",
  8348. [&body](const char *data, size_t data_length) {
  8349. body.append(data, data_length);
  8350. return true;
  8351. });
  8352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8353. EXPECT_EQ(StatusCode::OK_200, res->status);
  8354. EXPECT_EQ("123456789", body);
  8355. }
  8356. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  8357. std::string body;
  8358. auto res = cli_.Post(
  8359. "/post-loopback",
  8360. [](size_t /*offset*/, DataSink &sink) {
  8361. sink.write("123", 3);
  8362. sink.write("456", 3);
  8363. sink.write("789", 3);
  8364. sink.done();
  8365. return true;
  8366. },
  8367. "text/plain",
  8368. [&body](const char *data, size_t data_length) {
  8369. body.append(data, data_length);
  8370. return true;
  8371. });
  8372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8373. EXPECT_EQ(StatusCode::OK_200, res->status);
  8374. EXPECT_EQ("123456789", body);
  8375. }
  8376. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8377. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8378. cli_.set_compress(true);
  8379. auto res = cli_.Put(
  8380. "/put", 3,
  8381. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8382. sink.os << "PUT";
  8383. return true;
  8384. },
  8385. "text/plain");
  8386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8387. EXPECT_EQ(StatusCode::OK_200, res->status);
  8388. EXPECT_EQ("PUT", res->body);
  8389. }
  8390. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8391. cli_.set_compress(true);
  8392. auto res = cli_.Post(
  8393. "/post", 42,
  8394. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8395. return false;
  8396. },
  8397. "text/plain");
  8398. ASSERT_TRUE(!res);
  8399. EXPECT_EQ(Error::Canceled, res.error());
  8400. }
  8401. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8402. cli_.set_compress(true);
  8403. auto res = cli_.Put(
  8404. "/put",
  8405. [](size_t /*offset*/, DataSink &sink) {
  8406. sink.os << "PUT";
  8407. sink.done();
  8408. return true;
  8409. },
  8410. "text/plain");
  8411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8412. EXPECT_EQ(StatusCode::OK_200, res->status);
  8413. EXPECT_EQ("PUT", res->body);
  8414. }
  8415. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8416. cli_.set_compress(true);
  8417. auto res = cli_.Post(
  8418. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8419. "text/plain");
  8420. ASSERT_TRUE(!res);
  8421. EXPECT_EQ(Error::Canceled, res.error());
  8422. }
  8423. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8424. cli_.set_compress(true);
  8425. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8427. EXPECT_EQ(StatusCode::OK_200, res->status);
  8428. EXPECT_EQ(LARGE_DATA, res->body);
  8429. }
  8430. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8431. #ifdef CPPHTTPLIB_SSL_ENABLED
  8432. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8433. Client cli(s.c_str());
  8434. cli.enable_server_certificate_verification(false);
  8435. #else
  8436. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8437. Client cli(s.c_str());
  8438. #endif
  8439. cli.set_compress(true);
  8440. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8442. EXPECT_EQ(StatusCode::OK_200, res->status);
  8443. EXPECT_EQ(LARGE_DATA, res->body);
  8444. // The compressed size should be less than a 10th of the original. May vary
  8445. // depending on the zlib library.
  8446. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8447. static_cast<uint64_t>(10 * 1024 * 1024));
  8448. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8449. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8450. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8451. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8452. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8453. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8454. #endif
  8455. }
  8456. TEST_F(ServerTest, PutContentWithDeflate) {
  8457. cli_.set_compress(false);
  8458. Headers headers;
  8459. headers.emplace("Content-Encoding", "deflate");
  8460. // PUT in deflate format:
  8461. auto res = cli_.Put("/put", headers,
  8462. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8464. EXPECT_EQ(StatusCode::OK_200, res->status);
  8465. EXPECT_EQ("PUT", res->body);
  8466. }
  8467. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8468. Headers headers;
  8469. headers.emplace("Accept-Encoding", "gzip, deflate");
  8470. auto res = cli_.Get("/streamed-chunked", headers);
  8471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8472. EXPECT_EQ(StatusCode::OK_200, res->status);
  8473. EXPECT_EQ(std::string("123456789"), res->body);
  8474. }
  8475. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  8476. Headers headers;
  8477. headers.emplace("Accept-Encoding", "gzip, deflate");
  8478. auto res = cli_.Get("/streamed-chunked2", headers);
  8479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8480. EXPECT_EQ(StatusCode::OK_200, res->status);
  8481. EXPECT_EQ(std::string("123456789"), res->body);
  8482. }
  8483. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8484. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8486. EXPECT_EQ(StatusCode::OK_200, res->status);
  8487. }
  8488. TEST(GzipDecompressor, ChunkedDecompression) {
  8489. std::string data;
  8490. for (size_t i = 0; i < 32 * 1024; ++i) {
  8491. data.push_back(static_cast<char>('a' + i % 26));
  8492. }
  8493. std::string compressed_data;
  8494. {
  8495. httplib::detail::gzip_compressor compressor;
  8496. bool result = compressor.compress(
  8497. data.data(), data.size(),
  8498. /*last=*/true,
  8499. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8500. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8501. compressed_data_size);
  8502. return true;
  8503. });
  8504. ASSERT_TRUE(result);
  8505. }
  8506. std::string decompressed_data;
  8507. {
  8508. httplib::detail::gzip_decompressor decompressor;
  8509. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8510. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8511. size_t chunk_size = 130;
  8512. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8513. chunk_begin += chunk_size) {
  8514. size_t current_chunk_size =
  8515. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8516. bool result = decompressor.decompress(
  8517. compressed_data.data() + chunk_begin, current_chunk_size,
  8518. [&](const char *decompressed_data_chunk,
  8519. size_t decompressed_data_chunk_size) {
  8520. decompressed_data.insert(decompressed_data.size(),
  8521. decompressed_data_chunk,
  8522. decompressed_data_chunk_size);
  8523. return true;
  8524. });
  8525. ASSERT_TRUE(result);
  8526. }
  8527. }
  8528. ASSERT_EQ(data, decompressed_data);
  8529. }
  8530. TEST(GzipDecompressor, DeflateDecompression) {
  8531. std::string original_text = "Raw deflate without gzip";
  8532. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8533. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8534. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8535. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8536. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8537. std::string decompressed_data;
  8538. {
  8539. httplib::detail::gzip_decompressor decompressor;
  8540. bool result = decompressor.decompress(
  8541. compressed_data.data(), compressed_data.size(),
  8542. [&](const char *decompressed_data_chunk,
  8543. size_t decompressed_data_chunk_size) {
  8544. decompressed_data.insert(decompressed_data.size(),
  8545. decompressed_data_chunk,
  8546. decompressed_data_chunk_size);
  8547. return true;
  8548. });
  8549. ASSERT_TRUE(result);
  8550. }
  8551. ASSERT_EQ(original_text, decompressed_data);
  8552. }
  8553. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8554. std::string original_text = "Raw deflate without gzip";
  8555. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8556. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8557. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8558. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8559. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8560. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8561. std::string decompressed_data;
  8562. {
  8563. httplib::detail::gzip_decompressor decompressor;
  8564. bool result = decompressor.decompress(
  8565. compressed_data.data(), compressed_data.size(),
  8566. [&](const char *decompressed_data_chunk,
  8567. size_t decompressed_data_chunk_size) {
  8568. decompressed_data.insert(decompressed_data.size(),
  8569. decompressed_data_chunk,
  8570. decompressed_data_chunk_size);
  8571. return true;
  8572. });
  8573. ASSERT_TRUE(result);
  8574. }
  8575. ASSERT_EQ(original_text, decompressed_data);
  8576. }
  8577. TEST(GzipDecompressor, MultipleMembers) {
  8578. auto gzip = [](const std::string &data) {
  8579. std::string out;
  8580. httplib::detail::gzip_compressor compressor;
  8581. compressor.compress(data.data(), data.size(), /*last=*/true,
  8582. [&](const char *chunk, size_t n) {
  8583. out.append(chunk, n);
  8584. return true;
  8585. });
  8586. return out;
  8587. };
  8588. // Decompresses `data` handed over in two calls, the first `split` bytes long
  8589. auto decompress = [](const std::string &data, size_t split,
  8590. std::string &out) {
  8591. httplib::detail::gzip_decompressor decompressor;
  8592. auto callback = [&](const char *chunk, size_t n) {
  8593. out.append(chunk, n);
  8594. return true;
  8595. };
  8596. return decompressor.decompress(data.data(), split, callback) &&
  8597. decompressor.decompress(data.data() + split, data.size() - split,
  8598. callback);
  8599. };
  8600. // RFC 1952 2.2: a gzip body is a series of members, an empty one included.
  8601. // Bytes after the last member that start no other one are still ignored.
  8602. const auto members = gzip("Hello, ") + gzip("") + gzip("World!");
  8603. for (const auto &body : {members, members + std::string(8, '\0')}) {
  8604. for (size_t split = 0; split <= body.size(); split++) {
  8605. std::string out;
  8606. ASSERT_TRUE(decompress(body, split, out)) << "split at " << split;
  8607. EXPECT_EQ("Hello, World!", out) << "split at " << split;
  8608. }
  8609. }
  8610. // A broken later member fails like a broken first one
  8611. auto broken = gzip("Hello, ") + gzip("World!");
  8612. auto crc_pos = broken.size() - 8;
  8613. broken[crc_pos] = static_cast<char>(broken[crc_pos] ^ 0x01);
  8614. std::string out;
  8615. EXPECT_FALSE(decompress(broken, broken.size(), out));
  8616. }
  8617. #endif
  8618. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8619. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8620. Headers headers;
  8621. headers.emplace("Accept-Encoding", "br");
  8622. auto res = cli_.Get("/streamed-chunked", headers);
  8623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8624. EXPECT_EQ(StatusCode::OK_200, res->status);
  8625. EXPECT_EQ(std::string("123456789"), res->body);
  8626. }
  8627. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8628. Headers headers;
  8629. headers.emplace("Accept-Encoding", "br");
  8630. auto res = cli_.Get("/streamed-chunked2", headers);
  8631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8632. EXPECT_EQ(StatusCode::OK_200, res->status);
  8633. EXPECT_EQ(std::string("123456789"), res->body);
  8634. }
  8635. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8636. cli_.set_compress(true);
  8637. auto res = cli_.Put(
  8638. "/put", 3,
  8639. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8640. sink.os << "PUT";
  8641. return true;
  8642. },
  8643. "text/plain");
  8644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8645. EXPECT_EQ(StatusCode::OK_200, res->status);
  8646. EXPECT_EQ("PUT", res->body);
  8647. }
  8648. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8649. cli_.set_compress(true);
  8650. auto res = cli_.Put(
  8651. "/put",
  8652. [](size_t /*offset*/, DataSink &sink) {
  8653. sink.os << "PUT";
  8654. sink.done();
  8655. return true;
  8656. },
  8657. "text/plain");
  8658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8659. EXPECT_EQ(StatusCode::OK_200, res->status);
  8660. EXPECT_EQ("PUT", res->body);
  8661. }
  8662. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8663. cli_.set_compress(true);
  8664. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8666. EXPECT_EQ(StatusCode::OK_200, res->status);
  8667. EXPECT_EQ(LARGE_DATA, res->body);
  8668. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8669. }
  8670. #endif
  8671. TEST_F(ServerTest, Patch) {
  8672. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8674. EXPECT_EQ(StatusCode::OK_200, res->status);
  8675. EXPECT_EQ("PATCH", res->body);
  8676. }
  8677. TEST_F(ServerTest, Delete) {
  8678. auto res = cli_.Delete("/delete");
  8679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8680. EXPECT_EQ(StatusCode::OK_200, res->status);
  8681. EXPECT_EQ("DELETE", res->body);
  8682. }
  8683. TEST_F(ServerTest, DeleteContentReceiver) {
  8684. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8686. EXPECT_EQ(StatusCode::OK_200, res->status);
  8687. EXPECT_EQ("content", res->body);
  8688. }
  8689. TEST_F(ServerTest, Options) {
  8690. auto res = cli_.Options("*");
  8691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8692. EXPECT_EQ(StatusCode::OK_200, res->status);
  8693. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8694. EXPECT_TRUE(res->body.empty());
  8695. }
  8696. TEST_F(ServerTest, URL) {
  8697. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8699. EXPECT_EQ(StatusCode::OK_200, res->status);
  8700. }
  8701. TEST_F(ServerTest, ArrayParam) {
  8702. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8704. EXPECT_EQ(StatusCode::OK_200, res->status);
  8705. }
  8706. TEST_F(ServerTest, ArrayParamValues) {
  8707. auto res =
  8708. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8710. EXPECT_EQ(StatusCode::OK_200, res->status);
  8711. }
  8712. TEST_F(ServerTest, NoMultipleHeaders) {
  8713. Headers headers = {{"Content-Length", "5"}};
  8714. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8715. "text/plain");
  8716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8717. EXPECT_EQ(StatusCode::OK_200, res->status);
  8718. }
  8719. TEST_F(ServerTest, PostContentReceiver) {
  8720. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8722. ASSERT_EQ(StatusCode::OK_200, res->status);
  8723. ASSERT_EQ("content", res->body);
  8724. }
  8725. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8726. UploadFormDataItems items = {
  8727. {"text1", "text default", "", ""},
  8728. {"text2", "aωb", "", ""},
  8729. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8730. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8731. {"file3", "", "", "application/octet-stream"},
  8732. };
  8733. auto res = cli_.Post("/content_receiver", items);
  8734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8735. EXPECT_EQ(StatusCode::OK_200, res->status);
  8736. }
  8737. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8738. UploadFormDataItems items = {
  8739. {"text1", "text default", "", ""},
  8740. {"text2", "aωb", "", ""},
  8741. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8742. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8743. {"file3", "", "", "application/octet-stream"},
  8744. };
  8745. auto boundary = std::string("+++++");
  8746. std::string body;
  8747. for (const auto &item : items) {
  8748. body += "--" + boundary + "\r\n";
  8749. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8750. if (!item.filename.empty()) {
  8751. body += "; filename=\"" + item.filename + "\"";
  8752. }
  8753. body += "\r\n";
  8754. if (!item.content_type.empty()) {
  8755. body += "Content-Type: " + item.content_type + "\r\n";
  8756. }
  8757. body += "\r\n";
  8758. body += item.content + "\r\n";
  8759. }
  8760. body += "--" + boundary + "--\r\n";
  8761. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8762. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8764. EXPECT_EQ(StatusCode::OK_200, res->status);
  8765. }
  8766. TEST(MultipartFormDataTest, FieldEscaping) {
  8767. Server svr;
  8768. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8769. const ContentReader &content_reader) {
  8770. ASSERT_TRUE(req.is_multipart_form_data());
  8771. std::vector<FormData> received;
  8772. content_reader(
  8773. [&](const FormData &file) {
  8774. received.push_back(file);
  8775. return true;
  8776. },
  8777. [&](const char *data, size_t data_length) {
  8778. received.back().content.append(data, data_length);
  8779. return true;
  8780. });
  8781. // '"', CR and LF in names and filenames are escaped following the
  8782. // WHATWG HTML standard, so each part still parses as a single part
  8783. // with no injected headers. Content types get CR/LF escaped too,
  8784. // while '"' (legal there, e.g. quoted charset) is preserved.
  8785. ASSERT_EQ(4U, received.size());
  8786. EXPECT_EQ("na%22me", received[0].name);
  8787. EXPECT_EQ("quoted name", received[0].content);
  8788. EXPECT_EQ("file", received[1].name);
  8789. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8790. received[1].filename);
  8791. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8792. EXPECT_EQ("injected", received[1].content);
  8793. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8794. EXPECT_EQ("my%22file.txt", received[2].filename);
  8795. EXPECT_EQ("cr lf name", received[2].content);
  8796. EXPECT_EQ("typed", received[3].name);
  8797. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8798. received[3].content_type);
  8799. EXPECT_EQ("typed content", received[3].content);
  8800. });
  8801. auto port = svr.bind_to_any_port("localhost");
  8802. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8803. auto se = detail::scope_exit([&] {
  8804. svr.stop();
  8805. t.join();
  8806. ASSERT_FALSE(svr.is_running());
  8807. });
  8808. svr.wait_until_ready();
  8809. Client cli("localhost", port);
  8810. UploadFormDataItems items = {
  8811. {"na\"me", "quoted name", "", ""},
  8812. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8813. "application/octet-stream"},
  8814. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8815. {"typed", "typed content", "",
  8816. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8817. };
  8818. auto res = cli.Post("/post", items);
  8819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8820. EXPECT_EQ(StatusCode::OK_200, res->status);
  8821. }
  8822. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8823. const UploadFormDataItems items = {
  8824. {"name1", "Content 1", "", ""},
  8825. {"name2", "Content 2", "file2.txt", "text/plain"},
  8826. };
  8827. Server svr;
  8828. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8829. const ContentReader &content_reader) {
  8830. ASSERT_TRUE(req.is_multipart_form_data());
  8831. std::vector<FormData> received;
  8832. content_reader(
  8833. [&](const FormData &file) {
  8834. received.push_back(file);
  8835. return true;
  8836. },
  8837. [&](const char *data, size_t data_length) {
  8838. received.back().content.append(data, data_length);
  8839. return true;
  8840. });
  8841. ASSERT_EQ(2U, received.size());
  8842. EXPECT_EQ("name1", received[0].name);
  8843. EXPECT_EQ("Content 1", received[0].content);
  8844. EXPECT_EQ("name2", received[1].name);
  8845. EXPECT_EQ("Content 2", received[1].content);
  8846. EXPECT_EQ("file2.txt", received[1].filename);
  8847. EXPECT_EQ("text/plain", received[1].content_type);
  8848. });
  8849. auto port = svr.bind_to_any_port("localhost");
  8850. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8851. auto se = detail::scope_exit([&] {
  8852. svr.stop();
  8853. t.join();
  8854. ASSERT_FALSE(svr.is_running());
  8855. });
  8856. svr.wait_until_ready();
  8857. Client cli("localhost", port);
  8858. // Whole-body serialization with a generated boundary
  8859. {
  8860. MultipartFormDataWriter writer;
  8861. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8862. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8863. writer.content_type());
  8864. auto body = writer.serialize(items);
  8865. EXPECT_EQ(body.size(), writer.content_length(items));
  8866. auto res = cli.Post("/post", body, writer.content_type());
  8867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8868. EXPECT_EQ(StatusCode::OK_200, res->status);
  8869. }
  8870. // Per-part framing with a custom boundary via a content provider
  8871. {
  8872. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8873. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8874. MultipartFormDataWriter writer("custom-boundary_123");
  8875. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8876. std::string body;
  8877. for (const auto &item : items) {
  8878. body += writer.item_begin(item);
  8879. body += item.content;
  8880. body += MultipartFormDataWriter::item_end();
  8881. }
  8882. body += writer.finish();
  8883. EXPECT_EQ(body.size(), writer.content_length(items));
  8884. auto res = cli.Post(
  8885. "/post", body.size(),
  8886. [&](size_t offset, size_t length, DataSink &sink) {
  8887. sink.write(body.data() + offset, length);
  8888. return true;
  8889. },
  8890. writer.content_type());
  8891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8892. EXPECT_EQ(StatusCode::OK_200, res->status);
  8893. }
  8894. }
  8895. TEST_F(ServerTest, PostContentReceiverGzip) {
  8896. cli_.set_compress(true);
  8897. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8899. ASSERT_EQ(StatusCode::OK_200, res->status);
  8900. ASSERT_EQ("content", res->body);
  8901. }
  8902. TEST_F(ServerTest, PutContentReceiver) {
  8903. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8905. ASSERT_EQ(StatusCode::OK_200, res->status);
  8906. ASSERT_EQ("content", res->body);
  8907. }
  8908. TEST_F(ServerTest, PatchContentReceiver) {
  8909. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8911. ASSERT_EQ(StatusCode::OK_200, res->status);
  8912. ASSERT_EQ("content", res->body);
  8913. }
  8914. template <typename ClientType>
  8915. void TestWithHeadersAndContentReceiver(
  8916. ClientType &cli,
  8917. std::function<Result(ClientType &, const std::string &, const Headers &,
  8918. const std::string &, const std::string &,
  8919. ContentReceiver, DownloadProgress)>
  8920. request_func) {
  8921. Headers headers;
  8922. headers.emplace("X-Custom-Header", "test-value");
  8923. std::string received_body;
  8924. auto res = request_func(
  8925. cli, "/content_receiver", headers, "content", "application/json",
  8926. [&](const char *data, size_t data_length) {
  8927. received_body.append(data, data_length);
  8928. return true;
  8929. },
  8930. nullptr);
  8931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8932. EXPECT_EQ(StatusCode::OK_200, res->status);
  8933. EXPECT_EQ("content", received_body);
  8934. }
  8935. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8936. #ifdef CPPHTTPLIB_SSL_ENABLED
  8937. using ClientT = SSLClient;
  8938. #else
  8939. using ClientT = Client;
  8940. #endif
  8941. TestWithHeadersAndContentReceiver<ClientT>(
  8942. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8943. const std::string &body, const std::string &content_type,
  8944. ContentReceiver receiver, DownloadProgress progress) {
  8945. return cli.Post(path, headers, body, content_type, receiver, progress);
  8946. });
  8947. }
  8948. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8949. #ifdef CPPHTTPLIB_SSL_ENABLED
  8950. using ClientT = SSLClient;
  8951. #else
  8952. using ClientT = Client;
  8953. #endif
  8954. TestWithHeadersAndContentReceiver<ClientT>(
  8955. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8956. const std::string &body, const std::string &content_type,
  8957. ContentReceiver receiver, DownloadProgress progress) {
  8958. return cli.Put(path, headers, body, content_type, receiver, progress);
  8959. });
  8960. }
  8961. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8962. #ifdef CPPHTTPLIB_SSL_ENABLED
  8963. using ClientT = SSLClient;
  8964. #else
  8965. using ClientT = Client;
  8966. #endif
  8967. TestWithHeadersAndContentReceiver<ClientT>(
  8968. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8969. const std::string &body, const std::string &content_type,
  8970. ContentReceiver receiver, DownloadProgress progress) {
  8971. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8972. });
  8973. }
  8974. template <typename ClientType>
  8975. void TestWithHeadersAndContentReceiverWithProgress(
  8976. ClientType &cli,
  8977. std::function<Result(ClientType &, const std::string &, const Headers &,
  8978. const std::string &, const std::string &,
  8979. ContentReceiver, DownloadProgress)>
  8980. request_func) {
  8981. Headers headers;
  8982. headers.emplace("X-Test-Header", "progress-test");
  8983. std::string received_body;
  8984. auto progress_called = false;
  8985. auto res = request_func(
  8986. cli, "/content_receiver", headers, "content", "text/plain",
  8987. [&](const char *data, size_t data_length) {
  8988. received_body.append(data, data_length);
  8989. return true;
  8990. },
  8991. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8992. progress_called = true;
  8993. return true;
  8994. });
  8995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8996. EXPECT_EQ(StatusCode::OK_200, res->status);
  8997. EXPECT_EQ("content", received_body);
  8998. EXPECT_TRUE(progress_called);
  8999. }
  9000. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  9001. #ifdef CPPHTTPLIB_SSL_ENABLED
  9002. using ClientT = SSLClient;
  9003. #else
  9004. using ClientT = Client;
  9005. #endif
  9006. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  9007. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  9008. const std::string &body, const std::string &content_type,
  9009. ContentReceiver receiver, DownloadProgress progress) {
  9010. return cli.Post(path, headers, body, content_type, receiver, progress);
  9011. });
  9012. }
  9013. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  9014. #ifdef CPPHTTPLIB_SSL_ENABLED
  9015. using ClientT = SSLClient;
  9016. #else
  9017. using ClientT = Client;
  9018. #endif
  9019. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  9020. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  9021. const std::string &body, const std::string &content_type,
  9022. ContentReceiver receiver, DownloadProgress progress) {
  9023. return cli.Put(path, headers, body, content_type, receiver, progress);
  9024. });
  9025. }
  9026. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  9027. #ifdef CPPHTTPLIB_SSL_ENABLED
  9028. using ClientT = SSLClient;
  9029. #else
  9030. using ClientT = Client;
  9031. #endif
  9032. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  9033. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  9034. const std::string &body, const std::string &content_type,
  9035. ContentReceiver receiver, DownloadProgress progress) {
  9036. return cli.Patch(path, headers, body, content_type, receiver, progress);
  9037. });
  9038. }
  9039. template <typename ClientType>
  9040. void TestWithHeadersAndContentReceiverError(
  9041. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  9042. const Headers &, const std::string &,
  9043. const std::string &, ContentReceiver)>
  9044. request_func) {
  9045. Headers headers;
  9046. headers.emplace("X-Error-Test", "true");
  9047. std::string received_body;
  9048. auto receiver_failed = false;
  9049. auto res =
  9050. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  9051. [&](const char *data, size_t data_length) {
  9052. received_body.append(data, data_length);
  9053. receiver_failed = true;
  9054. return false;
  9055. });
  9056. ASSERT_FALSE(res);
  9057. EXPECT_TRUE(receiver_failed);
  9058. }
  9059. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  9060. #ifdef CPPHTTPLIB_SSL_ENABLED
  9061. using ClientT = SSLClient;
  9062. #else
  9063. using ClientT = Client;
  9064. #endif
  9065. TestWithHeadersAndContentReceiverError<ClientT>(
  9066. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  9067. const std::string &body, const std::string &content_type,
  9068. ContentReceiver receiver) {
  9069. return cli.Post(path, headers, body, content_type, receiver);
  9070. });
  9071. }
  9072. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  9073. #ifdef CPPHTTPLIB_SSL_ENABLED
  9074. using ClientT = SSLClient;
  9075. #else
  9076. using ClientT = Client;
  9077. #endif
  9078. TestWithHeadersAndContentReceiverError<ClientT>(
  9079. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  9080. const std::string &body, const std::string &content_type,
  9081. ContentReceiver receiver) {
  9082. return cli.Put(path, headers, body, content_type, receiver);
  9083. });
  9084. }
  9085. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  9086. #ifdef CPPHTTPLIB_SSL_ENABLED
  9087. using ClientT = SSLClient;
  9088. #else
  9089. using ClientT = Client;
  9090. #endif
  9091. TestWithHeadersAndContentReceiverError<ClientT>(
  9092. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  9093. const std::string &body, const std::string &content_type,
  9094. ContentReceiver receiver) {
  9095. return cli.Patch(path, headers, body, content_type, receiver);
  9096. });
  9097. }
  9098. TEST_F(ServerTest, PostQueryStringAndBody) {
  9099. auto res =
  9100. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  9101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9102. ASSERT_EQ(StatusCode::OK_200, res->status);
  9103. }
  9104. TEST_F(ServerTest, HTTP2Magic) {
  9105. Request req;
  9106. req.method = "PRI";
  9107. req.path = "*";
  9108. req.body = "SM";
  9109. auto res = std::make_shared<Response>();
  9110. auto error = Error::Success;
  9111. auto ret = cli_.send(req, *res, error);
  9112. ASSERT_TRUE(ret);
  9113. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9114. }
  9115. TEST_F(ServerTest, KeepAlive) {
  9116. auto res = cli_.Get("/hi");
  9117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9118. EXPECT_EQ(StatusCode::OK_200, res->status);
  9119. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9120. EXPECT_EQ("Hello World!", res->body);
  9121. res = cli_.Get("/hi");
  9122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9123. EXPECT_EQ(StatusCode::OK_200, res->status);
  9124. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9125. EXPECT_EQ("Hello World!", res->body);
  9126. res = cli_.Get("/hi");
  9127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9128. EXPECT_EQ(StatusCode::OK_200, res->status);
  9129. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9130. EXPECT_EQ("Hello World!", res->body);
  9131. res = cli_.Get("/not-exist");
  9132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9133. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9134. res = cli_.Post("/empty", "", "text/plain");
  9135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9136. EXPECT_EQ(StatusCode::OK_200, res->status);
  9137. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9138. EXPECT_EQ("empty", res->body);
  9139. EXPECT_EQ("close", res->get_header_value("Connection"));
  9140. res = cli_.Post(
  9141. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  9142. "text/plain");
  9143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9144. EXPECT_EQ(StatusCode::OK_200, res->status);
  9145. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9146. EXPECT_EQ("empty", res->body);
  9147. cli_.set_keep_alive(false);
  9148. res = cli_.Get("/last-request");
  9149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9150. EXPECT_EQ(StatusCode::OK_200, res->status);
  9151. EXPECT_EQ("close", res->get_header_value("Connection"));
  9152. }
  9153. TEST_F(ServerTest, TooManyRedirect) {
  9154. cli_.set_follow_location(true);
  9155. auto res = cli_.Get("/redirect/0");
  9156. ASSERT_TRUE(!res);
  9157. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  9158. }
  9159. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  9160. Request req;
  9161. req.method = "FOOBAR";
  9162. req.path = "/hi";
  9163. cli_.set_keep_alive(true);
  9164. auto res = cli_.send(req);
  9165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9166. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9167. EXPECT_EQ("close", res->get_header_value("Connection"));
  9168. EXPECT_FALSE(cli_.is_socket_open());
  9169. }
  9170. TEST_F(ServerTest, CustomRouteReadsBody) {
  9171. const std::string xml =
  9172. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  9173. Request req;
  9174. req.method = "PROPFIND";
  9175. req.path = "/dav/dir";
  9176. req.set_header("Depth", "1");
  9177. req.body = xml;
  9178. auto res = cli_.send(req);
  9179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9180. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9181. EXPECT_EQ(xml, res->body);
  9182. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  9183. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  9184. }
  9185. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  9186. Request req;
  9187. req.method = "PROPFIND";
  9188. req.path = "/dav/42";
  9189. auto res = cli_.send(req);
  9190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9191. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9192. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  9193. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  9194. }
  9195. TEST_F(ServerTest, CustomRouteRegexPattern) {
  9196. Request req;
  9197. req.method = "PROPFIND";
  9198. req.path = "/dav-re/123";
  9199. auto res = cli_.send(req);
  9200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9201. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9202. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  9203. }
  9204. TEST_F(ServerTest, CustomRouteWithoutBody) {
  9205. Request req;
  9206. req.method = "MKCOL";
  9207. req.path = "/dav-mkcol";
  9208. auto res = cli_.send(req);
  9209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9210. EXPECT_EQ(StatusCode::Created_201, res->status);
  9211. }
  9212. TEST_F(ServerTest, CustomRouteWithContentReader) {
  9213. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  9214. Request req;
  9215. req.method = "REPORT";
  9216. req.path = "/dav-report";
  9217. req.body = xml;
  9218. auto res = cli_.send(req);
  9219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9220. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9221. EXPECT_EQ(xml, res->body);
  9222. }
  9223. // A content reader route must fire even when the request carries no body,
  9224. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  9225. // Without that, a body-less PROPFIND-style request would fall through to 404.
  9226. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  9227. Request req;
  9228. req.method = "REPORT";
  9229. req.path = "/dav-report";
  9230. auto res = cli_.send(req);
  9231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9232. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9233. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  9234. }
  9235. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  9236. Request req;
  9237. req.method = "PROPFIND";
  9238. req.path = "/not-dav";
  9239. auto res = cli_.send(req);
  9240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9241. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9242. }
  9243. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  9244. Request req;
  9245. req.method = "UNLOCK";
  9246. req.path = "/dav/dir";
  9247. cli_.set_keep_alive(true);
  9248. auto res = cli_.send(req);
  9249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9250. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9251. EXPECT_EQ("close", res->get_header_value("Connection"));
  9252. EXPECT_FALSE(cli_.is_socket_open());
  9253. }
  9254. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  9255. // The mount point serves this path, but only for GET and HEAD.
  9256. auto get_res = cli_.Get("/dir/index.html");
  9257. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  9258. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  9259. Request req;
  9260. req.method = "PROPFIND";
  9261. req.path = "/dir/index.html";
  9262. auto res = cli_.send(req);
  9263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9265. }
  9266. TEST_F(ServerTest, CustomRouteKeepAlive) {
  9267. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9268. cli_.set_keep_alive(true);
  9269. for (auto i = 0; i < 2; i++) {
  9270. Request req;
  9271. req.method = "PROPFIND";
  9272. req.path = "/dav/dir";
  9273. req.body = xml;
  9274. auto res = cli_.send(req);
  9275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9276. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9277. EXPECT_EQ(xml, res->body);
  9278. EXPECT_TRUE(cli_.is_socket_open());
  9279. }
  9280. // A built-in method must still be served on the same connection.
  9281. cli_.set_keep_alive(false);
  9282. auto res = cli_.Get("/hi");
  9283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9284. EXPECT_EQ(StatusCode::OK_200, res->status);
  9285. EXPECT_EQ("close", res->get_header_value("Connection"));
  9286. }
  9287. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  9288. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9289. Request req;
  9290. req.method = "PROPFIND";
  9291. req.path = "/dav/dir";
  9292. req.set_header("Expect", "100-continue");
  9293. req.body = xml;
  9294. auto res = cli_.send(req);
  9295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9296. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9297. EXPECT_EQ(xml, res->body);
  9298. }
  9299. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  9300. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9301. TEST_F(ServerTest, Gzip) {
  9302. Headers headers;
  9303. headers.emplace("Accept-Encoding", "gzip, deflate");
  9304. auto res = cli_.Get("/compress", headers);
  9305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9306. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9307. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9308. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9309. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9310. "7890123456789012345678901234567890",
  9311. res->body);
  9312. EXPECT_EQ(StatusCode::OK_200, res->status);
  9313. }
  9314. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  9315. Headers headers;
  9316. headers.emplace("Accept-Encoding", "gzip, deflate");
  9317. auto res = cli_.Get("/compress-with-charset", headers);
  9318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9319. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9320. EXPECT_EQ("application/json; charset=utf-8",
  9321. res->get_header_value("Content-Type"));
  9322. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9323. "7890123456789012345678901234567890",
  9324. res->body);
  9325. EXPECT_EQ(StatusCode::OK_200, res->status);
  9326. }
  9327. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  9328. Headers headers;
  9329. headers.emplace("Accept-Encoding", "");
  9330. auto res = cli_.Get("/compress", headers);
  9331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9332. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9333. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9334. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9335. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9336. "7890123456789012345678901234567890",
  9337. res->body);
  9338. EXPECT_EQ(StatusCode::OK_200, res->status);
  9339. }
  9340. TEST_F(ServerTest, GzipWithContentReceiver) {
  9341. Headers headers;
  9342. headers.emplace("Accept-Encoding", "gzip, deflate");
  9343. std::string body;
  9344. auto res =
  9345. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9346. EXPECT_EQ(100U, data_length);
  9347. body.append(data, data_length);
  9348. return true;
  9349. });
  9350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9351. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9352. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9353. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9354. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9355. "7890123456789012345678901234567890",
  9356. body);
  9357. EXPECT_EQ(StatusCode::OK_200, res->status);
  9358. }
  9359. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9360. Headers headers;
  9361. headers.emplace("Accept-Encoding", "gzip, deflate");
  9362. cli_.set_decompress(false);
  9363. auto res = cli_.Get("/compress", headers);
  9364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9365. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9366. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9367. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9368. EXPECT_EQ(33U, res->body.size());
  9369. EXPECT_EQ(StatusCode::OK_200, res->status);
  9370. }
  9371. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9372. Headers headers;
  9373. headers.emplace("Accept-Encoding", "");
  9374. std::string body;
  9375. auto res =
  9376. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9377. EXPECT_EQ(100U, data_length);
  9378. body.append(data, data_length);
  9379. return true;
  9380. });
  9381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9382. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9383. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9384. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9385. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9386. "7890123456789012345678901234567890",
  9387. body);
  9388. EXPECT_EQ(StatusCode::OK_200, res->status);
  9389. }
  9390. TEST_F(ServerTest, NoGzip) {
  9391. Headers headers;
  9392. headers.emplace("Accept-Encoding", "gzip, deflate");
  9393. auto res = cli_.Get("/nocompress", headers);
  9394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9395. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9396. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9397. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9398. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9399. "7890123456789012345678901234567890",
  9400. res->body);
  9401. EXPECT_EQ(StatusCode::OK_200, res->status);
  9402. }
  9403. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9404. Headers headers;
  9405. headers.emplace("Accept-Encoding", "gzip, deflate");
  9406. std::string body;
  9407. auto res = cli_.Get("/nocompress", headers,
  9408. [&](const char *data, size_t data_length) {
  9409. EXPECT_EQ(100U, data_length);
  9410. body.append(data, data_length);
  9411. return true;
  9412. });
  9413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9414. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9415. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9416. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9417. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9418. "7890123456789012345678901234567890",
  9419. body);
  9420. EXPECT_EQ(StatusCode::OK_200, res->status);
  9421. }
  9422. TEST_F(ServerTest, MultipartFormDataGzip) {
  9423. UploadFormDataItems items = {
  9424. {"key1", "test", "", ""},
  9425. {"key2", "--abcdefg123", "", ""},
  9426. };
  9427. cli_.set_compress(true);
  9428. auto res = cli_.Post("/compress-multipart", items);
  9429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9430. EXPECT_EQ(StatusCode::OK_200, res->status);
  9431. }
  9432. #endif
  9433. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9434. // Static file compression is opt-in, so these run their own server rather than
  9435. // flipping it on for the shared ServerTest fixture, which would silently
  9436. // rewrite what every other static file test is asserting.
  9437. class StaticFileCompressionTest : public ::testing::Test {
  9438. protected:
  9439. void TearDown() override {
  9440. if (t_.joinable()) {
  9441. svr_.stop();
  9442. t_.join();
  9443. }
  9444. }
  9445. int start(const std::function<void(Server &)> &configure = nullptr) {
  9446. // Serves the same tree as a directory of build-time compressed assets
  9447. // would be served: the mount point names the coding the files are already
  9448. // stored in. Registered before "/" so it is the one that matches.
  9449. svr_.set_mount_point("/pre-encoded", "./www",
  9450. {{"Content-Encoding", "gzip"}});
  9451. svr_.set_mount_point("/", "./www");
  9452. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9453. res.set_file_content("./www/dir/index.html", "text/html");
  9454. });
  9455. svr_.Get("/pre-encoded-file-content",
  9456. [](const Request & /*req*/, Response &res) {
  9457. res.set_header("Content-Encoding", "gzip");
  9458. res.set_file_content("./www/dir/index.html", "text/html");
  9459. });
  9460. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9461. res.set_content_provider(
  9462. 6, "text/plain",
  9463. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9464. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9465. return true;
  9466. });
  9467. });
  9468. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9469. res.set_content_provider(
  9470. 1000, "text/plain",
  9471. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9472. if (offset < 100) {
  9473. std::string data(100, 'A');
  9474. sink.write(data.data(), data.size());
  9475. return true;
  9476. }
  9477. std::this_thread::sleep_for(std::chrono::seconds(2));
  9478. std::string data(900, 'B');
  9479. sink.write(data.data(), data.size());
  9480. return true;
  9481. });
  9482. });
  9483. if (configure) { configure(svr_); }
  9484. auto port = svr_.bind_to_any_port(HOST);
  9485. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9486. svr_.wait_until_ready();
  9487. return port;
  9488. }
  9489. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9490. // Every file under ./www except 1MB.txt is smaller than the default
  9491. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9492. // it out of the way.
  9493. static void enable_without_floor(Server &svr) {
  9494. svr.set_static_file_compression(true);
  9495. svr.set_static_file_compression_min_length(0);
  9496. }
  9497. Server svr_;
  9498. std::thread t_;
  9499. };
  9500. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9501. auto port = start();
  9502. Client cli(HOST, port);
  9503. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9505. EXPECT_EQ(StatusCode::OK_200, res->status);
  9506. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9507. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9508. EXPECT_EQ(1048576U, res->body.size());
  9509. }
  9510. TEST_F(StaticFileCompressionTest, MountPoint) {
  9511. auto port = start(enable);
  9512. Client cli(HOST, port);
  9513. cli.set_decompress(false);
  9514. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9516. EXPECT_EQ(StatusCode::OK_200, res->status);
  9517. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9518. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9519. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9520. // The response stays self-delimiting: a length, not a chunked body.
  9521. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9522. EXPECT_EQ(std::to_string(res->body.size()),
  9523. res->get_header_value("Content-Length"));
  9524. EXPECT_LT(res->body.size(), 1048576U);
  9525. EXPECT_FALSE(res->body.empty());
  9526. }
  9527. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9528. auto port = start(enable);
  9529. Client cli(HOST, port);
  9530. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9532. EXPECT_EQ(StatusCode::OK_200, res->status);
  9533. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9534. EXPECT_EQ(1048576U, res->body.size());
  9535. }
  9536. TEST_F(StaticFileCompressionTest, FileContent) {
  9537. auto port = start(enable_without_floor);
  9538. Client cli(HOST, port);
  9539. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9541. EXPECT_EQ(StatusCode::OK_200, res->status);
  9542. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9543. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9544. EXPECT_EQ(104U, res->body.size());
  9545. }
  9546. // A handler that serves an already-encoded file names the coding itself. The
  9547. // file-backed path decided its coding from Accept-Encoding and the content
  9548. // type alone, so it compressed the stored bytes a second time and appended a
  9549. // second Content-Encoding field line.
  9550. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9551. auto port = start(enable_without_floor);
  9552. Client cli(HOST, port);
  9553. cli.set_decompress(false);
  9554. auto res = cli.Get("/pre-encoded-file-content",
  9555. Headers{{"Accept-Encoding", "gzip"}});
  9556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9557. EXPECT_EQ(StatusCode::OK_200, res->status);
  9558. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9559. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9560. // Vary belongs to a coding the server chose, and it chose none here.
  9561. EXPECT_FALSE(res->has_header("Vary"));
  9562. // The file travels exactly as it is stored on disk.
  9563. EXPECT_EQ(104U, res->body.size());
  9564. }
  9565. // The 1MB file clears the default floor, so this one runs the configuration a
  9566. // deployment would actually have.
  9567. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9568. auto port = start(enable);
  9569. Client cli(HOST, port);
  9570. cli.set_decompress(false);
  9571. auto res =
  9572. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9574. EXPECT_EQ(StatusCode::OK_200, res->status);
  9575. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9576. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9577. EXPECT_FALSE(res->has_header("Vary"));
  9578. EXPECT_EQ(1048576U, res->body.size());
  9579. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9580. }
  9581. TEST_F(StaticFileCompressionTest, Head) {
  9582. auto port = start(enable);
  9583. Client cli(HOST, port);
  9584. cli.set_decompress(false);
  9585. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9586. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9587. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9589. EXPECT_EQ(StatusCode::OK_200, res->status);
  9590. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9591. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9592. // HEAD still reports the size a GET would return.
  9593. EXPECT_EQ(get->get_header_value("Content-Length"),
  9594. res->get_header_value("Content-Length"));
  9595. EXPECT_TRUE(res->body.empty());
  9596. }
  9597. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9598. auto port = start(enable);
  9599. Client cli(HOST, port);
  9600. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9601. {"Accept-Encoding", "gzip"}});
  9602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9604. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9605. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9606. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9607. EXPECT_EQ("cd", res->body);
  9608. }
  9609. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9610. auto port = start(enable);
  9611. Client cli(HOST, port);
  9612. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9614. EXPECT_EQ(StatusCode::OK_200, res->status);
  9615. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9616. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9617. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9618. }
  9619. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9620. auto port = start(enable);
  9621. Client cli(HOST, port);
  9622. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9624. EXPECT_EQ(StatusCode::OK_200, res->status);
  9625. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9626. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9627. EXPECT_TRUE(res->body.empty());
  9628. }
  9629. TEST_F(StaticFileCompressionTest, MinLength) {
  9630. auto port = start(enable);
  9631. Client cli(HOST, port);
  9632. // 104 bytes, well under the default floor. Compressing it would add the
  9633. // gzip header and trailer to a body that already fits in one packet.
  9634. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9636. EXPECT_EQ(StatusCode::OK_200, res->status);
  9637. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9638. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9639. }
  9640. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9641. auto port = start([](Server &svr) {
  9642. svr.set_static_file_compression(true);
  9643. svr.set_static_file_compression_min_length(1);
  9644. });
  9645. Client cli(HOST, port);
  9646. cli.set_decompress(false);
  9647. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9649. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9650. // A 9-byte file comes back larger than it went in, because gzip's header and
  9651. // trailer outweigh anything deflate can save. That is the end of the range
  9652. // the floor exists to keep out.
  9653. EXPECT_GT(res->body.size(), 9U);
  9654. }
  9655. TEST_F(StaticFileCompressionTest, MaxLength) {
  9656. auto port = start([](Server &svr) {
  9657. svr.set_static_file_compression(true);
  9658. svr.set_static_file_compression_min_length(0);
  9659. svr.set_static_file_compression_max_length(1024);
  9660. });
  9661. Client cli(HOST, port);
  9662. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9663. // defines `small` as a macro on Windows.
  9664. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9665. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9666. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9667. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9668. // Under it: compressed.
  9669. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9670. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9671. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9672. }
  9673. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9674. auto port = start(enable_without_floor);
  9675. Client cli(HOST, port);
  9676. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9677. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9678. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9679. auto identity_etag = identity->get_header_value("ETag");
  9680. ASSERT_FALSE(identity_etag.empty());
  9681. auto gzipped =
  9682. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9683. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9684. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9685. auto gzip_etag = gzipped->get_header_value("ETag");
  9686. ASSERT_FALSE(gzip_etag.empty());
  9687. // Two representations, two validators.
  9688. EXPECT_NE(identity_etag, gzip_etag);
  9689. // Each one revalidates against the request that would produce it...
  9690. auto fresh =
  9691. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9692. {"If-None-Match", gzip_etag}});
  9693. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9694. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9695. auto fresh_identity =
  9696. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9697. {"If-None-Match", identity_etag}});
  9698. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9699. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9700. // ...and not against the other representation.
  9701. auto crossed =
  9702. cli.Get("/dir/index.html",
  9703. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9704. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9705. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9706. }
  9707. // The opt-in covers responses the server reads off disk itself. A caller's own
  9708. // known-length provider keeps its Content-Length and, more importantly, keeps
  9709. // delivering incrementally: routing it through a compressor would hold every
  9710. // write back until zlib's window filled.
  9711. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9712. auto port = start(enable);
  9713. Client cli(HOST, port);
  9714. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9716. EXPECT_EQ(StatusCode::OK_200, res->status);
  9717. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9718. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9719. EXPECT_EQ("aaabbb", res->body);
  9720. }
  9721. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9722. auto port = start(enable);
  9723. Client cli(HOST, port);
  9724. cli.set_read_timeout(1, 0);
  9725. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9726. Headers{{"Accept-Encoding", "gzip"}});
  9727. ASSERT_TRUE(handle.is_valid());
  9728. // The provider writes 100 bytes and then stalls for longer than the read
  9729. // timeout. Those first bytes have to arrive anyway: run the response through
  9730. // a compressor and zlib holds them until its window fills, so the read would
  9731. // come back empty instead.
  9732. char buf[256];
  9733. auto n = handle.read(buf, sizeof(buf));
  9734. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9735. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9736. }
  9737. #endif
  9738. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9739. TEST_F(ServerTest, Brotli) {
  9740. Headers headers;
  9741. headers.emplace("Accept-Encoding", "br");
  9742. auto res = cli_.Get("/compress", headers);
  9743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9744. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9745. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9746. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9747. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9748. "7890123456789012345678901234567890",
  9749. res->body);
  9750. EXPECT_EQ(StatusCode::OK_200, res->status);
  9751. }
  9752. #endif
  9753. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9754. TEST_F(ServerTest, Zstd) {
  9755. Headers headers;
  9756. headers.emplace("Accept-Encoding", "zstd");
  9757. auto res = cli_.Get("/compress", headers);
  9758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9759. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9760. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9761. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9762. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9763. "7890123456789012345678901234567890",
  9764. res->body);
  9765. EXPECT_EQ(StatusCode::OK_200, res->status);
  9766. }
  9767. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9768. Headers headers;
  9769. headers.emplace("Accept-Encoding", "");
  9770. auto res = cli_.Get("/compress", headers);
  9771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9772. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9773. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9774. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9775. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9776. "7890123456789012345678901234567890",
  9777. res->body);
  9778. EXPECT_EQ(StatusCode::OK_200, res->status);
  9779. }
  9780. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9781. Headers headers;
  9782. headers.emplace("Accept-Encoding", "zstd");
  9783. std::string body;
  9784. auto res =
  9785. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9786. EXPECT_EQ(100U, data_length);
  9787. body.append(data, data_length);
  9788. return true;
  9789. });
  9790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9791. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9792. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9793. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9794. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9795. "7890123456789012345678901234567890",
  9796. body);
  9797. EXPECT_EQ(StatusCode::OK_200, res->status);
  9798. }
  9799. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9800. Headers headers;
  9801. headers.emplace("Accept-Encoding", "zstd");
  9802. cli_.set_decompress(false);
  9803. auto res = cli_.Get("/compress", headers);
  9804. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9805. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9806. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9807. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9809. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9810. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9811. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9812. EXPECT_EQ(StatusCode::OK_200, res->status);
  9813. ASSERT_EQ(26U, res->body.size());
  9814. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9815. 0);
  9816. }
  9817. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9818. Headers headers;
  9819. headers.emplace("Accept-Encoding", "");
  9820. std::string body;
  9821. auto res =
  9822. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9823. EXPECT_EQ(100U, data_length);
  9824. body.append(data, data_length);
  9825. return true;
  9826. });
  9827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9828. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9829. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9830. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9831. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9832. "7890123456789012345678901234567890",
  9833. body);
  9834. EXPECT_EQ(StatusCode::OK_200, res->status);
  9835. }
  9836. TEST_F(ServerTest, NoZstd) {
  9837. Headers headers;
  9838. headers.emplace("Accept-Encoding", "zstd");
  9839. auto res = cli_.Get("/nocompress", headers);
  9840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9841. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9842. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9843. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9844. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9845. "7890123456789012345678901234567890",
  9846. res->body);
  9847. EXPECT_EQ(StatusCode::OK_200, res->status);
  9848. }
  9849. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9850. Headers headers;
  9851. headers.emplace("Accept-Encoding", "zstd");
  9852. std::string body;
  9853. auto res = cli_.Get("/nocompress", headers,
  9854. [&](const char *data, size_t data_length) {
  9855. EXPECT_EQ(100U, data_length);
  9856. body.append(data, data_length);
  9857. return true;
  9858. });
  9859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9860. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9861. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9862. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9863. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9864. "7890123456789012345678901234567890",
  9865. body);
  9866. EXPECT_EQ(StatusCode::OK_200, res->status);
  9867. }
  9868. // TODO: How to enable zstd ??
  9869. TEST_F(ServerTest, MultipartFormDataZstd) {
  9870. UploadFormDataItems items = {
  9871. {"key1", "test", "", ""},
  9872. {"key2", "--abcdefg123", "", ""},
  9873. };
  9874. Headers headers;
  9875. headers.emplace("Accept-Encoding", "zstd");
  9876. cli_.set_compress(true);
  9877. auto res = cli_.Post("/compress-multipart", headers, items);
  9878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9879. EXPECT_EQ(StatusCode::OK_200, res->status);
  9880. }
  9881. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9882. Headers headers;
  9883. headers.emplace("Accept-Encoding", "zstd");
  9884. cli_.set_compress(true);
  9885. auto res = cli_.Put(
  9886. "/put", headers, 3,
  9887. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9888. sink.os << "PUT";
  9889. return true;
  9890. },
  9891. "text/plain");
  9892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9893. EXPECT_EQ(StatusCode::OK_200, res->status);
  9894. EXPECT_EQ("PUT", res->body);
  9895. }
  9896. // Pre-compression logging tests
  9897. TEST_F(ServerTest, PreCompressionLogging) {
  9898. // Test data for compression (matches the actual /compress endpoint content)
  9899. const std::string test_content =
  9900. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9901. "3456789012345678901234567890";
  9902. // Variables to capture logging data
  9903. std::string pre_compression_body;
  9904. std::string pre_compression_content_type;
  9905. std::string pre_compression_content_encoding;
  9906. std::string post_compression_body;
  9907. std::string post_compression_content_type;
  9908. std::string post_compression_content_encoding;
  9909. // Set up pre-compression logger
  9910. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9911. const Response &res) {
  9912. pre_compression_body = res.body;
  9913. pre_compression_content_type = res.get_header_value("Content-Type");
  9914. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9915. });
  9916. // Set up post-compression logger
  9917. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9918. post_compression_body = res.body;
  9919. post_compression_content_type = res.get_header_value("Content-Type");
  9920. post_compression_content_encoding =
  9921. res.get_header_value("Content-Encoding");
  9922. });
  9923. // Test with gzip compression
  9924. Headers headers;
  9925. headers.emplace("Accept-Encoding", "gzip");
  9926. auto res = cli_.Get("/compress", headers);
  9927. // Verify response was compressed
  9928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9929. EXPECT_EQ(StatusCode::OK_200, res->status);
  9930. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9931. // Verify pre-compression logger captured uncompressed content
  9932. EXPECT_EQ(test_content, pre_compression_body);
  9933. EXPECT_EQ("text/plain", pre_compression_content_type);
  9934. EXPECT_TRUE(pre_compression_content_encoding
  9935. .empty()); // No encoding header before compression
  9936. // Verify post-compression logger captured compressed content
  9937. EXPECT_NE(test_content,
  9938. post_compression_body); // Should be different after compression
  9939. EXPECT_EQ("text/plain", post_compression_content_type);
  9940. EXPECT_EQ("gzip", post_compression_content_encoding);
  9941. // Verify compressed content is smaller
  9942. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9943. }
  9944. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9945. const std::string test_content =
  9946. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9947. "3456789012345678901234567890";
  9948. std::string pre_compression_body;
  9949. std::string post_compression_body;
  9950. svr_.set_pre_compression_logger(
  9951. [&](const Request & /*req*/, const Response &res) {
  9952. pre_compression_body = res.body;
  9953. });
  9954. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9955. post_compression_body = res.body;
  9956. });
  9957. Headers headers;
  9958. headers.emplace("Accept-Encoding", "br");
  9959. auto res = cli_.Get("/compress", headers);
  9960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9961. EXPECT_EQ(StatusCode::OK_200, res->status);
  9962. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9963. // Verify pre-compression content is uncompressed
  9964. EXPECT_EQ(test_content, pre_compression_body);
  9965. // Verify post-compression content is compressed
  9966. EXPECT_NE(test_content, post_compression_body);
  9967. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9968. }
  9969. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9970. const std::string test_content =
  9971. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9972. "3456789012345678901234567890";
  9973. std::string pre_compression_body;
  9974. std::string post_compression_body;
  9975. svr_.set_pre_compression_logger(
  9976. [&](const Request & /*req*/, const Response &res) {
  9977. pre_compression_body = res.body;
  9978. });
  9979. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9980. post_compression_body = res.body;
  9981. });
  9982. // Request without compression (use /nocompress endpoint)
  9983. Headers headers;
  9984. auto res = cli_.Get("/nocompress", headers);
  9985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9986. EXPECT_EQ(StatusCode::OK_200, res->status);
  9987. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9988. // Pre-compression logger should not be called when no compression is applied
  9989. EXPECT_TRUE(
  9990. pre_compression_body.empty()); // Pre-compression logger not called
  9991. EXPECT_EQ(
  9992. test_content,
  9993. post_compression_body); // Post-compression logger captures final content
  9994. }
  9995. TEST_F(ServerTest, LoggerSeesContentLength) {
  9996. size_t logged_content_length = 0;
  9997. std::string logged_content_length_header;
  9998. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9999. logged_content_length = res.content_length_;
  10000. logged_content_length_header = res.get_header_value("Content-Length");
  10001. });
  10002. auto res = cli_.Get("/nocompress");
  10003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10004. EXPECT_EQ(StatusCode::OK_200, res->status);
  10005. EXPECT_EQ(res->body.size(), logged_content_length);
  10006. EXPECT_EQ(std::to_string(logged_content_length),
  10007. logged_content_length_header);
  10008. }
  10009. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  10010. const std::string test_content =
  10011. "123456789012345678901234567890123456789012345678901234567890123456789012"
  10012. "3456789012345678901234567890";
  10013. std::string pre_compression_body;
  10014. bool pre_logger_called = false;
  10015. // Set only pre-compression logger
  10016. svr_.set_pre_compression_logger(
  10017. [&](const Request & /*req*/, const Response &res) {
  10018. pre_compression_body = res.body;
  10019. pre_logger_called = true;
  10020. });
  10021. Headers headers;
  10022. headers.emplace("Accept-Encoding", "gzip");
  10023. auto res = cli_.Get("/compress", headers);
  10024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10025. EXPECT_EQ(StatusCode::OK_200, res->status);
  10026. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  10027. // Verify pre-compression logger was called
  10028. EXPECT_TRUE(pre_logger_called);
  10029. EXPECT_EQ(test_content, pre_compression_body);
  10030. }
  10031. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  10032. {
  10033. // Test with Expect: 100-continue header - success case
  10034. // Server returns 100 Continue, client sends body, server returns 200 OK
  10035. Request req;
  10036. req.method = "POST";
  10037. req.path = "/post-large";
  10038. req.set_header("Expect", "100-continue");
  10039. req.body = LARGE_DATA;
  10040. Response res;
  10041. auto error = Error::Success;
  10042. cli_.set_keep_alive(true);
  10043. auto ret = cli_.send(req, res, error);
  10044. EXPECT_TRUE(ret);
  10045. EXPECT_EQ(StatusCode::OK_200, res.status);
  10046. EXPECT_EQ(LARGE_DATA, res.body);
  10047. }
  10048. {
  10049. // Test with Expect: 100-continue header - error case
  10050. // Client should not send the body when server returns an error
  10051. Request req;
  10052. req.method = "POST";
  10053. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  10054. req.set_header("Expect", "100-continue");
  10055. req.body = LARGE_DATA;
  10056. Response res;
  10057. auto error = Error::Success;
  10058. auto start = std::chrono::high_resolution_clock::now();
  10059. cli_.set_keep_alive(true);
  10060. auto ret = cli_.send(req, res, error);
  10061. auto end = std::chrono::high_resolution_clock::now();
  10062. auto elapsed =
  10063. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  10064. .count();
  10065. // With Expect: 100-continue, request completes successfully but with error
  10066. EXPECT_TRUE(ret);
  10067. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  10068. EXPECT_EQ("close", res.get_header_value("Connection"));
  10069. EXPECT_FALSE(cli_.is_socket_open());
  10070. EXPECT_LE(elapsed, 2000);
  10071. }
  10072. {
  10073. // Send an extra GET request to ensure error recovery without hanging
  10074. Request req;
  10075. req.method = "GET";
  10076. req.path = "/hi";
  10077. auto start = std::chrono::high_resolution_clock::now();
  10078. auto res = cli_.send(req);
  10079. auto end = std::chrono::high_resolution_clock::now();
  10080. auto elapsed =
  10081. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  10082. .count();
  10083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10084. EXPECT_EQ(StatusCode::OK_200, res->status);
  10085. EXPECT_EQ("Hello World!", res->body);
  10086. EXPECT_LE(elapsed, 500);
  10087. }
  10088. }
  10089. TEST(ZstdDecompressor, ChunkedDecompression) {
  10090. std::string data;
  10091. for (size_t i = 0; i < 32 * 1024; ++i) {
  10092. data.push_back(static_cast<char>('a' + i % 26));
  10093. }
  10094. std::string compressed_data;
  10095. {
  10096. httplib::detail::zstd_compressor compressor;
  10097. bool result = compressor.compress(
  10098. data.data(), data.size(),
  10099. /*last=*/true,
  10100. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  10101. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  10102. compressed_data_size);
  10103. return true;
  10104. });
  10105. ASSERT_TRUE(result);
  10106. }
  10107. std::string decompressed_data;
  10108. {
  10109. httplib::detail::zstd_decompressor decompressor;
  10110. // Chunk size is chosen specifically to have a decompressed chunk size equal
  10111. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  10112. size_t chunk_size = 130;
  10113. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  10114. chunk_begin += chunk_size) {
  10115. size_t current_chunk_size =
  10116. std::min(compressed_data.size() - chunk_begin, chunk_size);
  10117. bool result = decompressor.decompress(
  10118. compressed_data.data() + chunk_begin, current_chunk_size,
  10119. [&](const char *decompressed_data_chunk,
  10120. size_t decompressed_data_chunk_size) {
  10121. decompressed_data.insert(decompressed_data.size(),
  10122. decompressed_data_chunk,
  10123. decompressed_data_chunk_size);
  10124. return true;
  10125. });
  10126. ASSERT_TRUE(result);
  10127. }
  10128. }
  10129. ASSERT_EQ(data, decompressed_data);
  10130. }
  10131. TEST(ZstdDecompressor, Decompress) {
  10132. std::string original_text = "Compressed with ZSTD";
  10133. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  10134. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  10135. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  10136. 0x20, 0x5a, 0x53, 0x54, 0x44};
  10137. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  10138. std::string decompressed_data;
  10139. {
  10140. httplib::detail::zstd_decompressor decompressor;
  10141. bool result = decompressor.decompress(
  10142. compressed_data.data(), compressed_data.size(),
  10143. [&](const char *decompressed_data_chunk,
  10144. size_t decompressed_data_chunk_size) {
  10145. decompressed_data.insert(decompressed_data.size(),
  10146. decompressed_data_chunk,
  10147. decompressed_data_chunk_size);
  10148. return true;
  10149. });
  10150. ASSERT_TRUE(result);
  10151. }
  10152. ASSERT_EQ(original_text, decompressed_data);
  10153. }
  10154. #endif
  10155. // Sends a raw request to a server listening at HOST:PORT, writing it in
  10156. // separate chunks so that the server sees each part in its own read(). Used to
  10157. // place a read boundary at a specific offset of a request body.
  10158. static bool send_request_in_parts(time_t read_timeout_sec,
  10159. const std::vector<std::string> &parts,
  10160. std::string *resp = nullptr,
  10161. int port = PORT) {
  10162. auto error = Error::Success;
  10163. auto client_sock = detail::create_client_socket(
  10164. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10165. /*connection_timeout_sec=*/5, 0,
  10166. /*read_timeout_sec=*/5, 0,
  10167. /*write_timeout_sec=*/5, 0, std::string(), error);
  10168. if (client_sock == INVALID_SOCKET) { return false; }
  10169. auto ret = detail::process_client_socket(
  10170. client_sock, read_timeout_sec, 0, 0, 0, 0,
  10171. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  10172. for (size_t i = 0; i < parts.size(); i++) {
  10173. const auto &part = parts[i];
  10174. if (part.size() !=
  10175. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  10176. return false;
  10177. }
  10178. if (i + 1 < parts.size()) {
  10179. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10180. }
  10181. }
  10182. char buf[512];
  10183. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  10184. while (line_reader.getline()) {
  10185. if (resp) { *resp += line_reader.ptr(); }
  10186. }
  10187. return true;
  10188. });
  10189. detail::close_socket(client_sock);
  10190. return ret;
  10191. }
  10192. // Sends a raw request to a server listening at HOST:PORT.
  10193. static bool send_request(time_t read_timeout_sec, const std::string &req,
  10194. std::string *resp = nullptr, int port = PORT) {
  10195. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  10196. }
  10197. #ifdef CPPHTTPLIB_SSL_ENABLED
  10198. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  10199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10200. ASSERT_TRUE(svr.is_valid());
  10201. svr.set_read_timeout(1, 0);
  10202. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10203. auto se = detail::scope_exit([&] {
  10204. svr.stop();
  10205. t.join();
  10206. ASSERT_FALSE(svr.is_running());
  10207. });
  10208. svr.wait_until_ready();
  10209. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  10210. // keeps each wait well within the read timeout. The server gives up a
  10211. // second in, so the bytes sent after that fail.
  10212. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  10213. parts.resize(26, std::string(1, '\0'));
  10214. EXPECT_FALSE(send_request_in_parts(5, parts));
  10215. }
  10216. #endif
  10217. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10218. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  10219. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  10220. const std::vector<std::string> &parts,
  10221. std::string *resp = nullptr,
  10222. int port = PORT) {
  10223. auto error = Error::Success;
  10224. auto sock = detail::create_client_socket(
  10225. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10226. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  10227. /*write_timeout_sec=*/5, 0, std::string(), error);
  10228. if (sock == INVALID_SOCKET) { return false; }
  10229. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10230. auto ctx = SSL_CTX_new(TLS_client_method());
  10231. auto ssl = SSL_new(ctx);
  10232. auto ssl_se = detail::scope_exit([&] {
  10233. SSL_free(ssl);
  10234. SSL_CTX_free(ctx);
  10235. });
  10236. SSL_set_fd(ssl, static_cast<int>(sock));
  10237. if (SSL_connect(ssl) != 1) { return false; }
  10238. for (size_t i = 0; i < parts.size(); i++) {
  10239. const auto &part = parts[i];
  10240. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  10241. static_cast<int>(part.size())) {
  10242. return false;
  10243. }
  10244. if (i + 1 < parts.size()) {
  10245. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10246. }
  10247. }
  10248. char buf[512];
  10249. int n;
  10250. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10251. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  10252. }
  10253. return true;
  10254. }
  10255. #endif
  10256. // The request line, then a header value a byte at a time.
  10257. static std::vector<std::string> slow_request_head_parts() {
  10258. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  10259. parts.resize(26, "a");
  10260. parts.emplace_back("\r\n\r\n");
  10261. return parts;
  10262. }
  10263. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  10264. // within the one-second read timeout. The server gives up a second in, before
  10265. // the head is complete.
  10266. static void
  10267. expect_slow_request_head_dropped(Server &svr,
  10268. const std::function<std::string()> &send) {
  10269. std::atomic<bool> handled(false);
  10270. svr.Get("/", [&](const Request &, Response &res) {
  10271. handled = true;
  10272. res.set_content("ok", "text/plain");
  10273. });
  10274. svr.set_read_timeout(1, 0);
  10275. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10276. auto se = detail::scope_exit([&] {
  10277. svr.stop();
  10278. t.join();
  10279. ASSERT_FALSE(svr.is_running());
  10280. });
  10281. svr.wait_until_ready();
  10282. auto resp = send();
  10283. EXPECT_FALSE(handled);
  10284. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  10285. }
  10286. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10287. Server svr;
  10288. expect_slow_request_head_dropped(svr, [] {
  10289. std::string resp;
  10290. send_request_in_parts(5, slow_request_head_parts(), &resp);
  10291. return resp;
  10292. });
  10293. }
  10294. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10295. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10296. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10297. ASSERT_TRUE(svr.is_valid());
  10298. expect_slow_request_head_dropped(svr, [] {
  10299. std::string resp;
  10300. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  10301. return resp;
  10302. });
  10303. }
  10304. #endif
  10305. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  10306. Server svr;
  10307. std::string header_value;
  10308. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  10309. header_value = req.get_header_value("foo");
  10310. res.set_content("ok", "text/plain");
  10311. });
  10312. thread t = thread([&] { svr.listen(HOST, PORT); });
  10313. auto se = detail::scope_exit([&] {
  10314. svr.stop();
  10315. t.join();
  10316. ASSERT_FALSE(svr.is_running());
  10317. });
  10318. svr.wait_until_ready();
  10319. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  10320. // like characters are not treated the same - use vertical tab and escape.
  10321. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  10322. "foo: \t \v bar \x1B\t \r\n"
  10323. "Connection: close\r\n"
  10324. "\r\n";
  10325. std::string res;
  10326. ASSERT_TRUE(send_request(5, req, &res));
  10327. EXPECT_EQ(header_value, "");
  10328. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10329. }
  10330. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  10331. Server svr;
  10332. std::string received;
  10333. svr.Get("/order", [&](const Request &req, Response &res) {
  10334. received = entries_to_string(req.headers);
  10335. res.set_content("ok", "text/plain");
  10336. });
  10337. auto port = svr.bind_to_any_port(HOST);
  10338. thread t = thread([&] { svr.listen_after_bind(); });
  10339. auto se = detail::scope_exit([&] {
  10340. svr.stop();
  10341. t.join();
  10342. ASSERT_FALSE(svr.is_running());
  10343. });
  10344. svr.wait_until_ready();
  10345. const std::string req = "GET /order HTTP/1.1\r\n"
  10346. "Host: localhost\r\n"
  10347. "X-First: 1\r\n"
  10348. "X-Dup: a\r\n"
  10349. "X-Second: 2\r\n"
  10350. "X-Dup: b\r\n"
  10351. "Connection: close\r\n"
  10352. "\r\n";
  10353. std::string res;
  10354. ASSERT_TRUE(send_request(5, req, &res, port));
  10355. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10356. EXPECT_EQ(
  10357. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10358. received);
  10359. }
  10360. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10361. Server svr;
  10362. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10363. res.set_header("Set-Cookie", "first=1");
  10364. res.set_header("X-Between", "y");
  10365. res.set_header("Set-Cookie", "second=2");
  10366. res.set_content("ok", "text/plain");
  10367. });
  10368. auto port = svr.bind_to_any_port(HOST);
  10369. thread t = thread([&] { svr.listen_after_bind(); });
  10370. auto se = detail::scope_exit([&] {
  10371. svr.stop();
  10372. t.join();
  10373. ASSERT_FALSE(svr.is_running());
  10374. });
  10375. svr.wait_until_ready();
  10376. Client cli(HOST, port);
  10377. auto res = cli.Get("/cookies");
  10378. ASSERT_TRUE(res);
  10379. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10380. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10381. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10382. }
  10383. // A stream may send a byte at a time with a small extension on each chunk,
  10384. // however long it runs
  10385. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10386. Server svr;
  10387. svr.Post("/count", [](const Request &req, Response &res) {
  10388. res.set_content(std::to_string(req.body.size()), "text/plain");
  10389. });
  10390. auto port = svr.bind_to_any_port(HOST);
  10391. ASSERT_LT(0, port);
  10392. thread t = thread([&] { svr.listen_after_bind(); });
  10393. auto se = detail::scope_exit([&] {
  10394. svr.stop();
  10395. t.join();
  10396. ASSERT_FALSE(svr.is_running());
  10397. });
  10398. svr.wait_until_ready();
  10399. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10400. "\r\nTransfer-Encoding: chunked\r\n"
  10401. "Connection: close\r\n\r\n";
  10402. for (auto i = 0; i < 4096; i++) {
  10403. req += "1;a=b\r\nx\r\n";
  10404. }
  10405. req += "0\r\n\r\n";
  10406. std::string res;
  10407. ASSERT_TRUE(send_request(5, req, &res, port));
  10408. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10409. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10410. }
  10411. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10412. Server svr;
  10413. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10414. auto i = new int(0);
  10415. res.set_header("Trailer", "X-Safe, X-Reflected");
  10416. res.set_chunked_content_provider(
  10417. "text/plain",
  10418. [i](size_t /*offset*/, DataSink &sink) {
  10419. if (*i == 0) {
  10420. sink.os << "body";
  10421. } else {
  10422. Headers trailer;
  10423. // A valid trailer that must survive.
  10424. trailer.emplace("X-Safe", "safe");
  10425. // Attacker-controlled value carrying CR/LF (response splitting).
  10426. trailer.emplace("X-Reflected",
  10427. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10428. // Attacker-controlled name carrying CR/LF.
  10429. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10430. sink.done_with_trailer(trailer);
  10431. }
  10432. (*i)++;
  10433. return true;
  10434. },
  10435. [i](bool /*success*/) { delete i; });
  10436. });
  10437. thread t = thread([&] { svr.listen(HOST, PORT); });
  10438. auto se = detail::scope_exit([&] {
  10439. svr.stop();
  10440. t.join();
  10441. ASSERT_FALSE(svr.is_running());
  10442. });
  10443. svr.wait_until_ready();
  10444. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10445. "Host: " + HOST +
  10446. "\r\n"
  10447. "Connection: close\r\n"
  10448. "\r\n";
  10449. std::string res;
  10450. ASSERT_TRUE(send_request(5, req, &res));
  10451. // The injected fields must not appear anywhere in the raw response.
  10452. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10453. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10454. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10455. // Invalid trailers are dropped entirely, matching set_header().
  10456. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10457. // The valid trailer still passes through.
  10458. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10459. }
  10460. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10461. // A custom header writer gets only the fields the default one writes
  10462. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10463. std::string s;
  10464. for (const auto &h : hdrs) {
  10465. s += h.first + ": " + h.second + "\r\n";
  10466. }
  10467. s += "\r\n";
  10468. return strm.write(s.data(), s.size());
  10469. };
  10470. for (auto custom_writer : {false, true}) {
  10471. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10472. Server svr;
  10473. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10474. svr.set_post_routing_handler([](const Request &, Response &res) {
  10475. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10476. });
  10477. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10478. // res.headers is a public field an application can populate directly,
  10479. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10480. // A valid header that must survive.
  10481. res.headers.emplace("X-Safe", "safe");
  10482. // Attacker-controlled value carrying CR/LF (response splitting).
  10483. res.headers.emplace("X-Reflected",
  10484. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10485. // Attacker-controlled name carrying CR/LF.
  10486. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10487. res.set_content("body", "text/plain");
  10488. });
  10489. thread t = thread([&] { svr.listen(HOST, PORT); });
  10490. auto se = detail::scope_exit([&] {
  10491. svr.stop();
  10492. t.join();
  10493. ASSERT_FALSE(svr.is_running());
  10494. });
  10495. svr.wait_until_ready();
  10496. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10497. "Host: " + HOST +
  10498. "\r\n"
  10499. "Connection: close\r\n"
  10500. "\r\n";
  10501. std::string res;
  10502. ASSERT_TRUE(send_request(5, req, &res));
  10503. // The injected fields must not appear anywhere in the raw response.
  10504. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10505. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10506. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10507. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10508. // Invalid headers are dropped entirely, matching set_header().
  10509. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10510. // The valid header still passes through.
  10511. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10512. }
  10513. }
  10514. // Forward declaration: in split builds split.py strips `inline` and moves the
  10515. // definition into httplib.cc, so detail::write_request_line is not visible from
  10516. // the public httplib.h. Re-declaring it here lets the tests link against the
  10517. // symbol in both header-only and split builds.
  10518. namespace httplib {
  10519. namespace detail {
  10520. ssize_t write_request_line(Stream &strm, const std::string &method,
  10521. const std::string &path);
  10522. } // namespace detail
  10523. } // namespace httplib
  10524. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10525. // A well-formed target is written verbatim.
  10526. {
  10527. detail::BufferStream strm;
  10528. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10529. EXPECT_GT(n, 0);
  10530. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10531. }
  10532. // A target carrying CR/LF, SP or other control octets must be rejected
  10533. // before anything reaches the wire, otherwise it splits the request line and
  10534. // injects a header or a whole request.
  10535. const std::string evil_targets[] = {
  10536. "/a\r\nInjected: pwned",
  10537. "/a\rInjected",
  10538. "/a\nInjected",
  10539. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10540. "/a b",
  10541. "/a\tb",
  10542. "/a\x7f",
  10543. };
  10544. for (const auto &evil : evil_targets) {
  10545. detail::BufferStream strm;
  10546. auto n = detail::write_request_line(strm, "GET", evil);
  10547. EXPECT_LT(n, 0);
  10548. EXPECT_TRUE(strm.get_buffer().empty());
  10549. }
  10550. }
  10551. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10552. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10553. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10554. // target reaches write_request. The client must fail cleanly with
  10555. // Error::Write instead of putting a request-line-less, header-injecting
  10556. // request on the wire.
  10557. Server svr;
  10558. svr.Get("/a", [](const Request &, Response &res) {
  10559. res.set_content("ok", "text/plain");
  10560. });
  10561. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10562. auto se = detail::scope_exit([&] {
  10563. svr.stop();
  10564. thread.join();
  10565. ASSERT_FALSE(svr.is_running());
  10566. });
  10567. svr.wait_until_ready();
  10568. {
  10569. Client cli(HOST, PORT);
  10570. cli.set_path_encode(false);
  10571. // The request is rejected before anything is written, so the connection
  10572. // stays silent and the subsequent response read would otherwise block for
  10573. // the full default read timeout. Shorten it -- the assertion is on the
  10574. // error, not the timeout.
  10575. cli.set_read_timeout(1, 0);
  10576. auto res = cli.Get("/a\r\nInjected: pwned");
  10577. EXPECT_FALSE(res);
  10578. EXPECT_EQ(Error::Write, res.error());
  10579. }
  10580. }
  10581. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10582. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10583. // including extension methods.
  10584. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10585. for (const auto &method : good_methods) {
  10586. detail::BufferStream strm;
  10587. auto n = detail::write_request_line(strm, method, "/");
  10588. EXPECT_GT(n, 0);
  10589. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10590. }
  10591. // A method carrying CR/LF would split the request line and smuggle a whole
  10592. // request ahead of the real one. A space or an empty method corrupts the
  10593. // request line. All must be rejected before anything reaches the wire.
  10594. const std::string evil_methods[] = {
  10595. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10596. "GET\r\nInjected: pwned",
  10597. "GET\r",
  10598. "GET\n",
  10599. "GE T",
  10600. "",
  10601. };
  10602. for (const auto &evil : evil_methods) {
  10603. detail::BufferStream strm;
  10604. auto n = detail::write_request_line(strm, evil, "/");
  10605. EXPECT_LT(n, 0);
  10606. EXPECT_TRUE(strm.get_buffer().empty());
  10607. }
  10608. }
  10609. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10610. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10611. // through Client::send must fail with Error::Write and no request, neither
  10612. // the smuggled one nor the real one, may reach the server.
  10613. Server svr;
  10614. std::atomic<int> request_count(0);
  10615. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10616. request_count++;
  10617. res.status = StatusCode::OK_200;
  10618. return Server::HandlerResponse::Handled;
  10619. });
  10620. auto port = svr.bind_to_any_port(HOST);
  10621. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10622. auto se = detail::scope_exit([&] {
  10623. svr.stop();
  10624. thread.join();
  10625. ASSERT_FALSE(svr.is_running());
  10626. });
  10627. svr.wait_until_ready();
  10628. {
  10629. Client cli(HOST, port);
  10630. const std::string evil_methods[] = {
  10631. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10632. "GE T",
  10633. "",
  10634. };
  10635. for (const auto &evil : evil_methods) {
  10636. Request req;
  10637. req.method = evil;
  10638. req.path = "/";
  10639. auto res = cli.send(req);
  10640. EXPECT_FALSE(res);
  10641. EXPECT_EQ(Error::Write, res.error());
  10642. }
  10643. auto handle =
  10644. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10645. EXPECT_FALSE(handle.is_valid());
  10646. EXPECT_EQ(Error::Write, handle.error);
  10647. // A valid request on the same client still goes through.
  10648. auto res = cli.Get("/");
  10649. ASSERT_TRUE(res);
  10650. EXPECT_EQ(StatusCode::OK_200, res->status);
  10651. }
  10652. EXPECT_EQ(1, request_count.load());
  10653. }
  10654. // Sends a raw request and verifies that there isn't a crash or exception.
  10655. static void test_raw_request(const std::string &req,
  10656. std::string *out = nullptr) {
  10657. Server svr;
  10658. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10659. res.set_content("ok", "text/plain");
  10660. });
  10661. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10662. res.set_content("ok", "text/plain");
  10663. });
  10664. svr.Get("/header_field_value_check",
  10665. [&](const Request & /*req*/, Response &res) {
  10666. res.set_content("ok", "text/plain");
  10667. });
  10668. svr.CustomRoute("PROPFIND", "/dav",
  10669. [&](const Request & /*req*/, Response &res) {
  10670. res.status = StatusCode::MultiStatus_207;
  10671. });
  10672. // Server read timeout must be longer than the client read timeout for the
  10673. // bug to reproduce, probably to force the server to process a request
  10674. // without a trailing blank line.
  10675. const time_t client_read_timeout_sec = 1;
  10676. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10677. bool listen_thread_ok = false;
  10678. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10679. auto se = detail::scope_exit([&] {
  10680. svr.stop();
  10681. t.join();
  10682. ASSERT_FALSE(svr.is_running());
  10683. EXPECT_TRUE(listen_thread_ok);
  10684. });
  10685. svr.wait_until_ready();
  10686. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10687. }
  10688. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10689. // A certain header line causes an exception if the header property is parsed
  10690. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10691. test_raw_request(
  10692. "GET /hi HTTP/1.1\r\n"
  10693. " : "
  10694. " "
  10695. " ");
  10696. }
  10697. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10698. // A certain header line causes an exception if the header property *name* is
  10699. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10700. // greedy matcher and requires backtracking when there are a lot of ":"
  10701. // characters.
  10702. // This occurs with libc++ but not libstdc++.
  10703. test_raw_request(
  10704. "GET /hi HTTP/1.1\r\n"
  10705. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10706. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10707. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10708. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10709. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10710. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10711. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10712. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10713. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10714. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10715. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10716. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10717. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10718. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10719. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10720. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10721. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10722. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10723. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10724. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10725. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10726. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10727. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10728. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10729. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10730. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10731. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10732. "&&&%%%");
  10733. }
  10734. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10735. // Make sure this doesn't crash the server.
  10736. // In a previous version of the header line regex, the "\r" rendered the line
  10737. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10738. // a new position where the leading white space ended and the field value
  10739. // began.
  10740. // The crash occurs with libc++ but not libstdc++.
  10741. test_raw_request("GET /hi HTTP/1.1\r\n"
  10742. "a:" +
  10743. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10744. "\r\n"
  10745. "\r\n");
  10746. }
  10747. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10748. const char *rejected[] = {
  10749. // RFC 9112 §3: one SP between the parts, and nothing else
  10750. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10751. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10752. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10753. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10754. // A request-target has no fragment
  10755. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10756. // An HTTP/1.1 request needs a Host
  10757. "GET /hi HTTP/1.1\r\n\r\n",
  10758. };
  10759. for (auto request : rejected) {
  10760. std::string out;
  10761. test_raw_request(request, &out);
  10762. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10763. }
  10764. std::string out;
  10765. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10766. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10767. }
  10768. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10769. // RFC 9112 §6.1
  10770. const char *requests[] = {
  10771. "PUT /put_hi HTTP/1.1\r\n"
  10772. "Host: localhost\r\n"
  10773. "Content-Length: 0\r\n"
  10774. "Transfer-Encoding: chunked\r\n"
  10775. "\r\n"
  10776. "0\r\n\r\n",
  10777. "PUT /put_hi HTTP/1.0\r\n"
  10778. "Connection: keep-alive\r\n"
  10779. "Transfer-Encoding: chunked\r\n"
  10780. "\r\n"
  10781. "0\r\n\r\n",
  10782. };
  10783. for (auto request : requests) {
  10784. std::string out;
  10785. test_raw_request(request, &out);
  10786. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10787. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10788. }
  10789. }
  10790. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10791. std::string out;
  10792. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10793. "Content-Type: text/plain\r\n"
  10794. "Transfer-Encoding: chunked\r\n"
  10795. "\r\n"
  10796. "nothex\r\n",
  10797. &out);
  10798. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10799. }
  10800. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10801. std::string out;
  10802. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10803. "Content-Type: text/plain\r\n"
  10804. "Transfer-Encoding: chunked\r\n"
  10805. "\r\n"
  10806. "3\r\n"
  10807. "xyz\r\n"
  10808. "NaN\r\n",
  10809. &out);
  10810. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10811. }
  10812. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10813. std::string out;
  10814. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10815. "Content-Type: text/plain\r\n"
  10816. "Transfer-Encoding: chunked\r\n"
  10817. "\r\n"
  10818. // Length is too large for 64 bits.
  10819. "1ffffffffffffffff\r\n"
  10820. "xyz\r\n",
  10821. &out);
  10822. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10823. }
  10824. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10825. test_raw_request("GET /hi HTTP/1.1\r\n"
  10826. "Content-Type: text/plain\r\n\r");
  10827. }
  10828. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10829. std::string out;
  10830. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10831. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10832. }
  10833. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10834. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10835. std::string out;
  10836. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10837. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10838. }
  10839. }
  10840. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10841. std::string out;
  10842. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10843. "Host: localhost\r\n"
  10844. "Connection: close\r\n\r\n",
  10845. &out);
  10846. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10847. }
  10848. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10849. Server svr;
  10850. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10851. EXPECT_TRUE(!req.remote_addr.empty());
  10852. });
  10853. thread t = thread([&] { svr.listen(HOST, PORT); });
  10854. auto se = detail::scope_exit([&] {
  10855. svr.stop();
  10856. t.join();
  10857. ASSERT_FALSE(svr.is_running());
  10858. });
  10859. svr.wait_until_ready();
  10860. // Send an invalid request line to trigger Bad Request
  10861. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10862. std::string out;
  10863. ASSERT_TRUE(send_request(5, bad_req, &out));
  10864. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10865. }
  10866. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10867. // answered right away rather than blocking on a read that waits for EOF.
  10868. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10869. std::string out;
  10870. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10871. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10872. }
  10873. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10874. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10875. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10876. for (const auto *method : methods) {
  10877. Server svr;
  10878. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10879. EXPECT_FALSE(svr.is_valid()) << method;
  10880. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10881. }
  10882. }
  10883. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10884. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10885. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10886. for (const auto *method : methods) {
  10887. Server svr;
  10888. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10889. EXPECT_FALSE(svr.is_valid()) << method;
  10890. }
  10891. }
  10892. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10893. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10894. "COPY", "MOVE", "LOCK",
  10895. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10896. Server svr;
  10897. for (const auto *method : methods) {
  10898. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10899. }
  10900. EXPECT_TRUE(svr.is_valid());
  10901. }
  10902. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10903. Server svr;
  10904. svr.CustomRoute("POST", "/x",
  10905. [](const Request &, Response &, const ContentReader &) {});
  10906. EXPECT_FALSE(svr.is_valid());
  10907. }
  10908. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10909. Server svr;
  10910. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10911. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10912. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10913. EXPECT_FALSE(svr.is_valid());
  10914. }
  10915. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10916. Server svr;
  10917. auto captured = Error::Success;
  10918. svr.set_error_logger(
  10919. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10920. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10921. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10922. }
  10923. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10924. std::string out;
  10925. std::string request(
  10926. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10927. test_raw_request(request, &out);
  10928. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10929. }
  10930. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10931. std::string out;
  10932. std::string request(
  10933. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10934. test_raw_request(request, &out);
  10935. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10936. }
  10937. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10938. std::string out;
  10939. std::string request(
  10940. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10941. test_raw_request(request, &out);
  10942. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10943. }
  10944. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10945. std::string out;
  10946. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10947. "Host: localhost\r\n"
  10948. "Test: \r\n\r\n",
  10949. &out);
  10950. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10951. }
  10952. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10953. Server svr;
  10954. std::string x_custom;
  10955. std::string cookie;
  10956. std::string xff;
  10957. std::string x_unicode;
  10958. std::string x_iis;
  10959. svr.Get("/check", [&](const Request &req, Response &res) {
  10960. x_custom = req.get_header_value("X-Custom");
  10961. cookie = req.get_header_value("Cookie");
  10962. xff = req.get_header_value("X-Forwarded-For");
  10963. x_unicode = req.get_header_value("X-Unicode");
  10964. x_iis = req.get_header_value("X-IIS");
  10965. res.set_content("ok", "text/plain");
  10966. });
  10967. thread t = thread([&] { svr.listen(HOST, PORT); });
  10968. auto se = detail::scope_exit([&] {
  10969. svr.stop();
  10970. t.join();
  10971. ASSERT_FALSE(svr.is_running());
  10972. });
  10973. svr.wait_until_ready();
  10974. const std::string req = "GET /check HTTP/1.1\r\n"
  10975. "Host: localhost\r\n"
  10976. "X-Custom: a%0D%0AInjected: b\r\n"
  10977. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10978. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10979. "X-Unicode: %E3%81%82\r\n"
  10980. "X-IIS: %u00E9\r\n"
  10981. "Connection: close\r\n"
  10982. "\r\n";
  10983. std::string res;
  10984. ASSERT_TRUE(send_request(5, req, &res));
  10985. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10986. // Every value must be returned verbatim (wire form), with no decoding.
  10987. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10988. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10989. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10990. EXPECT_EQ("%E3%81%82", x_unicode);
  10991. EXPECT_EQ("%u00E9", x_iis);
  10992. }
  10993. // Applications that previously relied on automatic percent-decoding can
  10994. // reproduce the old behavior by explicitly calling decode_path_component()
  10995. // or, for RFC 3986 conformance, decode_uri_component().
  10996. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10997. Server svr;
  10998. std::string decoded;
  10999. svr.Get("/check", [&](const Request &req, Response &res) {
  11000. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  11001. res.set_content("ok", "text/plain");
  11002. });
  11003. thread t = thread([&] { svr.listen(HOST, PORT); });
  11004. auto se = detail::scope_exit([&] {
  11005. svr.stop();
  11006. t.join();
  11007. ASSERT_FALSE(svr.is_running());
  11008. });
  11009. svr.wait_until_ready();
  11010. const std::string req = "GET /check HTTP/1.1\r\n"
  11011. "Host: localhost\r\n"
  11012. "X-Custom: hello%20world\r\n"
  11013. "Connection: close\r\n"
  11014. "\r\n";
  11015. std::string res;
  11016. ASSERT_TRUE(send_request(5, req, &res));
  11017. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  11018. EXPECT_EQ("hello world", decoded);
  11019. }
  11020. // Regression test for #2033. Browsers send Referer values that include
  11021. // percent-encoded characters such as %0A inside the URL. Decoding the
  11022. // header value would either trip the post-decode CR/LF/NUL guard (the
  11023. // original bug, returning 400) or, after that guard was relaxed, silently
  11024. // store a literal LF — both unacceptable. The wire form must round-trip.
  11025. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  11026. Server svr;
  11027. std::string referer;
  11028. svr.Get("/check", [&](const Request &req, Response &res) {
  11029. referer = req.get_header_value("Referer");
  11030. res.set_content("ok", "text/plain");
  11031. });
  11032. thread t = thread([&] { svr.listen(HOST, PORT); });
  11033. auto se = detail::scope_exit([&] {
  11034. svr.stop();
  11035. t.join();
  11036. ASSERT_FALSE(svr.is_running());
  11037. });
  11038. svr.wait_until_ready();
  11039. const std::string req = "GET /check HTTP/1.1\r\n"
  11040. "Host: localhost\r\n"
  11041. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  11042. "Connection: close\r\n"
  11043. "\r\n";
  11044. std::string res;
  11045. ASSERT_TRUE(send_request(5, req, &res));
  11046. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  11047. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  11048. }
  11049. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  11050. Server svr;
  11051. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  11052. res.set_header("Cache-Control", "no-cache");
  11053. res.set_chunked_content_provider(
  11054. "text/event-stream", [](size_t offset, DataSink &sink) {
  11055. std::string s = "data:";
  11056. s += std::to_string(offset);
  11057. s += "\n\n";
  11058. auto ret = sink.write(s.data(), s.size());
  11059. EXPECT_TRUE(ret);
  11060. std::this_thread::sleep_for(std::chrono::seconds(1));
  11061. return true;
  11062. });
  11063. });
  11064. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11065. svr.wait_until_ready();
  11066. Client client(HOST, PORT);
  11067. const Headers headers = {{"Accept", "text/event-stream"}};
  11068. auto get_thread = std::thread([&client, &headers]() {
  11069. auto res = client.Get(
  11070. "/events", headers,
  11071. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  11072. });
  11073. auto se = detail::scope_exit([&] {
  11074. svr.stop();
  11075. get_thread.join();
  11076. listen_thread.join();
  11077. ASSERT_FALSE(svr.is_running());
  11078. });
  11079. // Give GET time to get a few messages.
  11080. std::this_thread::sleep_for(std::chrono::seconds(2));
  11081. }
  11082. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  11083. httplib::Server svr;
  11084. svr.Post("/hi",
  11085. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11086. res.status = StatusCode::OK_200;
  11087. });
  11088. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11089. svr.wait_until_ready();
  11090. Client cli(HOST, PORT);
  11091. auto res = cli.Post("/hi", "data", "text/plain");
  11092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11093. EXPECT_EQ(StatusCode::OK_200, res->status);
  11094. svr.stop();
  11095. thread.join();
  11096. ASSERT_FALSE(svr.is_running());
  11097. res = cli.Post("/hi", "data", "text/plain");
  11098. ASSERT_FALSE(res);
  11099. }
  11100. TEST(ServerStopTest, ListenFailure) {
  11101. Server svr;
  11102. auto t = thread([&]() {
  11103. auto ret = svr.listen("????", PORT);
  11104. EXPECT_FALSE(ret);
  11105. });
  11106. svr.wait_until_ready();
  11107. svr.stop();
  11108. t.join();
  11109. }
  11110. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11111. TEST(ServerStopTest, Decommision) {
  11112. Server svr;
  11113. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  11114. for (int i = 0; i < 4; i++) {
  11115. auto is_even = !(i % 2);
  11116. std::thread t{[&] {
  11117. try {
  11118. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11119. if (is_even) {
  11120. throw std::runtime_error("Some thing that happens to go wrong.");
  11121. }
  11122. svr.listen(HOST, PORT);
  11123. } catch (...) { svr.decommission(); }
  11124. }};
  11125. svr.wait_until_ready();
  11126. // Server is up
  11127. {
  11128. Client cli(HOST, PORT);
  11129. auto res = cli.Get("/hi");
  11130. if (is_even) {
  11131. EXPECT_FALSE(res);
  11132. } else {
  11133. EXPECT_TRUE(res);
  11134. EXPECT_EQ("hi...", res->body);
  11135. }
  11136. }
  11137. svr.stop();
  11138. t.join();
  11139. // Server is down...
  11140. {
  11141. Client cli(HOST, PORT);
  11142. auto res = cli.Get("/hi");
  11143. EXPECT_FALSE(res);
  11144. }
  11145. }
  11146. }
  11147. #endif
  11148. // Helper function for string body upload progress tests
  11149. template <typename SetupHandler, typename ClientCall>
  11150. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  11151. ClientCall &&client_call,
  11152. const string &body) {
  11153. Server svr;
  11154. setup_handler(svr);
  11155. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11156. auto se = detail::scope_exit([&] {
  11157. svr.stop();
  11158. t.join();
  11159. });
  11160. svr.wait_until_ready();
  11161. Client cli(HOST, PORT);
  11162. vector<uint64_t> progress_values;
  11163. bool progress_called = false;
  11164. auto res =
  11165. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  11166. progress_values.push_back(current);
  11167. progress_called = true;
  11168. return true;
  11169. });
  11170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11171. EXPECT_EQ(200, res->status);
  11172. EXPECT_TRUE(progress_called);
  11173. }
  11174. TEST(UploadProgressTest, PostStringBodyBasic) {
  11175. TestStringBodyUploadProgress(
  11176. [](Server &svr) {
  11177. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11178. res.set_content("received", "text/plain");
  11179. });
  11180. },
  11181. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11182. return cli.Post("/test", body, "text/plain", progress_callback);
  11183. },
  11184. "test data for upload progress");
  11185. }
  11186. TEST(UploadProgressTest, PutStringBodyBasic) {
  11187. TestStringBodyUploadProgress(
  11188. [](Server &svr) {
  11189. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  11190. res.set_content("put received", "text/plain");
  11191. });
  11192. },
  11193. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11194. return cli.Put("/test", body, "text/plain", progress_callback);
  11195. },
  11196. "put test data for upload progress");
  11197. }
  11198. TEST(UploadProgressTest, PatchStringBodyBasic) {
  11199. TestStringBodyUploadProgress(
  11200. [](Server &svr) {
  11201. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  11202. res.set_content("patch received", "text/plain");
  11203. });
  11204. },
  11205. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11206. return cli.Patch("/test", body, "text/plain", progress_callback);
  11207. },
  11208. "patch test data for upload progress");
  11209. }
  11210. // Helper function for content provider upload progress tests
  11211. template <typename SetupHandler, typename ClientCall>
  11212. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  11213. ClientCall &&client_call) {
  11214. Server svr;
  11215. setup_handler(svr);
  11216. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11217. auto se = detail::scope_exit([&] {
  11218. svr.stop();
  11219. t.join();
  11220. });
  11221. svr.wait_until_ready();
  11222. Client cli(HOST, PORT);
  11223. vector<uint64_t> progress_values;
  11224. auto res =
  11225. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  11226. progress_values.push_back(current);
  11227. return true;
  11228. });
  11229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11230. EXPECT_EQ(200, res->status);
  11231. EXPECT_FALSE(progress_values.empty());
  11232. }
  11233. TEST(UploadProgressTest, PostContentProviderProgress) {
  11234. TestContentProviderUploadProgress(
  11235. [](Server &svr) {
  11236. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11237. res.set_content("provider received", "text/plain");
  11238. });
  11239. },
  11240. [](Client &cli, UploadProgress progress_callback) {
  11241. return cli.Post(
  11242. "/test", 9,
  11243. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  11244. sink.os << "test data";
  11245. return true;
  11246. },
  11247. "text/plain", progress_callback);
  11248. });
  11249. }
  11250. // Helper function for multipart upload progress tests
  11251. template <typename SetupHandler, typename ClientCall>
  11252. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  11253. ClientCall &&client_call,
  11254. const string &endpoint) {
  11255. Server svr;
  11256. setup_handler(svr);
  11257. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11258. auto se = detail::scope_exit([&] {
  11259. svr.stop();
  11260. t.join();
  11261. });
  11262. svr.wait_until_ready();
  11263. Client cli(HOST, PORT);
  11264. vector<uint64_t> progress_values;
  11265. UploadFormDataItems items = {
  11266. {"field1", "value1", "", ""},
  11267. {"field2", "longer value for progress tracking test", "", ""},
  11268. {"file1", "file content data for upload progress", "test.txt",
  11269. "text/plain"}};
  11270. auto res = client_call(cli, endpoint, items,
  11271. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11272. progress_values.push_back(current);
  11273. return true;
  11274. });
  11275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11276. EXPECT_EQ(200, res->status);
  11277. EXPECT_FALSE(progress_values.empty());
  11278. }
  11279. TEST(UploadProgressTest, PostMultipartProgress) {
  11280. TestMultipartUploadProgress(
  11281. [](Server &svr) {
  11282. svr.Post("/multipart", [](const Request &req, Response &res) {
  11283. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  11284. res.set_content("multipart received", "text/plain");
  11285. });
  11286. },
  11287. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  11288. UploadProgress progress_callback) {
  11289. return cli.Post(endpoint, items, progress_callback);
  11290. },
  11291. "/multipart");
  11292. }
  11293. // Helper function for basic download progress tests
  11294. template <typename SetupHandler, typename ClientCall>
  11295. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  11296. ClientCall &&client_call, const string &endpoint,
  11297. size_t expected_content_size) {
  11298. Server svr;
  11299. setup_handler(svr);
  11300. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11301. auto se = detail::scope_exit([&] {
  11302. svr.stop();
  11303. t.join();
  11304. });
  11305. svr.wait_until_ready();
  11306. Client cli(HOST, PORT);
  11307. vector<uint64_t> progress_values;
  11308. auto res = client_call(cli, endpoint,
  11309. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11310. progress_values.push_back(current);
  11311. return true;
  11312. });
  11313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11314. EXPECT_EQ(200, res->status);
  11315. EXPECT_FALSE(progress_values.empty());
  11316. EXPECT_EQ(expected_content_size, res->body.size());
  11317. }
  11318. TEST(DownloadProgressTest, GetBasic) {
  11319. TestBasicDownloadProgress(
  11320. [](Server &svr) {
  11321. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  11322. string content(1000, 'D');
  11323. res.set_content(content, "text/plain");
  11324. });
  11325. },
  11326. [](Client &cli, const string &endpoint,
  11327. DownloadProgress progress_callback) {
  11328. return cli.Get(endpoint, progress_callback);
  11329. },
  11330. "/download", 1000u);
  11331. }
  11332. // Helper function for content receiver download progress tests
  11333. template <typename SetupHandler, typename ClientCall>
  11334. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  11335. ClientCall &&client_call,
  11336. const string &endpoint,
  11337. size_t expected_content_size) {
  11338. Server svr;
  11339. setup_handler(svr);
  11340. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11341. auto se = detail::scope_exit([&] {
  11342. svr.stop();
  11343. t.join();
  11344. });
  11345. svr.wait_until_ready();
  11346. Client cli(HOST, PORT);
  11347. vector<uint64_t> progress_values;
  11348. string received_body;
  11349. auto res = client_call(
  11350. cli, endpoint,
  11351. [&](const char *data, size_t data_length) -> bool {
  11352. received_body.append(data, data_length);
  11353. return true;
  11354. },
  11355. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11356. progress_values.push_back(current);
  11357. return true;
  11358. });
  11359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11360. EXPECT_EQ(200, res->status);
  11361. EXPECT_FALSE(progress_values.empty());
  11362. EXPECT_EQ(expected_content_size, received_body.size());
  11363. EXPECT_TRUE(res->body.empty());
  11364. }
  11365. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11366. TestContentReceiverDownloadProgress(
  11367. [](Server &svr) {
  11368. svr.Get("/download-receiver",
  11369. [](const Request & /*req*/, Response &res) {
  11370. string content(2000, 'R');
  11371. res.set_content(content, "text/plain");
  11372. });
  11373. },
  11374. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11375. DownloadProgress progress_callback) {
  11376. return cli.Get(endpoint, content_receiver, progress_callback);
  11377. },
  11378. "/download-receiver", 2000u);
  11379. }
  11380. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11381. // A provider reaching a pass with nothing to hand over - an empty buffer
  11382. // popped off a queue, say - must not be taken to mean the body is finished.
  11383. // It used to end the loop with the terminating chunk unwritten while the
  11384. // server still considered the response complete, so the peer waited for an
  11385. // end that never arrived.
  11386. Server svr;
  11387. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11388. auto step = std::make_shared<int>(0);
  11389. res.set_chunked_content_provider("text/plain",
  11390. [step](size_t /*offset*/, DataSink &sink) {
  11391. switch ((*step)++) {
  11392. case 0: sink.write("", 0); break;
  11393. case 1: sink.write("hello", 5); break;
  11394. default: sink.done(); break;
  11395. }
  11396. return true;
  11397. });
  11398. });
  11399. auto port = svr.bind_to_any_port(HOST);
  11400. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11401. auto listen_se = detail::scope_exit([&] {
  11402. svr.stop();
  11403. listen_thread.join();
  11404. ASSERT_FALSE(svr.is_running());
  11405. });
  11406. svr.wait_until_ready();
  11407. Client cli(HOST, port);
  11408. // Without the fix the body is never terminated, so bound the wait rather
  11409. // than letting the test hang on the default read timeout.
  11410. cli.set_read_timeout(5, 0);
  11411. auto res = cli.Get("/stream");
  11412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11413. EXPECT_EQ(StatusCode::OK_200, res->status);
  11414. EXPECT_EQ("hello", res->body);
  11415. }
  11416. TEST(StreamingTest, NoContentLengthStreaming) {
  11417. Server svr;
  11418. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11419. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11420. if (offset < 6) {
  11421. sink.os << (offset < 3 ? "a" : "b");
  11422. } else {
  11423. sink.done();
  11424. }
  11425. return true;
  11426. });
  11427. });
  11428. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11429. auto listen_se = detail::scope_exit([&] {
  11430. svr.stop();
  11431. listen_thread.join();
  11432. ASSERT_FALSE(svr.is_running());
  11433. });
  11434. svr.wait_until_ready();
  11435. Client client(HOST, PORT);
  11436. auto get_thread = std::thread([&client]() {
  11437. std::string s;
  11438. auto res =
  11439. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11440. s += std::string(data, len);
  11441. return true;
  11442. });
  11443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11444. EXPECT_EQ(StatusCode::OK_200, res->status);
  11445. EXPECT_EQ("aaabbb", s);
  11446. });
  11447. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11448. // Give GET time to get a few messages.
  11449. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11450. }
  11451. TEST(MountTest, Unmount) {
  11452. Server svr;
  11453. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11454. auto se = detail::scope_exit([&] {
  11455. svr.stop();
  11456. listen_thread.join();
  11457. ASSERT_FALSE(svr.is_running());
  11458. });
  11459. svr.wait_until_ready();
  11460. Client cli("localhost", PORT);
  11461. svr.set_mount_point("/mount2", "./www2");
  11462. auto res = cli.Get("/");
  11463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11465. res = cli.Get("/mount2/dir/test.html");
  11466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11467. EXPECT_EQ(StatusCode::OK_200, res->status);
  11468. svr.set_mount_point("/", "./www");
  11469. res = cli.Get("/dir/");
  11470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11471. EXPECT_EQ(StatusCode::OK_200, res->status);
  11472. svr.remove_mount_point("/");
  11473. res = cli.Get("/dir/");
  11474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11475. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11476. svr.remove_mount_point("/mount2");
  11477. res = cli.Get("/mount2/dir/test.html");
  11478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11480. }
  11481. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11482. Server svr;
  11483. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11484. svr.Get("/api/hello", [](const Request &, Response &res) {
  11485. res.set_content("api", "text/plain");
  11486. });
  11487. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11488. auto se = detail::scope_exit([&] {
  11489. svr.stop();
  11490. listen_thread.join();
  11491. ASSERT_FALSE(svr.is_running());
  11492. });
  11493. svr.wait_until_ready();
  11494. Client cli(HOST, PORT);
  11495. auto res = cli.Get("/dir/test.html");
  11496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11497. EXPECT_EQ(StatusCode::OK_200, res->status);
  11498. res = cli.Get("/api/hello");
  11499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11500. EXPECT_EQ(StatusCode::OK_200, res->status);
  11501. EXPECT_EQ("api", res->body);
  11502. }
  11503. TEST(MountTest, PathSegmentBoundary) {
  11504. Server svr;
  11505. svr.set_mount_point("/mount2", "./www2");
  11506. svr.set_mount_point("/", "./www");
  11507. auto port = svr.bind_to_any_port(HOST);
  11508. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11509. auto se = detail::scope_exit([&] {
  11510. svr.stop();
  11511. listen_thread.join();
  11512. ASSERT_FALSE(svr.is_running());
  11513. });
  11514. svr.wait_until_ready();
  11515. Client cli(HOST, port);
  11516. auto res = cli.Get("/mount2/dir/test.html");
  11517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11518. EXPECT_EQ(StatusCode::OK_200, res->status);
  11519. // "/mount2" must not match part-way through a path segment.
  11520. res = cli.Get("/mount2dir/test.html");
  11521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11522. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11523. // A mount point ending in '/' keeps matching every path below it.
  11524. res = cli.Get("/dir/test.html");
  11525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11526. EXPECT_EQ(StatusCode::OK_200, res->status);
  11527. }
  11528. TEST(MountTest, Redicect) {
  11529. Server svr;
  11530. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11531. auto se = detail::scope_exit([&] {
  11532. svr.stop();
  11533. listen_thread.join();
  11534. ASSERT_FALSE(svr.is_running());
  11535. });
  11536. svr.set_mount_point("/", "./www");
  11537. svr.wait_until_ready();
  11538. Client cli("localhost", PORT);
  11539. auto res = cli.Get("/dir/");
  11540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11541. EXPECT_EQ(StatusCode::OK_200, res->status);
  11542. res = cli.Get("/dir");
  11543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11544. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11545. res = cli.Get("/file");
  11546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11547. EXPECT_EQ(StatusCode::OK_200, res->status);
  11548. res = cli.Get("/file/");
  11549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11550. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11551. cli.set_follow_location(true);
  11552. res = cli.Get("/dir");
  11553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11554. EXPECT_EQ(StatusCode::OK_200, res->status);
  11555. }
  11556. TEST(MountTest, MultibytesPathName) {
  11557. Server svr;
  11558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11559. auto se = detail::scope_exit([&] {
  11560. svr.stop();
  11561. listen_thread.join();
  11562. ASSERT_FALSE(svr.is_running());
  11563. });
  11564. svr.set_mount_point("/", "./www");
  11565. svr.wait_until_ready();
  11566. Client cli("localhost", PORT);
  11567. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11569. EXPECT_EQ(StatusCode::OK_200, res->status);
  11570. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11571. }
  11572. // A mount point serves no path with an empty segment or one ending in '.' or
  11573. // a space, so a guard in the pre-routing handler sees the path of every file
  11574. // that is served
  11575. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11576. Server svr;
  11577. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11578. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11579. if (req.path == "/dir/test.html") {
  11580. res.status = StatusCode::Unauthorized_401;
  11581. return Server::HandlerResponse::Handled;
  11582. }
  11583. return Server::HandlerResponse::Unhandled;
  11584. });
  11585. auto port = svr.bind_to_any_port(HOST);
  11586. ASSERT_LT(0, port);
  11587. thread t = thread([&] { svr.listen_after_bind(); });
  11588. auto se = detail::scope_exit([&] {
  11589. svr.stop();
  11590. t.join();
  11591. ASSERT_FALSE(svr.is_running());
  11592. });
  11593. svr.wait_until_ready();
  11594. Client cli(HOST, port);
  11595. for (auto path :
  11596. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11597. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11598. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11599. "/dir/test.html%3A%3A$DATA"}) {
  11600. SCOPED_TRACE(path);
  11601. auto res = cli.Get(path);
  11602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11603. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11604. }
  11605. }
  11606. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11607. Server svr;
  11608. svr.set_mount_point("/", "./www");
  11609. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11610. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11611. auto port = svr.bind_to_any_port(HOST);
  11612. ASSERT_GT(port, 0);
  11613. thread t = thread([&] { svr.listen_after_bind(); });
  11614. auto se = detail::scope_exit([&] {
  11615. svr.stop();
  11616. t.join();
  11617. ASSERT_FALSE(svr.is_running());
  11618. });
  11619. svr.wait_until_ready();
  11620. Client cli(HOST, port);
  11621. auto res = cli.Get("/dir/test.abcde");
  11622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11623. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11624. res = cli.Get("/dir/test.html");
  11625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11626. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11627. }
  11628. #ifdef _WIN32
  11629. // Issue #2435: mmap::open() must succeed even when another handle holds
  11630. // the file open for writing (e.g. an active log file).
  11631. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11632. const char *path = "mmap_concurrent_writer_test.txt";
  11633. const char *content = "hello";
  11634. {
  11635. std::ofstream f(path, std::ios::binary);
  11636. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11637. }
  11638. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11639. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11640. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11641. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11642. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11643. detail::mmap m(path);
  11644. ASSERT_TRUE(m.is_open());
  11645. EXPECT_EQ(strlen(content), m.size());
  11646. char buf[8];
  11647. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11648. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11649. }
  11650. #endif
  11651. #ifndef _WIN32
  11652. // A directory or a device has no size to serve.
  11653. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11654. const char *path = "./mmap_not_regular_test_dir";
  11655. ASSERT_EQ(0, ::mkdir(path, 0755));
  11656. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11657. for (auto p : {path, "/dev/null"}) {
  11658. detail::mmap m(p);
  11659. EXPECT_FALSE(m.is_open()) << p;
  11660. EXPECT_EQ(0U, m.size()) << p;
  11661. }
  11662. Server svr;
  11663. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11664. res.set_file_content("/dev/null");
  11665. });
  11666. auto port = svr.bind_to_any_port(HOST);
  11667. thread t = thread([&] { svr.listen_after_bind(); });
  11668. auto se = detail::scope_exit([&] {
  11669. svr.stop();
  11670. t.join();
  11671. });
  11672. svr.wait_until_ready();
  11673. auto res = Client(HOST, port).Get("/null");
  11674. ASSERT_TRUE(res);
  11675. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11676. }
  11677. #endif
  11678. #ifdef __linux__
  11679. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11680. TEST(MmapTest, FileIsNotMapped) {
  11681. const char *path = "mmap_not_mapped_test.txt";
  11682. {
  11683. std::ofstream f(path, std::ios::binary);
  11684. f << "hello";
  11685. }
  11686. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11687. detail::mmap m(path);
  11688. ASSERT_TRUE(m.is_open());
  11689. std::ifstream maps("/proc/self/maps");
  11690. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11691. std::istreambuf_iterator<char>());
  11692. EXPECT_EQ(std::string::npos, mappings.find(path));
  11693. }
  11694. #endif
  11695. TEST(KeepAliveTest, ReadTimeout) {
  11696. Server svr;
  11697. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11698. std::this_thread::sleep_for(std::chrono::seconds(2));
  11699. res.set_content("a", "text/plain");
  11700. });
  11701. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11702. res.set_content("b", "text/plain");
  11703. });
  11704. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11705. auto se = detail::scope_exit([&] {
  11706. svr.stop();
  11707. listen_thread.join();
  11708. ASSERT_FALSE(svr.is_running());
  11709. });
  11710. svr.wait_until_ready();
  11711. Client cli("localhost", PORT);
  11712. cli.set_keep_alive(true);
  11713. cli.set_read_timeout(std::chrono::seconds(1));
  11714. auto resa = cli.Get("/a");
  11715. ASSERT_FALSE(resa);
  11716. EXPECT_EQ(Error::Read, resa.error());
  11717. auto resb = cli.Get("/b");
  11718. ASSERT_TRUE(resb);
  11719. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11720. EXPECT_EQ("b", resb->body);
  11721. }
  11722. TEST(KeepAliveTest, MaxCount) {
  11723. size_t keep_alive_max_count = 3;
  11724. Server svr;
  11725. svr.set_keep_alive_max_count(keep_alive_max_count);
  11726. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11727. res.set_content("Hello World!", "text/plain");
  11728. });
  11729. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11730. auto se = detail::scope_exit([&] {
  11731. svr.stop();
  11732. listen_thread.join();
  11733. ASSERT_FALSE(svr.is_running());
  11734. });
  11735. svr.wait_until_ready();
  11736. Client cli(HOST, PORT);
  11737. cli.set_keep_alive(true);
  11738. for (size_t i = 0; i < 5; i++) {
  11739. auto result = cli.Get("/hi");
  11740. ASSERT_TRUE(result);
  11741. EXPECT_EQ(StatusCode::OK_200, result->status);
  11742. if (i == keep_alive_max_count - 1) {
  11743. EXPECT_EQ("close", result->get_header_value("Connection"));
  11744. } else {
  11745. EXPECT_FALSE(result->has_header("Connection"));
  11746. }
  11747. }
  11748. }
  11749. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11750. // can pull the next one into the server's buffer. The server must serve it
  11751. // without waiting for the socket to become readable again. The keep-alive
  11752. // timeout outlasts the client's read timeout, so a request left waiting for it
  11753. // shows up as a missing response.
  11754. static void serve_pipelining_routes(Server &svr,
  11755. const std::function<void(int)> &client) {
  11756. svr.set_keep_alive_timeout(5);
  11757. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11758. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11759. });
  11760. svr.Post("/echo", [](const Request &req, Response &res) {
  11761. res.set_content("echo " + req.body, "text/plain");
  11762. });
  11763. auto port = svr.bind_to_any_port(HOST);
  11764. thread t = thread([&] { svr.listen_after_bind(); });
  11765. auto se = detail::scope_exit([&] {
  11766. svr.stop();
  11767. t.join();
  11768. });
  11769. svr.wait_until_ready();
  11770. client(port);
  11771. }
  11772. static std::string
  11773. send_pipelined_requests(const std::vector<std::string> &parts) {
  11774. Server svr;
  11775. std::string res;
  11776. serve_pipelining_routes(svr, [&](int port) {
  11777. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11778. });
  11779. return res;
  11780. }
  11781. static void expect_in_order(const std::string &res,
  11782. const std::vector<std::string> &bodies) {
  11783. size_t pos = 0;
  11784. for (const auto &body : bodies) {
  11785. pos = res.find(body, pos);
  11786. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11787. pos += body.size();
  11788. }
  11789. }
  11790. TEST(KeepAliveTest, PipelinedRequests) {
  11791. auto res = send_pipelined_requests(
  11792. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11793. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11794. "Content-Length: 4\r\n\r\nbody"
  11795. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11796. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11797. }
  11798. // The second request starts in the server's buffer and ends on the socket.
  11799. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11800. auto res =
  11801. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11802. "GET /hi/2 HTTP/1.1\r\nHo",
  11803. "st: localhost\r\nConnection: close\r\n\r\n"});
  11804. expect_in_order(res, {"hi 1", "hi 2"});
  11805. }
  11806. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11807. // CRLF after a body does not turn into a 400 for the next request.
  11808. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11809. auto res = send_pipelined_requests(
  11810. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11811. "Content-Length: 4\r\n\r\nbody\r\n"
  11812. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11813. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11814. expect_in_order(res, {"echo body", "hi 2"});
  11815. }
  11816. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11817. // must not be served as the next request.
  11818. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11819. auto res = send_pipelined_requests(
  11820. {"INVALID REQUEST LINE\r\n\r\n"
  11821. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11822. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11823. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11824. }
  11825. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11826. // Over TLS, the next request is held by the TLS library as already decrypted
  11827. // data rather than on the socket.
  11828. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11829. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11830. std::string res;
  11831. serve_pipelining_routes(svr, [&](int port) {
  11832. // One part, so all three requests arrive in one TLS record
  11833. EXPECT_TRUE(send_ssl_request_in_parts(
  11834. 2,
  11835. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11836. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11837. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11838. &res, port));
  11839. });
  11840. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11841. }
  11842. #endif
  11843. TEST(KeepAliveTest, Issue1041) {
  11844. Server svr;
  11845. svr.set_keep_alive_timeout(3);
  11846. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11847. res.set_content("Hello World!", "text/plain");
  11848. });
  11849. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11850. auto se = detail::scope_exit([&] {
  11851. svr.stop();
  11852. listen_thread.join();
  11853. ASSERT_FALSE(svr.is_running());
  11854. });
  11855. svr.wait_until_ready();
  11856. Client cli(HOST, PORT);
  11857. cli.set_keep_alive(true);
  11858. auto result = cli.Get("/hi");
  11859. ASSERT_TRUE(result);
  11860. EXPECT_EQ(StatusCode::OK_200, result->status);
  11861. std::this_thread::sleep_for(std::chrono::seconds(5));
  11862. result = cli.Get("/hi");
  11863. ASSERT_TRUE(result);
  11864. EXPECT_EQ(StatusCode::OK_200, result->status);
  11865. }
  11866. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11867. Server svr;
  11868. svr.set_keep_alive_max_count(0);
  11869. std::set<int> remote_ports;
  11870. svr.Get("/hi", [&](const Request &req, Response &res) {
  11871. remote_ports.insert(req.remote_port);
  11872. res.set_content("hi", "text/plain");
  11873. });
  11874. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11875. auto se = detail::scope_exit([&] {
  11876. svr.stop();
  11877. listen_thread.join();
  11878. ASSERT_FALSE(svr.is_running());
  11879. });
  11880. svr.wait_until_ready();
  11881. Client cli(HOST, PORT);
  11882. cli.set_keep_alive(true);
  11883. for (int i = 0; i < 3; i++) {
  11884. auto res = cli.Get("/hi");
  11885. ASSERT_TRUE(res);
  11886. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11887. }
  11888. // All three over one connection
  11889. EXPECT_EQ(1u, remote_ports.size());
  11890. }
  11891. // Forward declaration (see the base64_encode note).
  11892. namespace httplib {
  11893. namespace detail {
  11894. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11895. } // namespace detail
  11896. } // namespace httplib
  11897. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11898. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11899. #ifndef _WIN32
  11900. signal(SIGPIPE, SIG_IGN);
  11901. #endif
  11902. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11903. ASSERT_NE(INVALID_SOCKET, srv);
  11904. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11905. default_socket_options(srv);
  11906. sockaddr_in addr{};
  11907. addr.sin_family = AF_INET;
  11908. addr.sin_port = 0;
  11909. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11910. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11911. ASSERT_EQ(0, ::listen(srv, 2));
  11912. socklen_t addr_len = sizeof(addr);
  11913. ASSERT_EQ(0,
  11914. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11915. auto port = ntohs(addr.sin_port);
  11916. struct Peer {
  11917. socket_t sock = INVALID_SOCKET;
  11918. #ifdef CPPHTTPLIB_SSL_ENABLED
  11919. tls::session_t session = nullptr;
  11920. #endif
  11921. };
  11922. #ifdef CPPHTTPLIB_SSL_ENABLED
  11923. tls::ctx_t ctx = nullptr;
  11924. if (use_tls) {
  11925. ctx = tls::create_server_context();
  11926. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11927. nullptr);
  11928. }
  11929. auto ctx_se = detail::scope_exit([&] {
  11930. if (ctx) { tls::free_context(ctx); }
  11931. });
  11932. #endif
  11933. auto close_peer = [](Peer &peer) {
  11934. #ifdef CPPHTTPLIB_SSL_ENABLED
  11935. if (peer.session) { tls::free_session(peer.session); }
  11936. #endif
  11937. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11938. };
  11939. auto accept_peer = [&]() {
  11940. Peer peer;
  11941. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11942. peer.sock = ::accept(srv, nullptr, nullptr);
  11943. if (peer.sock == INVALID_SOCKET) { return peer; }
  11944. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11945. #ifdef CPPHTTPLIB_SSL_ENABLED
  11946. if (use_tls) {
  11947. peer.session = tls::create_session(ctx, peer.sock);
  11948. tls::TlsError err;
  11949. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err,
  11950. nullptr)) {
  11951. close_peer(peer);
  11952. return Peer();
  11953. }
  11954. }
  11955. #endif
  11956. return peer;
  11957. };
  11958. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11959. #ifdef CPPHTTPLIB_SSL_ENABLED
  11960. tls::TlsError err;
  11961. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11962. #endif
  11963. return detail::read_socket(peer.sock, buf, len, 0);
  11964. };
  11965. auto read_head = [&](const Peer &peer) {
  11966. std::string head;
  11967. char buf[1024];
  11968. while (head.find("\r\n\r\n") == std::string::npos) {
  11969. auto n = read_some(peer, buf, sizeof(buf));
  11970. if (n <= 0) { break; }
  11971. head.append(buf, static_cast<size_t>(n));
  11972. }
  11973. };
  11974. auto send_text = [](const Peer &peer, const std::string &text) {
  11975. #ifdef CPPHTTPLIB_SSL_ENABLED
  11976. tls::TlsError err;
  11977. if (peer.session) {
  11978. tls::write(peer.session, text.data(), text.size(), err);
  11979. return;
  11980. }
  11981. #endif
  11982. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11983. };
  11984. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11985. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11986. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11987. // Sent once the first response is read, so that it lands on an idle socket
  11988. std::promise<void> first_response_read;
  11989. auto first_response_read_future = first_response_read.get_future();
  11990. auto server_thread = std::thread([&] {
  11991. auto peer1 = accept_peer();
  11992. if (peer1.sock == INVALID_SOCKET) { return; }
  11993. read_head(peer1);
  11994. if (same_write) {
  11995. send_text(peer1, first + stray);
  11996. } else {
  11997. send_text(peer1, first);
  11998. first_response_read_future.wait_for(std::chrono::seconds(5));
  11999. send_text(peer1, stray);
  12000. }
  12001. // peer1 stays open, so only the unread data can tell the client
  12002. auto peer2 = accept_peer();
  12003. if (peer2.sock != INVALID_SOCKET) {
  12004. read_head(peer2);
  12005. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  12006. "Connection: close\r\n\r\nsecond");
  12007. close_peer(peer2);
  12008. }
  12009. close_peer(peer1);
  12010. });
  12011. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  12012. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  12013. std::to_string(port));
  12014. #ifdef CPPHTTPLIB_SSL_ENABLED
  12015. cli.enable_server_certificate_verification(false);
  12016. #endif
  12017. cli.set_keep_alive(true);
  12018. cli.set_read_timeout(5, 0);
  12019. auto res = cli.Get("/1");
  12020. first_response_read.set_value();
  12021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12022. EXPECT_EQ("first", res->body);
  12023. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  12024. res = cli.Get("/2");
  12025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12026. EXPECT_EQ(StatusCode::OK_200, res->status);
  12027. EXPECT_EQ("second", res->body);
  12028. }
  12029. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  12030. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  12031. }
  12032. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  12033. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  12034. }
  12035. #ifdef CPPHTTPLIB_SSL_ENABLED
  12036. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  12037. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  12038. }
  12039. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  12040. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  12041. }
  12042. #endif
  12043. TEST(KeepAliveTest, Issue1959) {
  12044. Server svr;
  12045. svr.set_keep_alive_timeout(5);
  12046. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12047. res.set_content("a", "text/plain");
  12048. });
  12049. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12050. auto se = detail::scope_exit([&] {
  12051. if (!svr.is_running()) return;
  12052. svr.stop();
  12053. listen_thread.join();
  12054. ASSERT_FALSE(svr.is_running());
  12055. });
  12056. svr.wait_until_ready();
  12057. Client cli("localhost", PORT);
  12058. cli.set_keep_alive(true);
  12059. using namespace std::chrono;
  12060. auto start = steady_clock::now();
  12061. cli.Get("/a");
  12062. svr.stop();
  12063. listen_thread.join();
  12064. auto end = steady_clock::now();
  12065. auto elapsed = duration_cast<milliseconds>(end - start).count();
  12066. EXPECT_LT(elapsed, 5000);
  12067. }
  12068. #ifdef CPPHTTPLIB_SSL_ENABLED
  12069. TEST(KeepAliveTest, SSLClientReconnection) {
  12070. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12071. ASSERT_TRUE(svr.is_valid());
  12072. svr.set_keep_alive_timeout(1);
  12073. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  12074. res.set_content("Hello World!", "text/plain");
  12075. });
  12076. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12077. auto se = detail::scope_exit([&] {
  12078. svr.stop();
  12079. listen_thread.join();
  12080. ASSERT_FALSE(svr.is_running());
  12081. });
  12082. svr.wait_until_ready();
  12083. SSLClient cli(HOST, PORT);
  12084. cli.enable_server_certificate_verification(false);
  12085. cli.set_keep_alive(true);
  12086. auto result = cli.Get("/hi");
  12087. ASSERT_TRUE(result);
  12088. EXPECT_EQ(StatusCode::OK_200, result->status);
  12089. result = cli.Get("/hi");
  12090. ASSERT_TRUE(result);
  12091. EXPECT_EQ(StatusCode::OK_200, result->status);
  12092. std::this_thread::sleep_for(std::chrono::seconds(2));
  12093. // Recoonect
  12094. result = cli.Get("/hi");
  12095. ASSERT_TRUE(result);
  12096. EXPECT_EQ(StatusCode::OK_200, result->status);
  12097. result = cli.Get("/hi");
  12098. ASSERT_TRUE(result);
  12099. EXPECT_EQ(StatusCode::OK_200, result->status);
  12100. }
  12101. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  12102. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12103. ASSERT_TRUE(svr.is_valid());
  12104. svr.set_keep_alive_timeout(1);
  12105. std::string content = "reconnect";
  12106. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  12107. res.set_content("Hello World!", "text/plain");
  12108. });
  12109. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12110. auto se = detail::scope_exit([&] {
  12111. svr.stop();
  12112. listen_thread.join();
  12113. ASSERT_FALSE(svr.is_running());
  12114. });
  12115. svr.wait_until_ready();
  12116. SSLClient cli(HOST, PORT);
  12117. cli.enable_server_certificate_verification(false);
  12118. cli.set_keep_alive(true);
  12119. auto result = cli.Post(
  12120. "/hi", content.size(),
  12121. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12122. sink.write(content.c_str(), content.size());
  12123. return true;
  12124. },
  12125. "text/plain");
  12126. ASSERT_TRUE(result);
  12127. EXPECT_EQ(200, result->status);
  12128. std::this_thread::sleep_for(std::chrono::seconds(2));
  12129. // Recoonect
  12130. result = cli.Post(
  12131. "/hi", content.size(),
  12132. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12133. sink.write(content.c_str(), content.size());
  12134. return true;
  12135. },
  12136. "text/plain");
  12137. ASSERT_TRUE(result);
  12138. EXPECT_EQ(200, result->status);
  12139. result = cli.Post(
  12140. "/hi", content.size(),
  12141. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12142. sink.write(content.c_str(), content.size());
  12143. return true;
  12144. },
  12145. "text/plain");
  12146. ASSERT_TRUE(result);
  12147. EXPECT_EQ(200, result->status);
  12148. }
  12149. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  12150. using namespace httplib::tls;
  12151. {
  12152. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12153. ASSERT_TRUE(svr.is_valid());
  12154. svr.Get("/sni", [&](const Request &req, Response &res) {
  12155. std::string expected = req.sni();
  12156. EXPECT_EQ(expected, req.get_param_value("expected"));
  12157. res.set_content("ok", "text/plain");
  12158. });
  12159. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12160. auto se = detail::scope_exit([&] {
  12161. svr.stop();
  12162. listen_thread.join();
  12163. ASSERT_FALSE(svr.is_running());
  12164. });
  12165. svr.wait_until_ready();
  12166. {
  12167. SSLClient cli("localhost", PORT);
  12168. cli.enable_server_certificate_verification(false);
  12169. auto res = cli.Get("/sni?expected=localhost");
  12170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12171. }
  12172. {
  12173. SSLClient cli("::1", PORT);
  12174. cli.enable_server_certificate_verification(false);
  12175. auto res = cli.Get("/sni?expected=");
  12176. // NOTE: This may fail if the server is listening on IPv4 only
  12177. // (e.g., when localhost resolves to 127.0.0.1 only)
  12178. if (res) {
  12179. EXPECT_EQ(StatusCode::OK_200, res->status);
  12180. } else {
  12181. EXPECT_EQ(Error::Connection, res.error());
  12182. }
  12183. }
  12184. }
  12185. }
  12186. // The SNI of a failed handshake does not reach the next connection that the
  12187. // same worker thread serves
  12188. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  12189. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12190. ASSERT_TRUE(svr.is_valid());
  12191. svr.new_task_queue = [] { return new ThreadPool(1); };
  12192. svr.Get("/sni", [](const Request &req, Response &res) {
  12193. res.set_content(req.sni(), "text/plain");
  12194. });
  12195. auto port = svr.bind_to_any_port("127.0.0.1");
  12196. ASSERT_LT(0, port);
  12197. thread t = thread([&] { svr.listen_after_bind(); });
  12198. auto se = detail::scope_exit([&] {
  12199. svr.stop();
  12200. t.join();
  12201. ASSERT_FALSE(svr.is_running());
  12202. });
  12203. svr.wait_until_ready();
  12204. {
  12205. // Sends SNI, then rejects the server certificate, which the CA did not sign
  12206. SSLClient cli("localhost", port);
  12207. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  12208. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  12209. auto res = cli.Get("/sni");
  12210. ASSERT_FALSE(res);
  12211. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12212. }
  12213. // An IP host sends no SNI (RFC 6066)
  12214. SSLClient cli("127.0.0.1", port);
  12215. cli.enable_server_certificate_verification(false);
  12216. auto res = cli.Get("/sni");
  12217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12218. EXPECT_EQ("", res->body);
  12219. }
  12220. #endif
  12221. TEST(ClientProblemDetectionTest, ContentProvider) {
  12222. Server svr;
  12223. size_t content_length = 1024 * 1024;
  12224. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12225. res.set_content_provider(
  12226. content_length, "text/plain",
  12227. [&](size_t offset, size_t length, DataSink &sink) {
  12228. auto out_len = std::min(length, static_cast<size_t>(1024));
  12229. std::string out(out_len, '@');
  12230. sink.write(out.data(), out_len);
  12231. return offset < 4096;
  12232. },
  12233. [](bool success) { ASSERT_FALSE(success); });
  12234. });
  12235. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  12236. res.set_content_provider(
  12237. 0, "text/plain",
  12238. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  12239. EXPECT_TRUE(false);
  12240. return true;
  12241. },
  12242. [](bool success) { ASSERT_FALSE(success); });
  12243. });
  12244. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12245. auto se = detail::scope_exit([&] {
  12246. svr.stop();
  12247. listen_thread.join();
  12248. ASSERT_FALSE(svr.is_running());
  12249. });
  12250. svr.wait_until_ready();
  12251. Client cli("localhost", PORT);
  12252. {
  12253. auto res = cli.Get("/hi", [&](const char * /*data*/,
  12254. size_t /*data_length*/) { return false; });
  12255. ASSERT_FALSE(res);
  12256. }
  12257. {
  12258. auto res = cli.Get("/empty", [&](const char * /*data*/,
  12259. size_t /*data_length*/) { return false; });
  12260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12261. }
  12262. }
  12263. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  12264. // A provider that reports success without writing anything and without
  12265. // calling done() used to be handed the same offset and length again on every
  12266. // pass, so it spun for as long as the peer stayed connected.
  12267. Server svr;
  12268. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12269. res.set_content("ok", "text/plain");
  12270. });
  12271. auto port = svr.bind_to_any_port(HOST);
  12272. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  12273. auto se = detail::scope_exit([&] {
  12274. svr.stop();
  12275. listen_thread.join();
  12276. ASSERT_FALSE(svr.is_running());
  12277. });
  12278. svr.wait_until_ready();
  12279. std::atomic<int> call_count{0};
  12280. Client cli(HOST, port);
  12281. auto res = cli.Post(
  12282. "/", 1024,
  12283. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  12284. // Give up after enough passes to show the spin, so that losing the
  12285. // check below fails this test instead of hanging it.
  12286. return ++call_count < 100;
  12287. },
  12288. "text/plain");
  12289. ASSERT_FALSE(res);
  12290. EXPECT_EQ(Error::Write, res.error());
  12291. EXPECT_EQ(1, call_count.load());
  12292. }
  12293. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  12294. // A writer only has to assign `write`. The other three used to be left as
  12295. // empty std::functions, so a provider calling one threw
  12296. // std::bad_function_call out of the thread running it and took the whole
  12297. // process down.
  12298. DataSink sink;
  12299. std::string written;
  12300. sink.write = [&](const char *data, size_t data_len) {
  12301. written.append(data, data_len);
  12302. return true;
  12303. };
  12304. EXPECT_TRUE(sink.is_writable());
  12305. sink.done();
  12306. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12307. EXPECT_TRUE(written.empty());
  12308. }
  12309. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  12310. // A sink that cannot carry trailers still has to finish.
  12311. DataSink sink;
  12312. auto done_count = 0;
  12313. sink.done = [&]() { done_count++; };
  12314. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12315. EXPECT_EQ(1, done_count);
  12316. }
  12317. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  12318. Server svr;
  12319. const std::string body(4096, 'x');
  12320. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12321. res.set_content_provider(body.size(), "text/plain",
  12322. [&](size_t offset, size_t length, DataSink &sink) {
  12323. sink.write(body.data() + offset, length);
  12324. sink.done();
  12325. return true;
  12326. });
  12327. });
  12328. auto port = svr.bind_to_any_port(HOST);
  12329. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12330. auto se = detail::scope_exit([&] {
  12331. svr.stop();
  12332. listen_thread.join();
  12333. ASSERT_FALSE(svr.is_running());
  12334. });
  12335. svr.wait_until_ready();
  12336. Client cli(HOST, port);
  12337. auto res = cli.Get("/");
  12338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12339. EXPECT_EQ(StatusCode::OK_200, res->status);
  12340. EXPECT_EQ(body, res->body);
  12341. }
  12342. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  12343. Server svr;
  12344. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12345. res.set_content_provider(
  12346. 1024, "text/plain",
  12347. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12348. sink.write("hello", 5);
  12349. sink.done(); // short of the 1024 bytes the response promised
  12350. return true;
  12351. });
  12352. });
  12353. auto port = svr.bind_to_any_port(HOST);
  12354. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12355. auto se = detail::scope_exit([&] {
  12356. svr.stop();
  12357. listen_thread.join();
  12358. ASSERT_FALSE(svr.is_running());
  12359. });
  12360. svr.wait_until_ready();
  12361. Client cli(HOST, port);
  12362. cli.set_read_timeout(5, 0);
  12363. // The response is short of its Content-Length, so the client cannot read a
  12364. // complete body. What matters is that this returns at all: a no-op done()
  12365. // would leave the writer looping over a provider that never makes progress.
  12366. auto res = cli.Get("/");
  12367. EXPECT_FALSE(res);
  12368. }
  12369. // Read as the next response by a peer that sees it after a framed body.
  12370. static const std::string smuggled_response =
  12371. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12372. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12373. Server svr;
  12374. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12375. res.set_content_provider(
  12376. 5, "text/plain",
  12377. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12378. auto data = "AAAAA" + smuggled_response;
  12379. sink.write(data.data(), data.size());
  12380. return true;
  12381. });
  12382. });
  12383. thread t = thread([&] { svr.listen(HOST, PORT); });
  12384. auto se = detail::scope_exit([&] {
  12385. svr.stop();
  12386. t.join();
  12387. ASSERT_FALSE(svr.is_running());
  12388. });
  12389. svr.wait_until_ready();
  12390. std::string resp;
  12391. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12392. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12393. resp.clear();
  12394. ASSERT_TRUE(send_request(
  12395. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12396. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12397. }
  12398. TEST(NoContentTest, BodyIsNotSent) {
  12399. Server svr;
  12400. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12401. res.status = StatusCode::NoContent_204;
  12402. res.set_content(smuggled_response, "text/plain");
  12403. });
  12404. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12405. res.status = StatusCode::NotModified_304;
  12406. res.set_chunked_content_provider(
  12407. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12408. sink.write(smuggled_response.data(), smuggled_response.size());
  12409. sink.done();
  12410. return true;
  12411. });
  12412. });
  12413. thread t = thread([&] { svr.listen(HOST, PORT); });
  12414. auto se = detail::scope_exit([&] {
  12415. svr.stop();
  12416. t.join();
  12417. ASSERT_FALSE(svr.is_running());
  12418. });
  12419. svr.wait_until_ready();
  12420. for (auto path : {"/204", "/304"}) {
  12421. std::string resp;
  12422. ASSERT_TRUE(send_request(
  12423. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12424. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12425. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12426. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12427. }
  12428. }
  12429. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12430. Server svr;
  12431. std::atomic<bool> smuggled(false);
  12432. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12433. res.set_content("ok", "text/plain");
  12434. });
  12435. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12436. smuggled = true;
  12437. });
  12438. auto port = svr.bind_to_any_port(HOST);
  12439. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12440. auto se = detail::scope_exit([&] {
  12441. svr.stop();
  12442. listen_thread.join();
  12443. ASSERT_FALSE(svr.is_running());
  12444. });
  12445. svr.wait_until_ready();
  12446. // What follows the body would be read as the next request.
  12447. Client cli(HOST, port);
  12448. auto res = cli.Post(
  12449. "/", 5,
  12450. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12451. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12452. sink.write(data.data(), data.size());
  12453. return true;
  12454. },
  12455. "text/plain");
  12456. ASSERT_FALSE(res);
  12457. EXPECT_EQ(Error::Write, res.error());
  12458. EXPECT_FALSE(smuggled);
  12459. }
  12460. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12461. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12462. // The compressed path builds the whole body before connecting, so this
  12463. // fails client-side and never reaches a server.
  12464. Client cli(HOST, PORT);
  12465. cli.set_compress(true);
  12466. auto res = cli.Post(
  12467. "/", 1024,
  12468. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12469. sink.write("hello", 5);
  12470. sink.done(); // short of the 1024 bytes the request announced
  12471. return true;
  12472. },
  12473. "text/plain");
  12474. ASSERT_FALSE(res);
  12475. EXPECT_EQ(Error::Write, res.error());
  12476. }
  12477. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12478. Server svr;
  12479. std::string received;
  12480. size_t content_length_count = 0;
  12481. bool has_transfer_encoding = true;
  12482. svr.Post("/echo", [&](const Request &req, Response &res) {
  12483. received = req.body;
  12484. content_length_count = req.get_header_value_count("Content-Length");
  12485. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12486. res.set_content("ok", "text/plain");
  12487. });
  12488. svr.Get("/next", [](const Request &, Response &res) {
  12489. res.set_content("next", "text/plain");
  12490. });
  12491. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12492. auto se = detail::scope_exit([&] {
  12493. svr.stop();
  12494. listen_thread.join();
  12495. ASSERT_FALSE(svr.is_running());
  12496. });
  12497. svr.wait_until_ready();
  12498. Client cli(HOST, PORT);
  12499. cli.set_keep_alive(true);
  12500. cli.set_compress(true);
  12501. const std::string body = "hello world";
  12502. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12503. auto res = cli.Post("/echo", headers, body, "text/plain");
  12504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12505. EXPECT_EQ(StatusCode::OK_200, res->status);
  12506. EXPECT_EQ(body, received);
  12507. EXPECT_EQ(1u, content_length_count);
  12508. EXPECT_FALSE(has_transfer_encoding);
  12509. // The rest of a truncated body would be read as this request
  12510. auto res2 = cli.Get("/next");
  12511. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12512. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12513. EXPECT_EQ("next", res2->body);
  12514. }
  12515. #endif
  12516. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12517. Server svr;
  12518. std::string received;
  12519. size_t content_length_count = 1;
  12520. bool has_transfer_encoding = false;
  12521. svr.Post("/echo", [&](const Request &req, Response &res) {
  12522. received = req.body;
  12523. content_length_count = req.get_header_value_count("Content-Length");
  12524. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12525. res.set_content("ok", "text/plain");
  12526. });
  12527. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12528. auto se = detail::scope_exit([&] {
  12529. svr.stop();
  12530. listen_thread.join();
  12531. ASSERT_FALSE(svr.is_running());
  12532. });
  12533. svr.wait_until_ready();
  12534. Client cli(HOST, PORT);
  12535. cli.set_keep_alive(true);
  12536. const std::string body = "hello world";
  12537. Headers headers = {{"Content-Length", "5"}};
  12538. auto res = cli.Post(
  12539. "/echo", headers,
  12540. [&](size_t /*offset*/, DataSink &sink) {
  12541. sink.write(body.data(), body.size());
  12542. sink.done();
  12543. return true;
  12544. },
  12545. "text/plain");
  12546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12547. EXPECT_EQ(StatusCode::OK_200, res->status);
  12548. EXPECT_EQ(body, received);
  12549. EXPECT_EQ(0u, content_length_count);
  12550. EXPECT_TRUE(has_transfer_encoding);
  12551. }
  12552. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12553. Server svr;
  12554. svr.set_error_handler([](Request const &, Response &res) -> void {
  12555. res.set_chunked_content_provider(
  12556. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12557. sink.os << "hello";
  12558. sink.os << "world";
  12559. sink.done();
  12560. return true;
  12561. });
  12562. });
  12563. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12564. auto se = detail::scope_exit([&] {
  12565. svr.stop();
  12566. listen_thread.join();
  12567. ASSERT_FALSE(svr.is_running());
  12568. });
  12569. svr.wait_until_ready();
  12570. Client cli("localhost", PORT);
  12571. auto res = cli.Get("/");
  12572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12573. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12574. EXPECT_EQ("helloworld", res->body);
  12575. }
  12576. // A body set after a content provider must replace it, not be sent through it.
  12577. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12578. Server svr;
  12579. svr.set_mount_point("/", "./www");
  12580. svr.set_file_request_handler([](const Request &req, Response &res) {
  12581. if (req.path == "/dir/test.html") {
  12582. res.status = StatusCode::Forbidden_403;
  12583. res.set_content(std::string(5000, 'D'), "text/plain");
  12584. } else if (req.path == "/file") {
  12585. res.status = StatusCode::Forbidden_403;
  12586. res.body = "Denied";
  12587. }
  12588. });
  12589. auto port = svr.bind_to_any_port(HOST);
  12590. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12591. auto se = detail::scope_exit([&] {
  12592. svr.stop();
  12593. t.join();
  12594. ASSERT_FALSE(svr.is_running());
  12595. });
  12596. svr.wait_until_ready();
  12597. Client cli(HOST, port);
  12598. {
  12599. auto res = cli.Get("/dir/test.html");
  12600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12601. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12602. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12603. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12604. }
  12605. {
  12606. auto res = cli.Get("/file");
  12607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12608. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12609. EXPECT_EQ("Denied", res->body);
  12610. }
  12611. {
  12612. auto res = cli.Get("/dir/index.html");
  12613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12614. EXPECT_EQ(StatusCode::OK_200, res->status);
  12615. EXPECT_EQ(0U, res->body.find("<html>"));
  12616. }
  12617. }
  12618. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12619. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12620. Server svr;
  12621. std::vector<bool> released;
  12622. std::mutex released_mutex;
  12623. auto releaser = [&](bool success) {
  12624. std::lock_guard<std::mutex> guard(released_mutex);
  12625. released.push_back(success);
  12626. };
  12627. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12628. return sink.write(&"hello"[offset], length);
  12629. };
  12630. svr.Get("/sized", [&](const Request &, Response &res) {
  12631. res.status = StatusCode::NotFound_404;
  12632. res.set_content_provider(5, "text/plain", provider, releaser);
  12633. });
  12634. svr.Get("/chunked", [&](const Request &, Response &res) {
  12635. res.status = StatusCode::ServiceUnavailable_503;
  12636. res.set_chunked_content_provider(
  12637. "text/plain",
  12638. [](size_t, DataSink &sink) {
  12639. sink.os << "chunk";
  12640. sink.done();
  12641. return true;
  12642. },
  12643. releaser);
  12644. });
  12645. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12646. res.set_content_provider(5, "text/plain", provider, releaser);
  12647. throw std::runtime_error("after the provider");
  12648. });
  12649. svr.set_error_handler([](const Request &req, Response &res) {
  12650. // Leave the exception handler's content to it.
  12651. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12652. res.set_content(std::string(1000, 'E'), "text/html");
  12653. return Server::HandlerResponse::Handled;
  12654. });
  12655. svr.set_exception_handler(
  12656. [](const Request &, Response &res, std::exception_ptr) {
  12657. res.status = StatusCode::InternalServerError_500;
  12658. res.set_content(std::string(1000, 'X'), "text/html");
  12659. });
  12660. auto port = svr.bind_to_any_port(HOST);
  12661. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12662. auto se = detail::scope_exit([&] {
  12663. svr.stop();
  12664. t.join();
  12665. ASSERT_FALSE(svr.is_running());
  12666. });
  12667. svr.wait_until_ready();
  12668. Client cli(HOST, port);
  12669. {
  12670. auto res = cli.Get("/sized");
  12671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12672. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12673. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12674. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12675. }
  12676. {
  12677. auto res = cli.Get("/chunked");
  12678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12679. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12680. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12681. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12682. }
  12683. {
  12684. auto res = cli.Get("/throw");
  12685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12686. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12687. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12688. }
  12689. std::lock_guard<std::mutex> guard(released_mutex);
  12690. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12691. }
  12692. #endif
  12693. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12694. Server svr;
  12695. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12696. return sink.write(&"abc"[offset], length);
  12697. };
  12698. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12699. res.set_file_content("./www/dir/test.html");
  12700. res.set_content("body", "text/plain");
  12701. });
  12702. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12703. res.set_content(std::string(100, 'B'), "text/plain");
  12704. res.set_file_content("./www/dir/test.html");
  12705. });
  12706. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12707. res.set_content(std::string(100, 'B'), "text/plain");
  12708. res.set_content_provider(3, "text/x-provider", abc);
  12709. });
  12710. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12711. res.set_content_provider(3, "text/x-provider", abc);
  12712. res.set_content(std::string(100, 'B'), "text/plain");
  12713. });
  12714. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12715. res.set_content_provider(3, "text/x-provider", abc);
  12716. res.set_file_content("./www/dir/test.html", "text/x-file");
  12717. });
  12718. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12719. res.set_file_content("./www/dir/test.html");
  12720. res.set_header("Content-Type", "text/x-handler");
  12721. });
  12722. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12723. res.set_content_provider(3, "text/plain", abc);
  12724. res.body = "direct";
  12725. });
  12726. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12727. res.set_file_content("./www/dir/test.html");
  12728. res.body = "direct";
  12729. });
  12730. auto port = svr.bind_to_any_port(HOST);
  12731. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12732. auto se = detail::scope_exit([&] {
  12733. svr.stop();
  12734. t.join();
  12735. ASSERT_FALSE(svr.is_running());
  12736. });
  12737. svr.wait_until_ready();
  12738. Client cli(HOST, port);
  12739. auto expect_body = [&](const char *path, const std::string &body,
  12740. const std::string &type) {
  12741. // Uncompressed, so Content-Length can be compared with the body.
  12742. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12743. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12744. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12745. EXPECT_EQ(body, res->body) << path;
  12746. EXPECT_EQ(std::to_string(body.size()),
  12747. res->get_header_value("Content-Length"))
  12748. << path;
  12749. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12750. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12751. };
  12752. expect_body("/file-then-body", "body", "text/plain");
  12753. expect_body("/body-then-file", "test.html", "text/html");
  12754. expect_body("/body-then-provider", "abc", "text/x-provider");
  12755. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12756. expect_body("/provider-then-file", "test.html", "text/x-file");
  12757. expect_body("/file-then-header", "test.html", "text/x-handler");
  12758. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12759. expect_body("/file-then-direct-body", "direct", "text/plain");
  12760. // Ranges are checked against the body, not the dropped provider.
  12761. {
  12762. auto res = cli.Get("/provider-then-direct-body",
  12763. Headers{{make_range_header({{1, 2}})}});
  12764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12765. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12766. EXPECT_EQ("ir", res->body);
  12767. }
  12768. {
  12769. auto res = cli.Get("/file-then-direct-body",
  12770. Headers{{make_range_header({{7, 8}})}});
  12771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12772. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12773. }
  12774. }
  12775. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12776. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12777. const char *path = "./truncated_while_served.txt";
  12778. const size_t size = 32 * 1024 * 1024;
  12779. {
  12780. std::ofstream f(path, std::ios::binary);
  12781. f << std::string(size, 'x');
  12782. }
  12783. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12784. // Over TLS, where the bytes are encrypted in this process rather than
  12785. // copied by send().
  12786. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12787. svr.Get("/file", [&](const Request &, Response &res) {
  12788. res.set_file_content(path, "text/plain");
  12789. });
  12790. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12791. auto se = detail::scope_exit([&] {
  12792. svr.stop();
  12793. thread.join();
  12794. ASSERT_FALSE(svr.is_running());
  12795. });
  12796. svr.wait_until_ready();
  12797. // The file shrinks once the first bytes are in, as a rewrite in place
  12798. // would, and reading the mapping past its new end used to raise SIGBUS.
  12799. SSLClient cli(HOST, PORT);
  12800. cli.enable_server_certificate_verification(false);
  12801. size_t received = 0;
  12802. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12803. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12804. received += len;
  12805. return true;
  12806. });
  12807. EXPECT_FALSE(res);
  12808. EXPECT_LT(received, size);
  12809. }
  12810. #endif
  12811. // Forward declaration (see the base64_encode note).
  12812. namespace httplib {
  12813. namespace detail {
  12814. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12815. const std::string &content_type,
  12816. EncodingType encoding);
  12817. } // namespace detail
  12818. } // namespace httplib
  12819. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12820. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12821. ASSERT_TRUE(mm->is_open());
  12822. Response res;
  12823. detail::set_file_content_provider(res, mm, "text/html",
  12824. detail::EncodingType::None);
  12825. std::string out;
  12826. DataSink sink;
  12827. sink.write = [&](const char *d, size_t l) {
  12828. out.append(d, l);
  12829. return true;
  12830. };
  12831. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12832. EXPECT_EQ("test.html", out);
  12833. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12834. EXPECT_EQ("test.html", out);
  12835. }
  12836. TEST(LongPollingTest, ClientCloseDetection) {
  12837. Server svr;
  12838. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12839. res.set_chunked_content_provider(
  12840. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12841. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12842. sink.os << "hello";
  12843. auto count = 10;
  12844. while (count > 0 && sink.is_writable()) {
  12845. this_thread::sleep_for(chrono::milliseconds(10));
  12846. count--;
  12847. }
  12848. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12849. return true;
  12850. });
  12851. });
  12852. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12853. auto se = detail::scope_exit([&] {
  12854. svr.stop();
  12855. listen_thread.join();
  12856. ASSERT_FALSE(svr.is_running());
  12857. });
  12858. svr.wait_until_ready();
  12859. Client cli("localhost", PORT);
  12860. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12861. EXPECT_EQ("hello", string(data, data_length));
  12862. return false; // close the socket immediately.
  12863. });
  12864. ASSERT_FALSE(res);
  12865. }
  12866. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12867. Server svr;
  12868. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12869. res.set_chunked_content_provider(
  12870. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12871. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12872. sink.os << "hello";
  12873. EXPECT_TRUE(sink.os.good());
  12874. // Wait for the client to close the connection
  12875. auto count = 10;
  12876. while (count > 0 && sink.is_writable()) {
  12877. this_thread::sleep_for(chrono::milliseconds(10));
  12878. count--;
  12879. }
  12880. // After client disconnect, write repeatedly until the socket
  12881. // write actually fails (small writes may be absorbed by the
  12882. // kernel buffer)
  12883. std::string chunk(1024, 'x');
  12884. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12885. sink.os << chunk;
  12886. }
  12887. EXPECT_TRUE(sink.os.fail());
  12888. return true;
  12889. });
  12890. });
  12891. auto port = svr.bind_to_any_port("localhost");
  12892. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12893. auto se = detail::scope_exit([&] {
  12894. svr.stop();
  12895. listen_thread.join();
  12896. ASSERT_FALSE(svr.is_running());
  12897. });
  12898. svr.wait_until_ready();
  12899. Client cli("localhost", port);
  12900. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12901. EXPECT_EQ("hello", string(data, data_length));
  12902. return false; // close the socket immediately.
  12903. });
  12904. ASSERT_FALSE(res);
  12905. }
  12906. TEST(GetWithParametersTest, GetWithParameters) {
  12907. Server svr;
  12908. svr.Get("/", [&](const Request &req, Response &) {
  12909. EXPECT_EQ("world", req.get_param_value("hello"));
  12910. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12911. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12912. });
  12913. svr.Get("/params", [&](const Request &req, Response &) {
  12914. EXPECT_EQ("world", req.get_param_value("hello"));
  12915. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12916. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12917. });
  12918. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12919. EXPECT_EQ("resource-id", req.matches[1]);
  12920. EXPECT_EQ("foo", req.get_param_value("param1"));
  12921. EXPECT_EQ("bar", req.get_param_value("param2"));
  12922. });
  12923. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12924. EXPECT_EQ("user-id", req.path_params.at("id"));
  12925. EXPECT_EQ("foo", req.get_param_value("param1"));
  12926. EXPECT_EQ("bar", req.get_param_value("param2"));
  12927. });
  12928. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12929. auto se = detail::scope_exit([&] {
  12930. svr.stop();
  12931. listen_thread.join();
  12932. ASSERT_FALSE(svr.is_running());
  12933. });
  12934. svr.wait_until_ready();
  12935. {
  12936. Client cli(HOST, PORT);
  12937. Params params;
  12938. params.emplace("hello", "world");
  12939. params.emplace("hello2", "world2");
  12940. params.emplace("hello3", "world3");
  12941. auto res = cli.Get("/", params, Headers{});
  12942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12943. EXPECT_EQ(StatusCode::OK_200, res->status);
  12944. }
  12945. {
  12946. Client cli(HOST, PORT);
  12947. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12949. EXPECT_EQ(StatusCode::OK_200, res->status);
  12950. }
  12951. {
  12952. Client cli(HOST, PORT);
  12953. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12955. EXPECT_EQ(StatusCode::OK_200, res->status);
  12956. }
  12957. {
  12958. Client cli(HOST, PORT);
  12959. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12961. EXPECT_EQ(StatusCode::OK_200, res->status);
  12962. }
  12963. }
  12964. TEST(GetWithParametersTest, GetWithParameters2) {
  12965. Server svr;
  12966. svr.Get("/", [&](const Request &req, Response &res) {
  12967. auto text = req.get_param_value("hello");
  12968. res.set_content(text, "text/plain");
  12969. });
  12970. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12971. auto se = detail::scope_exit([&] {
  12972. svr.stop();
  12973. listen_thread.join();
  12974. ASSERT_FALSE(svr.is_running());
  12975. });
  12976. svr.wait_until_ready();
  12977. Client cli("localhost", PORT);
  12978. Params params;
  12979. params.emplace("hello", "world");
  12980. std::string body;
  12981. auto res = cli.Get("/", params, Headers{},
  12982. [&](const char *data, size_t data_length) {
  12983. body.append(data, data_length);
  12984. return true;
  12985. });
  12986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12987. EXPECT_EQ(StatusCode::OK_200, res->status);
  12988. EXPECT_EQ("world", body);
  12989. }
  12990. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12991. Server svr;
  12992. svr.Get("/search", [&](const Request &req, Response &res) {
  12993. auto q = req.get_param_value("q");
  12994. res.set_content(q, "text/plain");
  12995. });
  12996. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12997. auto se = detail::scope_exit([&] {
  12998. svr.stop();
  12999. listen_thread.join();
  13000. ASSERT_FALSE(svr.is_running());
  13001. });
  13002. svr.wait_until_ready();
  13003. Client cli("localhost", PORT);
  13004. // Verify that Get(path, params) works without requiring Headers argument
  13005. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  13006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13007. EXPECT_EQ(StatusCode::OK_200, res->status);
  13008. EXPECT_EQ("cpp-httplib", res->body);
  13009. }
  13010. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  13011. auto host = "httpbingo.org";
  13012. auto path = std::string{"/range/32"};
  13013. #ifdef CPPHTTPLIB_SSL_ENABLED
  13014. SSLClient cli(host);
  13015. #else
  13016. Client cli(host);
  13017. #endif
  13018. cli.set_default_headers({make_range_header({{1, 10}})});
  13019. cli.set_connection_timeout(5);
  13020. {
  13021. auto res = retry_service_failures([&] { return cli.Get(path); });
  13022. SKIP_ON_SERVICE_FAILURE(res);
  13023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13024. EXPECT_EQ("bcdefghijk", res->body);
  13025. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  13026. }
  13027. {
  13028. auto res = retry_service_failures([&] { return cli.Get(path); });
  13029. SKIP_ON_SERVICE_FAILURE(res);
  13030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13031. EXPECT_EQ("bcdefghijk", res->body);
  13032. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  13033. }
  13034. }
  13035. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  13036. Server svr;
  13037. svr.set_default_headers({{"Hello", "World"}});
  13038. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  13039. res.set_content("ok", "text/plain");
  13040. });
  13041. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13042. auto se = detail::scope_exit([&] {
  13043. svr.stop();
  13044. listen_thread.join();
  13045. ASSERT_FALSE(svr.is_running());
  13046. });
  13047. svr.wait_until_ready();
  13048. Client cli("localhost", PORT);
  13049. auto res = cli.Get("/");
  13050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13051. EXPECT_EQ(StatusCode::OK_200, res->status);
  13052. EXPECT_EQ("ok", res->body);
  13053. EXPECT_EQ("World", res->get_header_value("Hello"));
  13054. }
  13055. #ifdef CPPHTTPLIB_SSL_ENABLED
  13056. TEST(KeepAliveTest, ReadTimeoutSSL) {
  13057. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13058. ASSERT_TRUE(svr.is_valid());
  13059. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  13060. std::this_thread::sleep_for(std::chrono::seconds(2));
  13061. res.set_content("a", "text/plain");
  13062. });
  13063. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  13064. res.set_content("b", "text/plain");
  13065. });
  13066. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13067. auto se = detail::scope_exit([&] {
  13068. svr.stop();
  13069. listen_thread.join();
  13070. ASSERT_FALSE(svr.is_running());
  13071. });
  13072. svr.wait_until_ready();
  13073. SSLClient cli("localhost", PORT);
  13074. cli.enable_server_certificate_verification(false);
  13075. cli.set_keep_alive(true);
  13076. cli.set_read_timeout(std::chrono::seconds(1));
  13077. auto resa = cli.Get("/a");
  13078. ASSERT_TRUE(!resa);
  13079. EXPECT_EQ(Error::Read, resa.error());
  13080. auto resb = cli.Get("/b");
  13081. ASSERT_TRUE(resb);
  13082. EXPECT_EQ(StatusCode::OK_200, resb->status);
  13083. EXPECT_EQ("b", resb->body);
  13084. }
  13085. // Closing an idle keep-alive connection sends close_notify and returns. The
  13086. // server must not wait for the client's close_notify: an idle client never
  13087. // sends one, so the worker would be held until the read timeout expires, and
  13088. // stop() would wait for it.
  13089. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  13090. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13091. ASSERT_TRUE(svr.is_valid());
  13092. svr.set_keep_alive_timeout(1);
  13093. svr.set_read_timeout(10, 0);
  13094. svr.Get("/", [](const Request &, Response &res) {
  13095. res.set_content("ok", "text/plain");
  13096. });
  13097. auto port = svr.bind_to_any_port(HOST);
  13098. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  13099. auto se = detail::scope_exit([&] {
  13100. if (listen_thread.joinable()) {
  13101. svr.stop();
  13102. listen_thread.join();
  13103. }
  13104. });
  13105. svr.wait_until_ready();
  13106. SSLClient cli(HOST, port);
  13107. cli.enable_server_certificate_verification(false);
  13108. cli.set_keep_alive(true);
  13109. auto res = cli.Get("/");
  13110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13111. EXPECT_EQ(StatusCode::OK_200, res->status);
  13112. // Stay idle past the keep-alive timeout so the server closes the connection.
  13113. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  13114. auto start = std::chrono::steady_clock::now();
  13115. svr.stop();
  13116. listen_thread.join();
  13117. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13118. std::chrono::steady_clock::now() - start)
  13119. .count();
  13120. EXPECT_LT(elapsed, 3000);
  13121. }
  13122. #endif
  13123. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  13124. protected:
  13125. ServerTestWithAI_PASSIVE()
  13126. : cli_(HOST, PORT)
  13127. #ifdef CPPHTTPLIB_SSL_ENABLED
  13128. ,
  13129. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13130. #endif
  13131. {
  13132. #ifdef CPPHTTPLIB_SSL_ENABLED
  13133. cli_.enable_server_certificate_verification(false);
  13134. #endif
  13135. }
  13136. virtual void SetUp() {
  13137. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  13138. res.set_content("Hello World!", "text/plain");
  13139. });
  13140. t_ = thread(
  13141. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  13142. svr_.wait_until_ready();
  13143. }
  13144. virtual void TearDown() {
  13145. svr_.stop();
  13146. t_.join();
  13147. }
  13148. #ifdef CPPHTTPLIB_SSL_ENABLED
  13149. SSLClient cli_;
  13150. SSLServer svr_;
  13151. #else
  13152. Client cli_;
  13153. Server svr_;
  13154. #endif
  13155. thread t_;
  13156. };
  13157. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  13158. auto res = cli_.Get("/hi");
  13159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13160. EXPECT_EQ(StatusCode::OK_200, res->status);
  13161. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  13162. EXPECT_EQ("Hello World!", res->body);
  13163. }
  13164. class ServerUpDownTest : public ::testing::Test {
  13165. protected:
  13166. ServerUpDownTest() : cli_(HOST, PORT) {}
  13167. virtual void SetUp() {
  13168. t_ = thread([&]() {
  13169. svr_.bind_to_any_port(HOST);
  13170. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13171. ASSERT_TRUE(svr_.listen_after_bind());
  13172. });
  13173. svr_.wait_until_ready();
  13174. }
  13175. virtual void TearDown() {
  13176. svr_.stop();
  13177. t_.join();
  13178. }
  13179. Client cli_;
  13180. Server svr_;
  13181. thread t_;
  13182. };
  13183. TEST_F(ServerUpDownTest, QuickStartStop) {
  13184. // Should not crash, especially when run with
  13185. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  13186. }
  13187. class PayloadMaxLengthTest : public ::testing::Test {
  13188. protected:
  13189. PayloadMaxLengthTest()
  13190. : cli_(HOST, PORT)
  13191. #ifdef CPPHTTPLIB_SSL_ENABLED
  13192. ,
  13193. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13194. #endif
  13195. {
  13196. #ifdef CPPHTTPLIB_SSL_ENABLED
  13197. cli_.enable_server_certificate_verification(false);
  13198. #endif
  13199. }
  13200. virtual void SetUp() {
  13201. svr_.set_payload_max_length(8);
  13202. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13203. res.set_content("test", "text/plain");
  13204. });
  13205. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13206. svr_.wait_until_ready();
  13207. }
  13208. virtual void TearDown() {
  13209. svr_.stop();
  13210. t_.join();
  13211. }
  13212. #ifdef CPPHTTPLIB_SSL_ENABLED
  13213. SSLClient cli_;
  13214. SSLServer svr_;
  13215. #else
  13216. Client cli_;
  13217. Server svr_;
  13218. #endif
  13219. thread t_;
  13220. };
  13221. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  13222. auto res = cli_.Post("/test", "123456789", "text/plain");
  13223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13224. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13225. res = cli_.Post("/test", "12345678", "text/plain");
  13226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13227. EXPECT_EQ(StatusCode::OK_200, res->status);
  13228. }
  13229. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  13230. // Test chunked encoding with payload exceeding the 8-byte limit
  13231. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  13232. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  13233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13234. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13235. }
  13236. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  13237. // Test chunked encoding with payload within the 8-byte limit
  13238. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  13239. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  13240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13241. EXPECT_EQ(StatusCode::OK_200, res->status);
  13242. }
  13243. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  13244. // Test using send_request to send chunked data exceeding payload limit
  13245. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  13246. "Host: " +
  13247. std::string(HOST) + ":" + std::to_string(PORT) +
  13248. "\r\n"
  13249. "Transfer-Encoding: chunked\r\n"
  13250. "Connection: close\r\n"
  13251. "\r\n"
  13252. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  13253. "0123456789\r\n"
  13254. "0\r\n" // End chunk
  13255. "\r\n";
  13256. std::string response;
  13257. bool result = send_request(1, chunked_request, &response);
  13258. if (!result) {
  13259. // If send_request fails, it might be because the server closed the
  13260. // connection due to payload limit enforcement, which is acceptable
  13261. SUCCEED()
  13262. << "Server rejected oversized chunked request (connection closed)";
  13263. } else {
  13264. // If we got a response, check if it's an error response or connection was
  13265. // closed early Short response length indicates connection was closed due to
  13266. // payload limit
  13267. if (response.length() <= 10) {
  13268. SUCCEED() << "Server closed connection for oversized chunked request";
  13269. } else {
  13270. // Check for error status codes
  13271. EXPECT_TRUE(response.find("413") != std::string::npos ||
  13272. response.find("Payload Too Large") != std::string::npos ||
  13273. response.find("400") != std::string::npos);
  13274. }
  13275. }
  13276. }
  13277. class LargePayloadMaxLengthTest : public ::testing::Test {
  13278. protected:
  13279. LargePayloadMaxLengthTest()
  13280. : cli_(HOST, PORT)
  13281. #ifdef CPPHTTPLIB_SSL_ENABLED
  13282. ,
  13283. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13284. #endif
  13285. {
  13286. #ifdef CPPHTTPLIB_SSL_ENABLED
  13287. cli_.enable_server_certificate_verification(false);
  13288. #endif
  13289. }
  13290. virtual void SetUp() {
  13291. // Set 10MB payload limit
  13292. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  13293. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  13294. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13295. res.set_content("Large payload test", "text/plain");
  13296. });
  13297. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13298. svr_.wait_until_ready();
  13299. }
  13300. virtual void TearDown() {
  13301. svr_.stop();
  13302. t_.join();
  13303. }
  13304. #ifdef CPPHTTPLIB_SSL_ENABLED
  13305. SSLClient cli_;
  13306. SSLServer svr_;
  13307. #else
  13308. Client cli_;
  13309. Server svr_;
  13310. #endif
  13311. thread t_;
  13312. };
  13313. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  13314. // Test chunked encoding with payload within 10MB limit
  13315. std::string medium_payload(5 * 1024 * 1024,
  13316. 'A'); // 5MB payload, within 10MB limit
  13317. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  13318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13319. EXPECT_EQ(StatusCode::OK_200, res->status);
  13320. }
  13321. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  13322. // Test chunked encoding with payload exceeding 10MB limit
  13323. std::string large_payload(12 * 1024 * 1024,
  13324. 'B'); // 12MB payload, exceeds 10MB limit
  13325. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  13326. // Server may either return 413 or close the connection
  13327. if (res) {
  13328. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13329. } else {
  13330. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  13331. }
  13332. }
  13333. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  13334. Server svr;
  13335. svr.Get("/", [](const Request &, Response &res) {
  13336. // Claims the most the client accepts, far more than it sends, then drops
  13337. // the connection.
  13338. res.set_content_provider(std::string().max_size(), "text/plain",
  13339. [](size_t, size_t, DataSink &sink) {
  13340. sink.write("abc", 3);
  13341. return false;
  13342. });
  13343. });
  13344. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13345. auto se = detail::scope_exit([&] {
  13346. svr.stop();
  13347. thread.join();
  13348. ASSERT_FALSE(svr.is_running());
  13349. });
  13350. svr.wait_until_ready();
  13351. Client cli(HOST, PORT);
  13352. cli.set_payload_max_length(0);
  13353. EXPECT_FALSE(cli.Get("/"));
  13354. }
  13355. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13356. // Stream API does, not as a plain read failure
  13357. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13358. Server svr;
  13359. svr.Get("/big", [](const Request &, Response &res) {
  13360. res.set_content(std::string(100000, 'b'), "text/plain");
  13361. });
  13362. auto port = svr.bind_to_any_port(HOST);
  13363. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13364. auto se = detail::scope_exit([&] {
  13365. svr.stop();
  13366. thread.join();
  13367. });
  13368. svr.wait_until_ready();
  13369. Client cli(HOST, port);
  13370. cli.set_payload_max_length(1000);
  13371. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13372. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13373. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13374. [](const char *, size_t) { return true; });
  13375. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13376. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13377. // Small on the wire, over the limit once decompressed
  13378. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13379. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13380. #endif
  13381. }
  13382. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13383. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13384. // path.
  13385. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13386. Server svr;
  13387. const size_t LIMIT = 64 * 1024; // 64KB
  13388. svr.set_payload_max_length(LIMIT);
  13389. size_t total = 0;
  13390. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13391. const ContentReader &content_reader) {
  13392. content_reader([&](const char * /*data*/, size_t len) {
  13393. total += len;
  13394. return true;
  13395. });
  13396. res.status = 200;
  13397. res.set_content("stream_ok", "text/plain");
  13398. });
  13399. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13400. auto se = detail::scope_exit([&] {
  13401. svr.stop();
  13402. thread.join();
  13403. ASSERT_FALSE(svr.is_running());
  13404. });
  13405. svr.wait_until_ready();
  13406. // Prepare 256KB raw data and gzip-compress it
  13407. std::string raw(256 * 1024, 'A');
  13408. std::string gz;
  13409. {
  13410. z_stream zs{};
  13411. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13412. Z_DEFAULT_STRATEGY);
  13413. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13414. zs.avail_in = static_cast<uInt>(raw.size());
  13415. char outbuf[4096];
  13416. int ret;
  13417. do {
  13418. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13419. zs.avail_out = sizeof(outbuf);
  13420. ret = deflate(&zs, Z_FINISH);
  13421. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13422. } while (ret != Z_STREAM_END);
  13423. deflateEnd(&zs);
  13424. }
  13425. Client cli(HOST, PORT);
  13426. cli.set_connection_timeout(std::chrono::seconds(5));
  13427. Headers headers = {{"Content-Encoding", "gzip"}};
  13428. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13429. "application/octet-stream");
  13430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13431. // Server must reject oversized decompressed payloads with 413.
  13432. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13433. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13434. EXPECT_LE(total, LIMIT);
  13435. }
  13436. #endif
  13437. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13438. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13439. // the payload must be passed through untouched instead of being rejected.
  13440. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13441. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13442. Server svr;
  13443. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13444. res.set_content(body, "image/jpeg");
  13445. res.set_header("Content-Encoding", "UTF-8");
  13446. });
  13447. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13448. res.set_content(body, "image/jpeg");
  13449. res.set_header("Content-Encoding", "identity");
  13450. });
  13451. svr.Post("/echo", [](const Request &req, Response &res) {
  13452. res.set_content(req.body, "image/jpeg");
  13453. });
  13454. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13455. auto se = detail::scope_exit([&] {
  13456. svr.stop();
  13457. t.join();
  13458. ASSERT_FALSE(svr.is_running());
  13459. });
  13460. svr.wait_until_ready();
  13461. Client cli(HOST, PORT);
  13462. {
  13463. auto res = cli.Get("/image");
  13464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13465. EXPECT_EQ(StatusCode::OK_200, res->status);
  13466. EXPECT_EQ(body, res->body);
  13467. }
  13468. {
  13469. auto res = cli.Get("/identity");
  13470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13471. EXPECT_EQ(StatusCode::OK_200, res->status);
  13472. EXPECT_EQ(body, res->body);
  13473. }
  13474. {
  13475. // The same applies to a request body reaching the server.
  13476. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13477. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13479. EXPECT_EQ(StatusCode::OK_200, res->status);
  13480. EXPECT_EQ(body, res->body);
  13481. }
  13482. }
  13483. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13484. // gzip-encoded response even when the build has no zlib support.
  13485. static const char GZIPPED_HELLO_WORLD[] = {
  13486. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13487. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13488. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13489. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13490. // A content coding is a whole token, not something the field value merely
  13491. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13492. // as "fibre" look like Brotli, and turned a multi-coding value like
  13493. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13494. // it was never meant to see.
  13495. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13496. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13497. Server svr;
  13498. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13499. res.set_content(body, "image/jpeg");
  13500. res.set_header("Content-Encoding", "fibre");
  13501. });
  13502. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13503. res.set_content(body, "image/jpeg");
  13504. res.set_header("Content-Encoding", "gzip, br");
  13505. });
  13506. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13507. res.set_content(body, "image/jpeg");
  13508. res.set_header("Content-Encoding", "x-zstd-ish");
  13509. });
  13510. auto port = svr.bind_to_any_port(HOST);
  13511. thread t = thread([&]() { svr.listen_after_bind(); });
  13512. auto se = detail::scope_exit([&] {
  13513. svr.stop();
  13514. t.join();
  13515. ASSERT_FALSE(svr.is_running());
  13516. });
  13517. svr.wait_until_ready();
  13518. Client cli(HOST, port);
  13519. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13520. auto res = cli.Get(path);
  13521. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13522. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13523. // Not a coding we recognize, so the payload comes back untouched
  13524. EXPECT_EQ(body, res->body) << path;
  13525. }
  13526. }
  13527. // A content coding cpp-httplib recognizes but was not built with must be
  13528. // reported as such. Handing the still-compressed payload back to the caller
  13529. // would silently corrupt it.
  13530. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13531. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13532. Server svr;
  13533. // "image/jpeg" keeps the server from applying a content coding of its own,
  13534. // so the hand-crafted Content-Encoding below survives.
  13535. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13536. res.set_content(gzipped, "image/jpeg");
  13537. res.set_header("Content-Encoding", "gzip");
  13538. });
  13539. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13540. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13541. res.set_content(gzipped, "image/jpeg");
  13542. res.set_header("Content-Encoding", "GZIP");
  13543. });
  13544. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13545. auto se = detail::scope_exit([&] {
  13546. svr.stop();
  13547. t.join();
  13548. ASSERT_FALSE(svr.is_running());
  13549. });
  13550. svr.wait_until_ready();
  13551. Client cli(HOST, PORT);
  13552. {
  13553. auto res = cli.Get("/gzipped");
  13554. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13556. EXPECT_EQ("Hello World!", res->body);
  13557. #else
  13558. ASSERT_FALSE(res);
  13559. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13560. #endif
  13561. }
  13562. {
  13563. // open_stream() must behave the same way.
  13564. auto handle = cli.open_stream("GET", "/gzipped");
  13565. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13566. ASSERT_TRUE(handle.is_valid());
  13567. std::string received;
  13568. char buf[256];
  13569. ssize_t n;
  13570. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13571. received.append(buf, static_cast<size_t>(n));
  13572. }
  13573. EXPECT_EQ("Hello World!", received);
  13574. #else
  13575. EXPECT_FALSE(handle.is_valid());
  13576. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13577. #endif
  13578. }
  13579. {
  13580. // A differently-cased coding must not be mistaken for an unknown one, or
  13581. // the body would be handed back still compressed.
  13582. auto res = cli.Get("/gzipped-uppercase");
  13583. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13585. EXPECT_EQ("Hello World!", res->body);
  13586. #else
  13587. ASSERT_FALSE(res);
  13588. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13589. #endif
  13590. }
  13591. }
  13592. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13593. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13594. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13595. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13596. // body a second time and appending a second Content-Encoding field line, so
  13597. // clients that decode one coding per listed value handed back raw gzip bytes.
  13598. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13599. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13600. Server svr;
  13601. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13602. // keeps the server from applying a coding of its own.
  13603. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13604. res.set_content(gzipped, "text/plain");
  13605. res.set_header("Content-Encoding", "gzip");
  13606. });
  13607. auto port = svr.bind_to_any_port(HOST);
  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. Client cli(HOST, port);
  13616. Headers headers = {{"Accept-Encoding", "gzip"}};
  13617. auto res = cli.Get("/pre-gzipped", headers);
  13618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13619. EXPECT_EQ(StatusCode::OK_200, res->status);
  13620. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13621. EXPECT_EQ("Hello World!", res->body);
  13622. }
  13623. // set_compress(false) sends every handler response as it is, buffered or
  13624. // streamed
  13625. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13626. const std::string text(1000, 'a');
  13627. Server svr;
  13628. svr.set_compress(false);
  13629. svr.Get("/buffered", [&](const Request &, Response &res) {
  13630. res.set_content(text, "text/plain");
  13631. });
  13632. svr.Get("/streamed", [&](const Request &, Response &res) {
  13633. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13634. sink.write(text.data(), text.size());
  13635. sink.done();
  13636. return true;
  13637. });
  13638. });
  13639. auto port = svr.bind_to_any_port(HOST);
  13640. ASSERT_LT(0, port);
  13641. thread t = thread([&] { svr.listen_after_bind(); });
  13642. auto se = detail::scope_exit([&] {
  13643. svr.stop();
  13644. t.join();
  13645. ASSERT_FALSE(svr.is_running());
  13646. });
  13647. svr.wait_until_ready();
  13648. Client cli(HOST, port);
  13649. cli.set_decompress(false);
  13650. for (auto path : {"/buffered", "/streamed"}) {
  13651. SCOPED_TRACE(path);
  13652. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13654. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13655. EXPECT_EQ(text, res->body);
  13656. }
  13657. }
  13658. // A chunked provider settles its coding where the headers are written and
  13659. // reuses it at write time. Both ends of that have to hold: a handler's own
  13660. // Content-Encoding suppresses the coding, and a response without one is still
  13661. // compressed as it always was.
  13662. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13663. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13664. const std::string plain = "Hello World! Hello World! Hello World!";
  13665. Server svr;
  13666. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13667. res.set_header("Content-Encoding", "gzip");
  13668. res.set_chunked_content_provider(
  13669. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13670. sink.write(gzipped.data(), gzipped.size());
  13671. sink.done();
  13672. return true;
  13673. });
  13674. });
  13675. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13676. res.set_chunked_content_provider(
  13677. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13678. sink.write(plain.data(), plain.size());
  13679. sink.done();
  13680. return true;
  13681. });
  13682. });
  13683. auto port = svr.bind_to_any_port(HOST);
  13684. thread t = thread([&]() { svr.listen_after_bind(); });
  13685. auto se = detail::scope_exit([&] {
  13686. svr.stop();
  13687. t.join();
  13688. ASSERT_FALSE(svr.is_running());
  13689. });
  13690. svr.wait_until_ready();
  13691. Client cli(HOST, port);
  13692. Headers headers = {{"Accept-Encoding", "gzip"}};
  13693. {
  13694. auto res = cli.Get("/pre-gzipped", headers);
  13695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13696. EXPECT_EQ(StatusCode::OK_200, res->status);
  13697. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13698. EXPECT_EQ("Hello World!", res->body);
  13699. }
  13700. {
  13701. auto res = cli.Get("/negotiated", headers);
  13702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13703. EXPECT_EQ(StatusCode::OK_200, res->status);
  13704. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13705. EXPECT_EQ(plain, res->body);
  13706. }
  13707. }
  13708. #endif
  13709. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13710. // the same message as the comma-joined one, so both have to be read the same
  13711. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13712. // single gzip coding, and a body the sender says was encoded twice was handed
  13713. // back after one pass, still compressed but presented as decoded.
  13714. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13715. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13716. Server svr;
  13717. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13718. res.set_content(body, "image/jpeg");
  13719. res.headers.emplace("Content-Encoding", "gzip");
  13720. res.headers.emplace("Content-Encoding", "gzip");
  13721. });
  13722. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13723. res.set_content(body, "image/jpeg");
  13724. res.set_header("Content-Encoding", "gzip, gzip");
  13725. });
  13726. auto port = svr.bind_to_any_port(HOST);
  13727. thread t = thread([&]() { svr.listen_after_bind(); });
  13728. auto se = detail::scope_exit([&] {
  13729. svr.stop();
  13730. t.join();
  13731. ASSERT_FALSE(svr.is_running());
  13732. });
  13733. svr.wait_until_ready();
  13734. Client cli(HOST, port);
  13735. // Two codings is not something cpp-httplib decodes, so both representations
  13736. // take the pass-through path rather than one of them being gunzipped once.
  13737. for (const char *path : {"/split", "/joined"}) {
  13738. auto res = cli.Get(path);
  13739. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13740. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13741. EXPECT_EQ(body, res->body) << path;
  13742. }
  13743. }
  13744. // Regression test for DoS vulnerability: a malicious server sending a response
  13745. // without Content-Length header must not cause unbounded memory consumption on
  13746. // the client side. The client should stop reading after a reasonable limit,
  13747. // similar to the server-side set_payload_max_length protection.
  13748. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13749. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13750. #ifndef _WIN32
  13751. signal(SIGPIPE, SIG_IGN);
  13752. #endif
  13753. auto server_thread = std::thread([] {
  13754. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13755. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13756. default_socket_options(srv);
  13757. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13758. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13759. sockaddr_in addr{};
  13760. addr.sin_family = AF_INET;
  13761. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13762. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13763. int opt = 1;
  13764. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13765. #ifdef _WIN32
  13766. reinterpret_cast<const char *>(&opt),
  13767. #else
  13768. &opt,
  13769. #endif
  13770. sizeof(opt));
  13771. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13772. ::listen(srv, 1);
  13773. sockaddr_in cli_addr{};
  13774. socklen_t cli_len = sizeof(cli_addr);
  13775. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13776. if (cli != INVALID_SOCKET) {
  13777. char buf[4096];
  13778. ::recv(cli, buf, sizeof(buf), 0);
  13779. // Malicious response: no Content-Length, no chunked encoding
  13780. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13781. "Connection: close\r\n"
  13782. "\r\n";
  13783. ::send(cli,
  13784. #ifdef _WIN32
  13785. static_cast<const char *>(response_header.c_str()),
  13786. static_cast<int>(response_header.size()),
  13787. #else
  13788. response_header.c_str(), response_header.size(),
  13789. #endif
  13790. 0);
  13791. // Send 10MB of data
  13792. std::string chunk(64 * 1024, 'A');
  13793. size_t total_sent = 0;
  13794. while (total_sent < MALICIOUS_DATA_SIZE) {
  13795. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13796. auto sent = ::send(cli,
  13797. #ifdef _WIN32
  13798. static_cast<const char *>(chunk.c_str()),
  13799. static_cast<int>(to_send),
  13800. #else
  13801. chunk.c_str(), to_send,
  13802. #endif
  13803. 0);
  13804. if (sent <= 0) break;
  13805. total_sent += static_cast<size_t>(sent);
  13806. }
  13807. detail::close_socket(cli);
  13808. }
  13809. detail::close_socket(srv);
  13810. });
  13811. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13812. size_t total_read = 0;
  13813. {
  13814. Client cli("127.0.0.1", PORT + 2);
  13815. cli.set_read_timeout(5, 0);
  13816. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13817. auto stream = cli.open_stream("GET", "/malicious");
  13818. ASSERT_TRUE(stream.is_valid());
  13819. char buffer[64 * 1024];
  13820. ssize_t n;
  13821. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13822. total_read += static_cast<size_t>(n);
  13823. }
  13824. } // StreamHandle and Client destroyed here, closing the socket
  13825. server_thread.join();
  13826. // With set_payload_max_length, the client must stop reading before consuming
  13827. // all 10MB. The read loop should be cut off at or near the configured limit.
  13828. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13829. << "Client read " << total_read << " bytes, exceeding the configured "
  13830. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13831. }
  13832. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13833. // the entire response body without truncation.
  13834. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13835. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13836. #ifndef _WIN32
  13837. signal(SIGPIPE, SIG_IGN);
  13838. #endif
  13839. auto server_thread = std::thread([] {
  13840. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13841. default_socket_options(srv);
  13842. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13843. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13844. sockaddr_in addr{};
  13845. addr.sin_family = AF_INET;
  13846. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13847. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13848. int opt = 1;
  13849. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13850. #ifdef _WIN32
  13851. reinterpret_cast<const char *>(&opt),
  13852. #else
  13853. &opt,
  13854. #endif
  13855. sizeof(opt));
  13856. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13857. ::listen(srv, 1);
  13858. sockaddr_in cli_addr{};
  13859. socklen_t cli_len = sizeof(cli_addr);
  13860. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13861. if (cli != INVALID_SOCKET) {
  13862. char buf[4096];
  13863. ::recv(cli, buf, sizeof(buf), 0);
  13864. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13865. "Connection: close\r\n"
  13866. "\r\n";
  13867. ::send(cli,
  13868. #ifdef _WIN32
  13869. static_cast<const char *>(response_header.c_str()),
  13870. static_cast<int>(response_header.size()),
  13871. #else
  13872. response_header.c_str(), response_header.size(),
  13873. #endif
  13874. 0);
  13875. std::string chunk(64 * 1024, 'A');
  13876. size_t total_sent = 0;
  13877. while (total_sent < DATA_SIZE) {
  13878. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13879. auto sent = ::send(cli,
  13880. #ifdef _WIN32
  13881. static_cast<const char *>(chunk.c_str()),
  13882. static_cast<int>(to_send),
  13883. #else
  13884. chunk.c_str(), to_send,
  13885. #endif
  13886. 0);
  13887. if (sent <= 0) break;
  13888. total_sent += static_cast<size_t>(sent);
  13889. }
  13890. #ifdef _WIN32
  13891. ::shutdown(cli, SD_SEND);
  13892. #else
  13893. ::shutdown(cli, SHUT_WR);
  13894. #endif
  13895. // Drain until the client closes its end, ensuring all data is delivered
  13896. char drain[1024];
  13897. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13898. detail::close_socket(cli);
  13899. }
  13900. detail::close_socket(srv);
  13901. });
  13902. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13903. size_t total_read = 0;
  13904. {
  13905. Client cli("127.0.0.1", PORT + 2);
  13906. cli.set_read_timeout(5, 0);
  13907. cli.set_payload_max_length(0); // 0 means no limit
  13908. auto stream = cli.open_stream("GET", "/data");
  13909. ASSERT_TRUE(stream.is_valid());
  13910. char buffer[64 * 1024];
  13911. ssize_t n;
  13912. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13913. total_read += static_cast<size_t>(n);
  13914. }
  13915. }
  13916. server_thread.join();
  13917. EXPECT_EQ(total_read, DATA_SIZE)
  13918. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13919. << " bytes without truncation, but only read " << total_read << " bytes.";
  13920. }
  13921. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13922. // enormous Content-Length must not cause the client to pre-allocate a huge
  13923. // response body buffer. The reservation is capped at payload_max_length_, and
  13924. // the read itself fails when the body exceeds the limit.
  13925. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13926. #ifndef _WIN32
  13927. signal(SIGPIPE, SIG_IGN);
  13928. #endif
  13929. auto server_thread = std::thread([] {
  13930. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13931. default_socket_options(srv);
  13932. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13933. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13934. sockaddr_in addr{};
  13935. addr.sin_family = AF_INET;
  13936. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13937. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13938. int opt = 1;
  13939. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13940. #ifdef _WIN32
  13941. reinterpret_cast<const char *>(&opt),
  13942. #else
  13943. &opt,
  13944. #endif
  13945. sizeof(opt));
  13946. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13947. ::listen(srv, 1);
  13948. sockaddr_in cli_addr{};
  13949. socklen_t cli_len = sizeof(cli_addr);
  13950. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13951. if (cli != INVALID_SOCKET) {
  13952. char buf[4096];
  13953. ::recv(cli, buf, sizeof(buf), 0);
  13954. // Malicious response: claim a 20GB body but send only a tiny payload.
  13955. std::string response = "HTTP/1.1 200 OK\r\n"
  13956. "Content-Length: 20000000000\r\n"
  13957. "\r\n"
  13958. "abc";
  13959. ::send(cli,
  13960. #ifdef _WIN32
  13961. static_cast<const char *>(response.c_str()),
  13962. static_cast<int>(response.size()),
  13963. #else
  13964. response.c_str(), response.size(),
  13965. #endif
  13966. 0);
  13967. detail::close_socket(cli);
  13968. }
  13969. detail::close_socket(srv);
  13970. });
  13971. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13972. {
  13973. Client cli("127.0.0.1", PORT + 2);
  13974. cli.set_read_timeout(5, 0);
  13975. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13976. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13977. // (server claims more bytes than payload_max_length permits), but it must
  13978. // not exhaust memory before getting there.
  13979. auto res = cli.Get("/malicious");
  13980. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13981. }
  13982. server_thread.join();
  13983. }
  13984. // Verify that content_receiver bypasses the default payload_max_length,
  13985. // allowing streaming downloads larger than 100MB without requiring an explicit
  13986. // set_payload_max_length call.
  13987. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13988. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13989. #ifndef _WIN32
  13990. signal(SIGPIPE, SIG_IGN);
  13991. #endif
  13992. auto server_thread = std::thread([] {
  13993. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13994. default_socket_options(srv);
  13995. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13996. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13997. sockaddr_in addr{};
  13998. addr.sin_family = AF_INET;
  13999. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  14000. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14001. int opt = 1;
  14002. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14003. #ifdef _WIN32
  14004. reinterpret_cast<const char *>(&opt),
  14005. #else
  14006. &opt,
  14007. #endif
  14008. sizeof(opt));
  14009. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14010. ::listen(srv, 1);
  14011. sockaddr_in cli_addr{};
  14012. socklen_t cli_len = sizeof(cli_addr);
  14013. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14014. if (cli != INVALID_SOCKET) {
  14015. char buf[4096];
  14016. ::recv(cli, buf, sizeof(buf), 0);
  14017. // Response with Content-Length larger than default 100MB limit
  14018. auto content_length = std::to_string(DATA_SIZE);
  14019. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14020. "Content-Length: " +
  14021. content_length +
  14022. "\r\n"
  14023. "Connection: close\r\n"
  14024. "\r\n";
  14025. ::send(cli,
  14026. #ifdef _WIN32
  14027. static_cast<const char *>(response_header.c_str()),
  14028. static_cast<int>(response_header.size()),
  14029. #else
  14030. response_header.c_str(), response_header.size(),
  14031. #endif
  14032. 0);
  14033. std::string chunk(64 * 1024, 'A');
  14034. size_t total_sent = 0;
  14035. while (total_sent < DATA_SIZE) {
  14036. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  14037. auto sent = ::send(cli,
  14038. #ifdef _WIN32
  14039. static_cast<const char *>(chunk.c_str()),
  14040. static_cast<int>(to_send),
  14041. #else
  14042. chunk.c_str(), to_send,
  14043. #endif
  14044. 0);
  14045. if (sent <= 0) break;
  14046. total_sent += static_cast<size_t>(sent);
  14047. }
  14048. detail::close_socket(cli);
  14049. }
  14050. detail::close_socket(srv);
  14051. });
  14052. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14053. size_t total_received = 0;
  14054. {
  14055. Client cli("127.0.0.1", PORT + 2);
  14056. cli.set_read_timeout(10, 0);
  14057. // Do NOT call set_payload_max_length — use the default 100MB limit
  14058. auto res =
  14059. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14060. total_received += data_length;
  14061. return true;
  14062. });
  14063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14064. EXPECT_EQ(StatusCode::OK_200, res->status);
  14065. }
  14066. server_thread.join();
  14067. EXPECT_EQ(total_received, DATA_SIZE)
  14068. << "With content_receiver, the client should read all " << DATA_SIZE
  14069. << " bytes despite the default 100MB payload_max_length, but only read "
  14070. << total_received << " bytes.";
  14071. }
  14072. // Verify that an explicit set_payload_max_length smaller than the response is
  14073. // enforced even when a content_receiver is used.
  14074. TEST(ClientVulnerabilityTest,
  14075. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  14076. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  14077. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  14078. #ifndef _WIN32
  14079. signal(SIGPIPE, SIG_IGN);
  14080. #endif
  14081. auto server_thread = std::thread([] {
  14082. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14083. default_socket_options(srv);
  14084. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14085. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14086. sockaddr_in addr{};
  14087. addr.sin_family = AF_INET;
  14088. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  14089. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14090. int opt = 1;
  14091. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14092. #ifdef _WIN32
  14093. reinterpret_cast<const char *>(&opt),
  14094. #else
  14095. &opt,
  14096. #endif
  14097. sizeof(opt));
  14098. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14099. ::listen(srv, 1);
  14100. sockaddr_in cli_addr{};
  14101. socklen_t cli_len = sizeof(cli_addr);
  14102. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14103. if (cli != INVALID_SOCKET) {
  14104. char buf[4096];
  14105. ::recv(cli, buf, sizeof(buf), 0);
  14106. auto content_length = std::to_string(DATA_SIZE);
  14107. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14108. "Content-Length: " +
  14109. content_length +
  14110. "\r\n"
  14111. "Connection: close\r\n"
  14112. "\r\n";
  14113. ::send(cli,
  14114. #ifdef _WIN32
  14115. static_cast<const char *>(response_header.c_str()),
  14116. static_cast<int>(response_header.size()),
  14117. #else
  14118. response_header.c_str(), response_header.size(),
  14119. #endif
  14120. 0);
  14121. std::string chunk(64 * 1024, 'A');
  14122. size_t total_sent = 0;
  14123. while (total_sent < DATA_SIZE) {
  14124. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  14125. auto sent = ::send(cli,
  14126. #ifdef _WIN32
  14127. static_cast<const char *>(chunk.c_str()),
  14128. static_cast<int>(to_send),
  14129. #else
  14130. chunk.c_str(), to_send,
  14131. #endif
  14132. 0);
  14133. if (sent <= 0) break;
  14134. total_sent += static_cast<size_t>(sent);
  14135. }
  14136. detail::close_socket(cli);
  14137. }
  14138. detail::close_socket(srv);
  14139. });
  14140. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14141. size_t total_received = 0;
  14142. {
  14143. Client cli("127.0.0.1", PORT + 2);
  14144. cli.set_read_timeout(10, 0);
  14145. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  14146. auto res =
  14147. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14148. total_received += data_length;
  14149. return true;
  14150. });
  14151. // Should fail because 200MB exceeds the explicit 150MB limit
  14152. EXPECT_FALSE(res);
  14153. }
  14154. server_thread.join();
  14155. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  14156. << "Client with content_receiver should respect the explicit "
  14157. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  14158. << total_received << " bytes.";
  14159. }
  14160. // Verify that an explicit set_payload_max_length larger than the response
  14161. // allows the content_receiver to read all data successfully.
  14162. TEST(ClientVulnerabilityTest,
  14163. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  14164. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  14165. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  14166. #ifndef _WIN32
  14167. signal(SIGPIPE, SIG_IGN);
  14168. #endif
  14169. auto server_thread = std::thread([] {
  14170. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14171. default_socket_options(srv);
  14172. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14173. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14174. sockaddr_in addr{};
  14175. addr.sin_family = AF_INET;
  14176. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  14177. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14178. int opt = 1;
  14179. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14180. #ifdef _WIN32
  14181. reinterpret_cast<const char *>(&opt),
  14182. #else
  14183. &opt,
  14184. #endif
  14185. sizeof(opt));
  14186. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14187. ::listen(srv, 1);
  14188. sockaddr_in cli_addr{};
  14189. socklen_t cli_len = sizeof(cli_addr);
  14190. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14191. if (cli != INVALID_SOCKET) {
  14192. char buf[4096];
  14193. ::recv(cli, buf, sizeof(buf), 0);
  14194. auto content_length = std::to_string(DATA_SIZE);
  14195. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14196. "Content-Length: " +
  14197. content_length +
  14198. "\r\n"
  14199. "Connection: close\r\n"
  14200. "\r\n";
  14201. ::send(cli,
  14202. #ifdef _WIN32
  14203. static_cast<const char *>(response_header.c_str()),
  14204. static_cast<int>(response_header.size()),
  14205. #else
  14206. response_header.c_str(), response_header.size(),
  14207. #endif
  14208. 0);
  14209. std::string chunk(64 * 1024, 'A');
  14210. size_t total_sent = 0;
  14211. while (total_sent < DATA_SIZE) {
  14212. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  14213. auto sent = ::send(cli,
  14214. #ifdef _WIN32
  14215. static_cast<const char *>(chunk.c_str()),
  14216. static_cast<int>(to_send),
  14217. #else
  14218. chunk.c_str(), to_send,
  14219. #endif
  14220. 0);
  14221. if (sent <= 0) break;
  14222. total_sent += static_cast<size_t>(sent);
  14223. }
  14224. #ifdef _WIN32
  14225. ::shutdown(cli, SD_SEND);
  14226. #else
  14227. ::shutdown(cli, SHUT_WR);
  14228. #endif
  14229. char drain[1024];
  14230. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  14231. detail::close_socket(cli);
  14232. }
  14233. detail::close_socket(srv);
  14234. });
  14235. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14236. size_t total_received = 0;
  14237. {
  14238. Client cli("127.0.0.1", PORT + 2);
  14239. cli.set_read_timeout(10, 0);
  14240. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  14241. auto res =
  14242. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14243. total_received += data_length;
  14244. return true;
  14245. });
  14246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14247. EXPECT_EQ(StatusCode::OK_200, res->status);
  14248. }
  14249. server_thread.join();
  14250. EXPECT_EQ(total_received, DATA_SIZE)
  14251. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  14252. << " bytes (larger than " << DATA_SIZE
  14253. << " bytes response), content_receiver should read all data, but only "
  14254. "read "
  14255. << total_received << " bytes.";
  14256. }
  14257. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  14258. // Regression test for "zip bomb" attack on the client side: a malicious server
  14259. // sends a small gzip-compressed response that decompresses to a huge payload.
  14260. // The client must enforce payload_max_length on the decompressed size.
  14261. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  14262. constexpr size_t DECOMPRESSED_SIZE =
  14263. 10 * 1024 * 1024; // 10MB after decompression
  14264. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  14265. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  14266. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  14267. std::string compressed;
  14268. {
  14269. httplib::detail::gzip_compressor compressor;
  14270. bool ok =
  14271. compressor.compress(uncompressed.data(), uncompressed.size(),
  14272. /*last=*/true, [&](const char *buf, size_t len) {
  14273. compressed.append(buf, len);
  14274. return true;
  14275. });
  14276. ASSERT_TRUE(ok);
  14277. }
  14278. // Sanity: compressed data should be much smaller than the decompressed size
  14279. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  14280. #ifndef _WIN32
  14281. signal(SIGPIPE, SIG_IGN);
  14282. #endif
  14283. // Set up the listening socket in the main thread so the server is guaranteed
  14284. // to be ready before the client connects (eliminates race condition).
  14285. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14286. default_socket_options(srv);
  14287. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14288. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14289. sockaddr_in addr{};
  14290. addr.sin_family = AF_INET;
  14291. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  14292. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14293. int opt = 1;
  14294. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14295. #ifdef _WIN32
  14296. reinterpret_cast<const char *>(&opt),
  14297. #else
  14298. &opt,
  14299. #endif
  14300. sizeof(opt));
  14301. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14302. ASSERT_EQ(0, ::listen(srv, 1));
  14303. auto server_thread = std::thread([&compressed, srv] {
  14304. sockaddr_in cli_addr{};
  14305. socklen_t cli_len = sizeof(cli_addr);
  14306. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14307. if (cli != INVALID_SOCKET) {
  14308. // Read the full HTTP request (until \r\n\r\n)
  14309. char buf[4096];
  14310. size_t total = 0;
  14311. while (total < sizeof(buf)) {
  14312. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  14313. if (n <= 0) break;
  14314. total += static_cast<size_t>(n);
  14315. // Check for end of headers
  14316. if (total >= 4) {
  14317. std::string req(buf, total);
  14318. if (req.find("\r\n\r\n") != std::string::npos) break;
  14319. }
  14320. }
  14321. // Malicious response: gzip-compressed body, no Content-Length
  14322. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14323. "Content-Encoding: gzip\r\n"
  14324. "Connection: close\r\n"
  14325. "\r\n";
  14326. ::send(cli,
  14327. #ifdef _WIN32
  14328. static_cast<const char *>(response_header.c_str()),
  14329. static_cast<int>(response_header.size()),
  14330. #else
  14331. response_header.c_str(), response_header.size(),
  14332. #endif
  14333. 0);
  14334. // Send the compressed payload (small on the wire, huge when decompressed)
  14335. size_t total_sent = 0;
  14336. while (total_sent < compressed.size()) {
  14337. auto to_send = std::min(compressed.size() - total_sent,
  14338. static_cast<size_t>(64 * 1024));
  14339. auto sent =
  14340. ::send(cli,
  14341. #ifdef _WIN32
  14342. static_cast<const char *>(compressed.c_str() + total_sent),
  14343. static_cast<int>(to_send),
  14344. #else
  14345. compressed.c_str() + total_sent, to_send,
  14346. #endif
  14347. 0);
  14348. if (sent <= 0) break;
  14349. total_sent += static_cast<size_t>(sent);
  14350. }
  14351. detail::close_socket(cli);
  14352. }
  14353. });
  14354. auto se = detail::scope_exit([&] {
  14355. detail::close_socket(srv);
  14356. server_thread.join();
  14357. });
  14358. size_t total_decompressed = 0;
  14359. {
  14360. Client cli("127.0.0.1", PORT + 3);
  14361. cli.set_read_timeout(5, 0);
  14362. cli.set_decompress(true);
  14363. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14364. auto stream = cli.open_stream("GET", "/zipbomb");
  14365. ASSERT_TRUE(stream.is_valid());
  14366. char buffer[64 * 1024];
  14367. ssize_t n;
  14368. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14369. total_decompressed += static_cast<size_t>(n);
  14370. }
  14371. }
  14372. // The decompressed size must be capped by payload_max_length. Without
  14373. // protection, the client would decompress the full 10MB from a tiny
  14374. // compressed payload, enabling a zip bomb DoS attack.
  14375. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14376. << "Client decompressed " << total_decompressed
  14377. << " bytes from a gzip response. The decompressed size should be "
  14378. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14379. }
  14380. #endif
  14381. TEST(HostAndPortPropertiesTest, NoSSL) {
  14382. httplib::Client cli("www.google.com", 1234);
  14383. ASSERT_EQ("www.google.com", cli.host());
  14384. ASSERT_EQ(1234, cli.port());
  14385. }
  14386. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14387. httplib::Client cli("www.google.com:1234");
  14388. ASSERT_EQ("www.google.com", cli.host());
  14389. ASSERT_EQ(1234, cli.port());
  14390. }
  14391. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14392. // Port number that overflows int — should not crash, client becomes invalid
  14393. httplib::Client cli("http://www.google.com:99999999999999999999");
  14394. ASSERT_FALSE(cli.is_valid());
  14395. }
  14396. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14397. // Port 99999 exceeds valid range (1-65535) — should not crash
  14398. httplib::Client cli("http://www.google.com:99999");
  14399. ASSERT_FALSE(cli.is_valid());
  14400. auto res = cli.Get("/");
  14401. EXPECT_FALSE(res);
  14402. EXPECT_EQ(Error::Connection, res.error());
  14403. }
  14404. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14405. httplib::Client cli("http://user:pass@localhost:1234");
  14406. ASSERT_FALSE(cli.is_valid());
  14407. EXPECT_FALSE(cli.Get("/"));
  14408. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14409. }
  14410. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14411. httplib::Client cli("http://www.google.com:80abc");
  14412. ASSERT_FALSE(cli.is_valid());
  14413. }
  14414. #ifdef CPPHTTPLIB_SSL_ENABLED
  14415. TEST(HostAndPortPropertiesTest, SSL) {
  14416. httplib::SSLClient cli("www.google.com");
  14417. ASSERT_EQ("www.google.com", cli.host());
  14418. ASSERT_EQ(443, cli.port());
  14419. }
  14420. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14421. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14422. std::string cert;
  14423. read_file(CA_CERT_FILE, cert);
  14424. httplib::SSLClient httplib_client("www.google.com");
  14425. // Load CA store first time
  14426. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14427. // Load CA store second time (update)
  14428. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14429. // Verify client is still valid and can make connections
  14430. httplib_client.enable_server_certificate_verification(true);
  14431. auto res = httplib_client.Get("/");
  14432. // Any status: Google may redirect or rate-limit CI runners.
  14433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14434. }
  14435. TEST(SSLClientTest, ServerNameIndication_Online) {
  14436. auto host = "httpbingo.org";
  14437. auto path = std::string{"/get"};
  14438. SSLClient cli(host, 443);
  14439. auto res = retry_service_failures([&] { return cli.Get(path); });
  14440. SKIP_ON_SERVICE_FAILURE(res);
  14441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14442. ASSERT_EQ(StatusCode::OK_200, res->status);
  14443. }
  14444. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14445. // Use a site that will cause SSL verification failure due to self-signed cert
  14446. SSLClient cli("self-signed.badssl.com", 443);
  14447. cli.enable_server_certificate_verification(true);
  14448. auto res = retry_service_failures([&] { return cli.Get("/"); });
  14449. SKIP_ON_SERVICE_FAILURE(res);
  14450. ASSERT_TRUE(!res);
  14451. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14452. // Verify backend error is captured for SSLServerVerification
  14453. // This occurs when certificate verification fails
  14454. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14455. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14456. EXPECT_NE(0UL, res.ssl_backend_error());
  14457. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14458. res.ssl_error());
  14459. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14460. #if !defined(_WIN32) || \
  14461. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14462. // On non-Windows or when Windows Schannel is disabled, the error comes
  14463. // from OpenSSL's verification
  14464. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14465. res.ssl_backend_error());
  14466. #endif
  14467. #endif
  14468. }
  14469. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14470. // Use a site where hostname doesn't match the certificate
  14471. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14472. SSLClient cli("wrong.host.badssl.com", 443);
  14473. cli.enable_server_certificate_verification(true);
  14474. cli.enable_server_hostname_verification(true);
  14475. auto res = retry_service_failures([&] { return cli.Get("/"); });
  14476. SKIP_ON_SERVICE_FAILURE(res);
  14477. ASSERT_TRUE(!res);
  14478. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14479. // Verify backend error is captured for hostname verification failure
  14480. EXPECT_NE(0UL, res.ssl_backend_error());
  14481. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14482. res.ssl_error());
  14483. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14484. #if !defined(_WIN32) || \
  14485. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14486. // On non-Windows or when Windows Schannel is disabled, the error comes
  14487. // from OpenSSL's hostname verification
  14488. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14489. res.ssl_backend_error());
  14490. #endif
  14491. #endif
  14492. }
  14493. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14494. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14495. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14496. SSLClient cli("www.google.com", 443);
  14497. cli.enable_server_certificate_verification(true);
  14498. auto res = cli.Get("/");
  14499. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14500. }
  14501. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14502. SSLClient cli("www.google.com", 443);
  14503. cli.enable_server_certificate_verification(true);
  14504. cli.enable_windows_certificate_verification(false);
  14505. auto res = cli.Get("/");
  14506. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14507. }
  14508. // The server sends an intermediate cross-signed by a root Windows trusts,
  14509. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14510. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14511. SSLClient cli("accounts.spotify.com", 443);
  14512. auto res = cli.Get("/");
  14513. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14514. << " ssl_backend_error=" << res.ssl_backend_error();
  14515. }
  14516. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14517. // policy status, which no backend reports for a self-signed certificate.
  14518. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14519. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14520. ASSERT_TRUE(svr.is_valid());
  14521. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14522. auto se = detail::scope_exit([&] {
  14523. svr.stop();
  14524. t.join();
  14525. ASSERT_FALSE(svr.is_running());
  14526. });
  14527. svr.wait_until_ready();
  14528. SSLClient cli("127.0.0.1", PORT);
  14529. cli.set_connection_timeout(30);
  14530. auto res = cli.Get("/");
  14531. ASSERT_FALSE(res);
  14532. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14533. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14534. }
  14535. TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
  14536. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14537. ASSERT_TRUE(svr.is_valid());
  14538. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14539. auto se = detail::scope_exit([&] {
  14540. svr.stop();
  14541. t.join();
  14542. ASSERT_FALSE(svr.is_running());
  14543. });
  14544. svr.wait_until_ready();
  14545. auto url = "wss://127.0.0.1:" + std::to_string(PORT) + "/";
  14546. {
  14547. ws::WebSocketClient client(url);
  14548. auto res = client.connect();
  14549. ASSERT_FALSE(res);
  14550. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14551. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14552. res.ssl_backend_error());
  14553. }
  14554. {
  14555. ws::WebSocketClient client(url);
  14556. client.enable_windows_certificate_verification(false);
  14557. auto res = client.connect();
  14558. ASSERT_FALSE(res);
  14559. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14560. EXPECT_NE(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14561. res.ssl_backend_error());
  14562. }
  14563. }
  14564. #endif
  14565. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14566. Client cli("https://google.com");
  14567. auto res = cli.Get("/");
  14568. // Any status: Google may redirect or rate-limit CI runners.
  14569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14570. }
  14571. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14572. SSLClient cli("google.com");
  14573. cli.set_ca_cert_path(CA_CERT_FILE);
  14574. auto res = cli.Get("/");
  14575. // Any status: Google may redirect or rate-limit CI runners.
  14576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14577. }
  14578. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14579. SSLClient cli("google.com");
  14580. cli.enable_server_certificate_verification(true);
  14581. cli.set_ca_cert_path("hello");
  14582. auto res = cli.Get("/");
  14583. ASSERT_TRUE(!res);
  14584. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14585. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14586. // should be set
  14587. EXPECT_EQ(0, res.ssl_error());
  14588. // Verify backend error is captured for SSLLoadingCerts
  14589. // This error occurs when loading CA certificates fails
  14590. EXPECT_NE(0UL, res.ssl_backend_error());
  14591. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14592. // OpenSSL specific error codes:
  14593. // > openssl errstr 0x80000002
  14594. // error:80000002:system library::No such file or directory
  14595. // > openssl errstr 0xA000126
  14596. // error:0A000126:SSL routines::unexpected eof while reading
  14597. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14598. res.ssl_backend_error() == 0xA000126);
  14599. #endif
  14600. }
  14601. TEST(SSLClientTest, ServerCertificateVerification4) {
  14602. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14603. ASSERT_TRUE(svr.is_valid());
  14604. svr.Get("/test", [&](const Request &, Response &res) {
  14605. res.set_content("test", "text/plain");
  14606. svr.stop();
  14607. ASSERT_TRUE(true);
  14608. });
  14609. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14610. auto se = detail::scope_exit([&] {
  14611. t.join();
  14612. ASSERT_FALSE(svr.is_running());
  14613. });
  14614. svr.wait_until_ready();
  14615. SSLClient cli("127.0.0.1", PORT);
  14616. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14617. cli.enable_server_certificate_verification(true);
  14618. cli.set_connection_timeout(30);
  14619. auto res = cli.Get("/test");
  14620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14621. ASSERT_EQ(StatusCode::OK_200, res->status);
  14622. }
  14623. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14624. std::string cert;
  14625. read_file(CA_CERT_FILE, cert);
  14626. SSLClient cli("google.com");
  14627. cli.load_ca_cert_store(cert.data(), cert.size());
  14628. const auto res = cli.Get("/");
  14629. // Any status: Google may redirect or rate-limit CI runners.
  14630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14631. }
  14632. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14633. // clang-format off
  14634. static constexpr char cert[] =
  14635. "GlobalSign Root CA\n"
  14636. "==================\n"
  14637. "-----BEGIN CERTIFICATE-----\n"
  14638. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14639. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14640. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14641. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14642. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14643. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14644. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14645. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14646. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14647. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14648. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14649. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14650. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14651. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14652. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14653. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14654. "-----END CERTIFICATE-----\n";
  14655. // clang-format on
  14656. SSLClient cli("google.com");
  14657. cli.load_ca_cert_store(cert, sizeof(cert));
  14658. const auto res = cli.Get("/");
  14659. // Any status: Google may redirect or rate-limit CI runners.
  14660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14661. }
  14662. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14663. SSLClient cli("www.youtube.com");
  14664. cli.set_ca_cert_path(CA_CERT_FILE);
  14665. cli.enable_server_certificate_verification(true);
  14666. cli.set_follow_location(true);
  14667. auto res = cli.Get("/");
  14668. // Any status: Google may redirect or rate-limit CI runners.
  14669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14670. }
  14671. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14672. SSLClient cli("wWw.YouTube.Com");
  14673. cli.set_ca_cert_path(CA_CERT_FILE);
  14674. cli.enable_server_certificate_verification(true);
  14675. cli.enable_server_hostname_verification(true);
  14676. cli.set_follow_location(true);
  14677. auto res = cli.Get("/");
  14678. // Any status: Google may redirect or rate-limit CI runners.
  14679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14680. }
  14681. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14682. SSLClient cli("gOoGlE.COm");
  14683. cli.enable_server_certificate_verification(true);
  14684. cli.enable_server_hostname_verification(true);
  14685. cli.set_follow_location(true);
  14686. auto res = cli.Get("/");
  14687. // Any status: Google may redirect or rate-limit CI runners.
  14688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14689. }
  14690. TEST(SSLClientTest, Issue2004_Online) {
  14691. Client client("https://google.com");
  14692. client.set_follow_location(true);
  14693. auto res = client.Get("/");
  14694. // Any status: Google may redirect or rate-limit CI runners.
  14695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14696. }
  14697. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14698. // Create SSLClient with invalid cert/key to make is_valid() return false
  14699. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14700. "nonexistent_key.pem");
  14701. // is_valid() should be false due to cert loading failure
  14702. ASSERT_FALSE(cli.is_valid());
  14703. auto res = cli.Get("/");
  14704. ASSERT_FALSE(res);
  14705. EXPECT_EQ(Error::SSLConnection, res.error());
  14706. }
  14707. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14708. // Test for Issue #2251: SSL error not properly reported when client cert
  14709. // and key paths are swapped or mismatched
  14710. // This simulates the scenario where user accidentally swaps the cert and key
  14711. // files
  14712. // Using client cert file as private key and vice versa (completely wrong)
  14713. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14714. // Should fail validation due to cert/key mismatch
  14715. ASSERT_FALSE(cli.is_valid());
  14716. // Attempt to make a request should fail with proper error
  14717. auto res = cli.Get("/");
  14718. ASSERT_FALSE(res);
  14719. EXPECT_EQ(Error::SSLConnection, res.error());
  14720. // SSL error should be recorded in the Result object (this is the key fix for
  14721. // Issue #2251)
  14722. auto backend_error = res.ssl_backend_error();
  14723. EXPECT_NE(0u, backend_error);
  14724. }
  14725. // Tests cert/key mismatch detection at the TLS context level
  14726. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14727. // Test that using mismatched cert/key causes connection failure.
  14728. // We verify this at the SSLClient level rather than through internal
  14729. // TLS API functions.
  14730. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14731. cli.enable_server_certificate_verification(false);
  14732. cli.set_connection_timeout(2);
  14733. // The mismatch should cause a connection or handshake error
  14734. auto res = cli.Get("/test");
  14735. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14736. // Either way, the request should fail
  14737. EXPECT_FALSE(res);
  14738. }
  14739. #endif
  14740. #if 0
  14741. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14742. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14743. ASSERT_TRUE(cli != nullptr);
  14744. cli->set_address_family(AF_INET6);
  14745. cli->set_interface("en0");
  14746. auto res = cli->Get("/get");
  14747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14748. ASSERT_EQ(StatusCode::OK_200, res->status);
  14749. }
  14750. #endif
  14751. // Client certificate tests - work with all TLS backends
  14752. #ifdef CPPHTTPLIB_SSL_ENABLED
  14753. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14754. void ClientCertPresent(
  14755. const std::string &client_cert_file,
  14756. const std::string &client_private_key_file,
  14757. const std::string &client_encrypted_private_key_pass = std::string(),
  14758. const ClientCertServerSetup &setup = nullptr) {
  14759. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14760. ASSERT_TRUE(svr.is_valid());
  14761. if (setup) { setup(svr); }
  14762. svr.Get("/test", [&](const Request &req, Response &res) {
  14763. res.set_content("test", "text/plain");
  14764. auto cert = req.peer_cert();
  14765. ASSERT_TRUE(static_cast<bool>(cert));
  14766. std::string common_name = cert.subject_cn();
  14767. EXPECT_EQ("Common Name", common_name);
  14768. });
  14769. auto port = svr.bind_to_any_port(HOST);
  14770. ASSERT_LT(0, port);
  14771. thread t = thread([&]() { svr.listen_after_bind(); });
  14772. auto se = detail::scope_exit([&] {
  14773. svr.stop();
  14774. t.join();
  14775. ASSERT_FALSE(svr.is_running());
  14776. });
  14777. svr.wait_until_ready();
  14778. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14779. client_encrypted_private_key_pass);
  14780. cli.enable_server_certificate_verification(false);
  14781. cli.set_connection_timeout(30);
  14782. auto res = cli.Get("/test");
  14783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14784. ASSERT_EQ(StatusCode::OK_200, res->status);
  14785. }
  14786. TEST(SSLClientServerTest, ClientCertPresent) {
  14787. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14788. }
  14789. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14790. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14791. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14792. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14793. }
  14794. // Expects svr, which must require client certificates, to reject a client
  14795. // that has none
  14796. void RejectsClientWithoutCert(SSLServer &svr) {
  14797. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14798. auto port = svr.bind_to_any_port(HOST);
  14799. ASSERT_LT(0, port);
  14800. thread t = thread([&]() { svr.listen_after_bind(); });
  14801. auto se = detail::scope_exit([&] {
  14802. svr.stop();
  14803. t.join();
  14804. ASSERT_FALSE(svr.is_running());
  14805. });
  14806. svr.wait_until_ready();
  14807. SSLClient cli(HOST, port);
  14808. cli.set_connection_timeout(30);
  14809. // Skip the server certificate check, so that the request fails because the
  14810. // client certificate is missing rather than because cert.pem is not trusted
  14811. cli.enable_server_certificate_verification(false);
  14812. auto res = cli.Get("/test");
  14813. ASSERT_FALSE(res);
  14814. // The server rejects the client during the handshake, or on TLS 1.3 right
  14815. // after it, which the client notices on its first write or read
  14816. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14817. res.error() == Error::Write || res.error() == Error::Read)
  14818. << to_string(res.error());
  14819. if (res.error() == Error::SSLConnection) {
  14820. EXPECT_NE(0UL, res.ssl_backend_error());
  14821. }
  14822. // A rejection noticed on the write keeps the TLS error the write hit
  14823. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14824. }
  14825. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14826. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14827. ASSERT_TRUE(svr.is_valid());
  14828. if (setup) { setup(svr); }
  14829. RejectsClientWithoutCert(svr);
  14830. }
  14831. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14832. // A server that requires client certificates must keep requiring them after
  14833. // setup changes it, and keep accepting a client that has one
  14834. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14835. ClientCertMissing(setup);
  14836. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14837. setup);
  14838. }
  14839. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14840. ClientCertStillRequired([](SSLServer &svr) {
  14841. ASSERT_TRUE(tls::set_verify_callback(
  14842. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14843. });
  14844. }
  14845. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14846. ClientCertStillRequired([](SSLServer &svr) {
  14847. ASSERT_TRUE(tls::set_verify_callback(
  14848. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14849. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14850. });
  14851. }
  14852. // The client verifies the server certificate during the handshake, so a
  14853. // server that fails the check never gets the client certificate, even when a
  14854. // verifier of the client's own accepts it
  14855. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14856. struct Case {
  14857. const char *trusted_ca;
  14858. const char *host;
  14859. Error error;
  14860. };
  14861. // cert2.pem names localhost: the first client does not trust it, and the
  14862. // second trusts it but asks for another name
  14863. for (const auto &c :
  14864. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14865. Case{SERVER_CERT2_FILE, "example.com",
  14866. Error::SSLServerHostnameVerification}}) {
  14867. for (auto with_verifier : {false, true}) {
  14868. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14869. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14870. CLIENT_CA_CERT_FILE);
  14871. ASSERT_TRUE(svr.is_valid());
  14872. std::atomic<bool> got_client_cert{false};
  14873. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14874. [&](const tls::VerifyContext &) {
  14875. got_client_cert = true;
  14876. return true;
  14877. }));
  14878. auto port = svr.bind_to_any_port("127.0.0.1");
  14879. ASSERT_LT(0, port);
  14880. thread t = thread([&] { svr.listen_after_bind(); });
  14881. svr.wait_until_ready();
  14882. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14883. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14884. cli.set_ca_cert_path(c.trusted_ca);
  14885. if (with_verifier) {
  14886. cli.set_server_certificate_verifier(
  14887. [](const tls::VerifyContext &) { return true; });
  14888. }
  14889. auto res = cli.Get("/");
  14890. EXPECT_FALSE(res);
  14891. EXPECT_EQ(c.error, res.error());
  14892. svr.stop();
  14893. t.join();
  14894. EXPECT_FALSE(got_client_cert);
  14895. }
  14896. }
  14897. }
  14898. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14899. std::string cert_pem, key_pem, ca_pem;
  14900. read_file(SERVER_CERT_FILE, cert_pem);
  14901. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14902. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14903. ASSERT_TRUE(
  14904. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14905. }
  14906. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14908. ASSERT_TRUE(svr.is_valid());
  14909. UpdateCertsPemWithClientCA(svr);
  14910. RejectsClientWithoutCert(svr);
  14911. }
  14912. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14913. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14914. }
  14915. // A TLS error from one request must not show up in a later request's Result
  14916. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14917. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14918. ASSERT_TRUE(svr.is_valid());
  14919. svr.Get("/test", [](const Request &, Response &res) {
  14920. res.set_content("test", "text/plain");
  14921. });
  14922. auto port = svr.bind_to_any_port(HOST);
  14923. ASSERT_LT(0, port);
  14924. thread t = thread([&]() { svr.listen_after_bind(); });
  14925. auto se = detail::scope_exit([&] {
  14926. svr.stop();
  14927. t.join();
  14928. ASSERT_FALSE(svr.is_running());
  14929. });
  14930. svr.wait_until_ready();
  14931. SSLClient cli(HOST, port);
  14932. cli.set_connection_timeout(30);
  14933. cli.enable_server_hostname_verification(false);
  14934. // cert.pem is not trusted, so the handshake fails
  14935. ASSERT_FALSE(cli.Get("/test"));
  14936. cli.enable_server_certificate_verification(false);
  14937. auto res = cli.Get("/test");
  14938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14939. EXPECT_EQ(0, res.ssl_error());
  14940. EXPECT_EQ(0UL, res.ssl_backend_error());
  14941. }
  14942. // PEM memory-based constructor tests (works with all TLS backends).
  14943. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14944. // terminator after it.
  14945. void PemMemoryClientCertPresent(
  14946. const std::string &client_cert_file,
  14947. const std::string &client_private_key_file,
  14948. const std::string &client_encrypted_private_key_pass = std::string(),
  14949. bool exact_size = false) {
  14950. // Read PEM files into memory
  14951. std::string server_cert_pem, server_key_pem;
  14952. std::string client_ca_pem;
  14953. std::string client_cert_pem, client_key_pem;
  14954. read_file(SERVER_CERT_FILE, server_cert_pem);
  14955. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14956. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14957. read_file(client_cert_file, client_cert_pem);
  14958. read_file(client_private_key_file, client_key_pem);
  14959. std::list<std::vector<char>> exact_copies;
  14960. auto data = [&](const std::string &pem) -> const char * {
  14961. if (!exact_size) { return pem.c_str(); }
  14962. exact_copies.emplace_back(pem.begin(), pem.end());
  14963. return exact_copies.back().data();
  14964. };
  14965. // Create server with PEM memory
  14966. SSLServer::PemMemory server_pem = {
  14967. data(server_cert_pem),
  14968. server_cert_pem.size(),
  14969. data(server_key_pem),
  14970. server_key_pem.size(),
  14971. data(client_ca_pem),
  14972. client_ca_pem.size(),
  14973. nullptr // no password for server key
  14974. };
  14975. SSLServer svr(server_pem);
  14976. ASSERT_TRUE(svr.is_valid());
  14977. svr.Get("/test", [&](const Request &req, Response &res) {
  14978. res.set_content("test", "text/plain");
  14979. auto cert = req.peer_cert();
  14980. ASSERT_TRUE(static_cast<bool>(cert));
  14981. EXPECT_EQ("Common Name", cert.subject_cn());
  14982. });
  14983. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14984. auto se = detail::scope_exit([&] {
  14985. svr.stop();
  14986. t.join();
  14987. ASSERT_FALSE(svr.is_running());
  14988. });
  14989. svr.wait_until_ready();
  14990. // Create client with PEM memory
  14991. const char *password = client_encrypted_private_key_pass.empty()
  14992. ? nullptr
  14993. : client_encrypted_private_key_pass.c_str();
  14994. SSLClient::PemMemory client_pem = {
  14995. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14996. client_key_pem.size(), password};
  14997. SSLClient cli(HOST, PORT, client_pem);
  14998. cli.enable_server_certificate_verification(false);
  14999. cli.set_connection_timeout(30);
  15000. auto res = cli.Get("/test");
  15001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15002. ASSERT_EQ(StatusCode::OK_200, res->status);
  15003. }
  15004. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  15005. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15006. }
  15007. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  15008. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  15009. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  15010. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  15011. }
  15012. // A server built from PEM memory with a client CA requires client certificates,
  15013. // also when the CA is a NUL-terminated string passed with a length of 0
  15014. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  15015. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15016. read_file(SERVER_CERT_FILE, server_cert_pem);
  15017. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15018. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15019. SSLServer::PemMemory server_pem = {
  15020. server_cert_pem.c_str(),
  15021. server_cert_pem.size(),
  15022. server_key_pem.c_str(),
  15023. server_key_pem.size(),
  15024. client_ca_pem.c_str(),
  15025. client_ca_pem.size(),
  15026. nullptr // no password for server key
  15027. };
  15028. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  15029. SCOPED_TRACE(client_ca_pem_len);
  15030. server_pem.client_ca_pem_len = client_ca_pem_len;
  15031. SSLServer svr(server_pem);
  15032. ASSERT_TRUE(svr.is_valid());
  15033. RejectsClientWithoutCert(svr);
  15034. }
  15035. // An empty CA fails to load instead of turning the check off
  15036. server_pem.client_ca_pem = "";
  15037. server_pem.client_ca_pem_len = 0;
  15038. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  15039. }
  15040. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  15041. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  15042. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  15043. true);
  15044. }
  15045. // A length shorter than the PEM cuts it short, so it no longer loads
  15046. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  15047. std::string cert, key;
  15048. read_file(SERVER_CERT_FILE, cert);
  15049. read_file(SERVER_PRIVATE_KEY_FILE, key);
  15050. for (auto cut_cert : {true, false}) {
  15051. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  15052. auto key_len = cut_cert ? key.size() : key.size() / 2;
  15053. SSLServer::PemMemory server_pem = {
  15054. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  15055. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  15056. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  15057. key_len, nullptr};
  15058. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  15059. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  15060. key.c_str(), key_len, nullptr};
  15061. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  15062. }
  15063. }
  15064. TEST(SSLClientServerTest, SSLConnectTimeout) {
  15065. class NoListenSSLServer : public SSLServer {
  15066. public:
  15067. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  15068. const char *client_ca_cert_file_path,
  15069. const char *client_ca_cert_dir_path = nullptr)
  15070. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  15071. client_ca_cert_dir_path),
  15072. stop_(false) {}
  15073. std::atomic_bool stop_;
  15074. private:
  15075. bool process_and_close_socket(socket_t /*sock*/) override {
  15076. // Don't create SSL context
  15077. while (!stop_.load()) {
  15078. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  15079. }
  15080. return true;
  15081. }
  15082. };
  15083. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15084. CLIENT_CA_CERT_FILE);
  15085. ASSERT_TRUE(svr.is_valid());
  15086. // Keep-alive parking would bypass the override.
  15087. svr.set_keep_alive_parking(false);
  15088. svr.Get("/test", [&](const Request &, Response &res) {
  15089. res.set_content("test", "text/plain");
  15090. });
  15091. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15092. auto se = detail::scope_exit([&] {
  15093. svr.stop_ = true;
  15094. svr.stop();
  15095. t.join();
  15096. ASSERT_FALSE(svr.is_running());
  15097. });
  15098. svr.wait_until_ready();
  15099. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15100. cli.enable_server_certificate_verification(false);
  15101. cli.set_connection_timeout(1);
  15102. auto res = cli.Get("/test");
  15103. ASSERT_TRUE(!res);
  15104. EXPECT_EQ(Error::SSLConnection, res.error());
  15105. // Timeout results in WantRead error code (maps to backend-specific value)
  15106. EXPECT_NE(0, res.ssl_error());
  15107. }
  15108. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  15109. // Test SSLServer with client certificate verification using the standard
  15110. // constructor (ContextSetupCallback is tested by backend-specific tests)
  15111. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  15112. CLIENT_CA_CERT_DIR);
  15113. ASSERT_TRUE(svr.is_valid());
  15114. svr.Get("/test", [&](const Request &req, Response &res) {
  15115. res.set_content("test", "text/plain");
  15116. auto cert = req.peer_cert();
  15117. ASSERT_TRUE(static_cast<bool>(cert));
  15118. auto common_name = cert.subject_cn();
  15119. EXPECT_EQ("Common Name", common_name);
  15120. });
  15121. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15122. auto se = detail::scope_exit([&] {
  15123. svr.stop();
  15124. t.join();
  15125. ASSERT_FALSE(svr.is_running());
  15126. });
  15127. svr.wait_until_ready();
  15128. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15129. cli.enable_server_certificate_verification(false);
  15130. cli.set_connection_timeout(30);
  15131. auto res = cli.Get("/test");
  15132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15133. ASSERT_EQ(StatusCode::OK_200, res->status);
  15134. }
  15135. // Test verify_hostname on every backend: a host is named by a SAN only
  15136. TEST(SSLClientServerTest, TlsVerifyHostname) {
  15137. using namespace httplib::tls;
  15138. // We need a running server to test against
  15139. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15140. ASSERT_TRUE(svr.is_valid());
  15141. svr.Get("/test", [](const Request &, Response &res) {
  15142. res.set_content("ok", "text/plain");
  15143. });
  15144. thread t([&]() { svr.listen(HOST, PORT); });
  15145. auto se = detail::scope_exit([&] {
  15146. svr.stop();
  15147. t.join();
  15148. });
  15149. svr.wait_until_ready();
  15150. bool verify_callback_called = false;
  15151. bool verify_result_wrong = false;
  15152. SSLClient cli(HOST, PORT);
  15153. cli.enable_server_certificate_verification(true);
  15154. cli.set_ca_cert_path(CA_CERT_FILE);
  15155. cli.set_connection_timeout(5);
  15156. // Note: Test certificate has CN="Common Name", not "localhost"
  15157. bool verify_result_cn = false;
  15158. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15159. verify_callback_called = true;
  15160. if (!ctx.cert) return false;
  15161. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  15162. verify_result_cn = ctx.check_hostname("Common Name");
  15163. // Test 2: wrong hostname should not match
  15164. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  15165. return true; // Accept for the purpose of this test
  15166. });
  15167. auto res = cli.Get("/test");
  15168. // The request may succeed or fail depending on cert configuration
  15169. // but the callback should have been called
  15170. ASSERT_TRUE(verify_callback_called)
  15171. << "Verify callback should have been called";
  15172. EXPECT_FALSE(verify_result_cn)
  15173. << "verify_hostname must not match the certificate CN (no SAN)";
  15174. // Wrong hostname should not match
  15175. EXPECT_FALSE(verify_result_wrong)
  15176. << "verify_hostname should not match 'wronghost.example.com'";
  15177. }
  15178. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  15179. // backend verifies it.
  15180. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  15181. // Certificate CN is "localhost" and it carries no SAN.
  15182. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  15183. ASSERT_TRUE(svr.is_valid());
  15184. svr.Get("/test", [](const Request &, Response &res) {
  15185. res.set_content("ok", "text/plain");
  15186. });
  15187. auto port = svr.bind_to_any_port(HOST);
  15188. thread t([&]() { svr.listen_after_bind(); });
  15189. auto se = detail::scope_exit([&] {
  15190. svr.stop();
  15191. t.join();
  15192. });
  15193. svr.wait_until_ready();
  15194. SSLClient cli("localhost", port);
  15195. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  15196. cli.enable_server_certificate_verification(true);
  15197. cli.set_connection_timeout(5);
  15198. auto res = cli.Get("/test");
  15199. ASSERT_FALSE(res);
  15200. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  15201. // The same certificate is accepted once host name verification is off, so the
  15202. // failure above is the host name and not the chain.
  15203. cli.enable_server_hostname_verification(false);
  15204. res = cli.Get("/test");
  15205. ASSERT_TRUE(res) << to_string(res.error());
  15206. EXPECT_EQ(StatusCode::OK_200, res->status);
  15207. }
  15208. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  15209. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  15210. // X509_check_ip behavior and must hold for every backend.
  15211. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  15212. using namespace httplib::tls;
  15213. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  15214. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  15215. ASSERT_TRUE(svr.is_valid());
  15216. svr.Get("/test", [](const Request &, Response &res) {
  15217. res.set_content("ok", "text/plain");
  15218. });
  15219. thread t([&]() { svr.listen(HOST, PORT); });
  15220. auto se = detail::scope_exit([&] {
  15221. svr.stop();
  15222. t.join();
  15223. });
  15224. svr.wait_until_ready();
  15225. bool verify_callback_called = false;
  15226. bool ip_matched_via_cn = true;
  15227. SSLClient cli(HOST, PORT);
  15228. cli.enable_server_certificate_verification(true);
  15229. cli.set_ca_cert_path(CA_CERT_FILE);
  15230. cli.set_connection_timeout(5);
  15231. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15232. verify_callback_called = true;
  15233. if (!ctx.cert) return false;
  15234. // The IP appears only in the CN, so it must NOT be accepted.
  15235. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  15236. return true; // Accept for the purpose of this test
  15237. });
  15238. cli.Get("/test");
  15239. ASSERT_TRUE(verify_callback_called)
  15240. << "Verify callback should have been called";
  15241. EXPECT_FALSE(ip_matched_via_cn)
  15242. << "An IP host must not be authenticated via the certificate CN";
  15243. }
  15244. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  15245. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  15246. using namespace httplib::tls;
  15247. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  15248. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  15249. ASSERT_TRUE(svr.is_valid());
  15250. svr.Get("/test", [](const Request &, Response &res) {
  15251. res.set_content("ok", "text/plain");
  15252. });
  15253. thread t([&]() { svr.listen(HOST, PORT); });
  15254. auto se = detail::scope_exit([&] {
  15255. svr.stop();
  15256. t.join();
  15257. });
  15258. svr.wait_until_ready();
  15259. bool verify_callback_called = false;
  15260. bool san_matched = false;
  15261. bool wrong_ipv6_matched = true;
  15262. bool cn_ipv6_matched = true;
  15263. SSLClient cli(HOST, PORT);
  15264. cli.enable_server_certificate_verification(true);
  15265. cli.set_ca_cert_path(CA_CERT_FILE);
  15266. cli.set_connection_timeout(5);
  15267. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15268. verify_callback_called = true;
  15269. if (!ctx.cert) return false;
  15270. // Matches the IPv6 iPAddress SAN.
  15271. san_matched = ctx.check_hostname("2001:db8::1");
  15272. // A different IPv6 address must not match.
  15273. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  15274. // "::1" lives only in the CN, so it must not be accepted.
  15275. cn_ipv6_matched = ctx.check_hostname("::1");
  15276. return true; // Accept for the purpose of this test
  15277. });
  15278. cli.Get("/test");
  15279. ASSERT_TRUE(verify_callback_called)
  15280. << "Verify callback should have been called";
  15281. EXPECT_TRUE(san_matched)
  15282. << "verify_hostname should match an IPv6 iPAddress SAN";
  15283. EXPECT_FALSE(wrong_ipv6_matched)
  15284. << "verify_hostname should not match a non-matching IPv6 address";
  15285. EXPECT_FALSE(cn_ipv6_matched)
  15286. << "An IPv6 host must not be authenticated via the certificate CN";
  15287. }
  15288. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  15289. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  15290. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  15291. using namespace httplib::tls;
  15292. // SANs: DNS:a.zz, IP:42.46.122.122
  15293. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15294. ASSERT_TRUE(svr.is_valid());
  15295. svr.Get("/test", [](const Request &, Response &res) {
  15296. res.set_content("ok", "text/plain");
  15297. });
  15298. auto port = svr.bind_to_any_port(HOST);
  15299. thread t([&]() { svr.listen_after_bind(); });
  15300. auto se = detail::scope_exit([&] {
  15301. svr.stop();
  15302. t.join();
  15303. });
  15304. svr.wait_until_ready();
  15305. bool verify_callback_called = false;
  15306. bool dns_san_matched = false;
  15307. bool ip_san_matched = false;
  15308. bool ip_matched_via_dns_san = true;
  15309. bool dns_matched_via_ip_san = true;
  15310. bool cn_matched_next_to_dns_san = true;
  15311. SSLClient cli(HOST, port);
  15312. cli.enable_server_certificate_verification(true);
  15313. cli.set_ca_cert_path(CA_CERT_FILE);
  15314. cli.set_connection_timeout(5);
  15315. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15316. verify_callback_called = true;
  15317. if (!ctx.cert) return false;
  15318. dns_san_matched = ctx.check_hostname("a.zz");
  15319. ip_san_matched = ctx.check_hostname("42.46.122.122");
  15320. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  15321. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  15322. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  15323. return true; // Accept for the purpose of this test
  15324. });
  15325. cli.Get("/test");
  15326. ASSERT_TRUE(verify_callback_called)
  15327. << "Verify callback should have been called";
  15328. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  15329. EXPECT_TRUE(ip_san_matched)
  15330. << "verify_hostname should match an iPAddress SAN";
  15331. EXPECT_FALSE(ip_matched_via_dns_san)
  15332. << "An IP host must not be authenticated via a dNSName SAN";
  15333. EXPECT_FALSE(dns_matched_via_ip_san)
  15334. << "A DNS host must not be authenticated via an iPAddress SAN";
  15335. EXPECT_FALSE(cn_matched_next_to_dns_san)
  15336. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  15337. }
  15338. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  15339. // "www.*.example.test" names one host and not every host under example.test.
  15340. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  15341. using namespace httplib::tls;
  15342. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  15343. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  15344. ASSERT_TRUE(svr.is_valid());
  15345. svr.Get("/test", [](const Request &, Response &res) {
  15346. res.set_content("ok", "text/plain");
  15347. });
  15348. auto port = svr.bind_to_any_port(HOST);
  15349. thread t([&]() { svr.listen_after_bind(); });
  15350. auto se = detail::scope_exit([&] {
  15351. svr.stop();
  15352. t.join();
  15353. });
  15354. svr.wait_until_ready();
  15355. bool verify_callback_called = false;
  15356. bool leftmost_wildcard_matched = false;
  15357. bool wildcard_spanned_labels = true;
  15358. bool inner_wildcard_matched = true;
  15359. SSLClient cli(HOST, port);
  15360. cli.enable_server_certificate_verification(true);
  15361. cli.set_ca_cert_path(CA_CERT_FILE);
  15362. cli.set_connection_timeout(5);
  15363. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15364. verify_callback_called = true;
  15365. if (!ctx.cert) return false;
  15366. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  15367. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  15368. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  15369. return true; // Accept for the purpose of this test
  15370. });
  15371. cli.Get("/test");
  15372. ASSERT_TRUE(verify_callback_called)
  15373. << "Verify callback should have been called";
  15374. EXPECT_TRUE(leftmost_wildcard_matched)
  15375. << "A leftmost wildcard should match a single label";
  15376. EXPECT_FALSE(wildcard_spanned_labels)
  15377. << "A wildcard label must not match more than one label";
  15378. EXPECT_FALSE(inner_wildcard_matched)
  15379. << "A wildcard outside the leftmost label must not be honoured";
  15380. }
  15381. // sans() must report each SAN entry under its own type.
  15382. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  15383. using namespace httplib::tls;
  15384. // SANs: DNS:a.zz, IP:42.46.122.122
  15385. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15386. ASSERT_TRUE(svr.is_valid());
  15387. svr.Get("/test", [](const Request &, Response &res) {
  15388. res.set_content("ok", "text/plain");
  15389. });
  15390. auto port = svr.bind_to_any_port(HOST);
  15391. thread t([&]() { svr.listen_after_bind(); });
  15392. auto se = detail::scope_exit([&] {
  15393. svr.stop();
  15394. t.join();
  15395. });
  15396. svr.wait_until_ready();
  15397. bool verify_callback_called = false;
  15398. std::vector<SanEntry> sans;
  15399. SSLClient cli(HOST, port);
  15400. cli.enable_server_certificate_verification(true);
  15401. cli.set_ca_cert_path(CA_CERT_FILE);
  15402. cli.set_connection_timeout(5);
  15403. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15404. verify_callback_called = true;
  15405. if (!ctx.cert) return false;
  15406. sans = ctx.sans();
  15407. return true; // Accept for the purpose of this test
  15408. });
  15409. cli.Get("/test");
  15410. ASSERT_TRUE(verify_callback_called)
  15411. << "Verify callback should have been called";
  15412. auto has_san = [&](SanType type, const std::string &value) {
  15413. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15414. return san.type == type && san.value == value;
  15415. });
  15416. };
  15417. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15418. << "sans() should report the dNSName SAN";
  15419. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15420. << "sans() should report the iPAddress SAN";
  15421. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15422. << "sans() must not report the dNSName SAN as an address";
  15423. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15424. << "sans() must not report the iPAddress SAN as a DNS name";
  15425. }
  15426. #endif
  15427. // mbedTLS-specific callback constructor test
  15428. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15429. #ifdef CPPHTTPLIB_SSL_ENABLED
  15430. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15431. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15432. ASSERT_TRUE(svr.is_valid());
  15433. // Set up a handler to verify client certificate is present
  15434. bool client_cert_verified = false;
  15435. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15436. // Verify that client certificate was provided
  15437. client_cert_verified = true;
  15438. res.set_content("success", "text/plain");
  15439. });
  15440. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15441. auto se = detail::scope_exit([&] {
  15442. svr.stop();
  15443. t.join();
  15444. ASSERT_FALSE(svr.is_running());
  15445. });
  15446. svr.wait_until_ready();
  15447. // Client with certificate
  15448. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15449. cli.enable_server_certificate_verification(false);
  15450. cli.set_connection_timeout(30);
  15451. auto res = cli.Get("/test");
  15452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15453. ASSERT_EQ(StatusCode::OK_200, res->status);
  15454. ASSERT_TRUE(client_cert_verified);
  15455. EXPECT_EQ("success", res->body);
  15456. }
  15457. #endif
  15458. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15459. // backends
  15460. #ifdef CPPHTTPLIB_SSL_ENABLED
  15461. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15462. using namespace httplib::tls;
  15463. // Test that when client CA cert file is provided,
  15464. // the server properly requests and validates client certificates
  15465. // Create a server with client authentication
  15466. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15467. ASSERT_TRUE(svr.is_valid());
  15468. bool handler_called = false;
  15469. svr.Get("/test", [&](const Request &req, Response &res) {
  15470. handler_called = true;
  15471. // Verify that a client certificate was provided
  15472. auto cert = req.peer_cert();
  15473. ASSERT_TRUE(static_cast<bool>(cert));
  15474. // Get the issuer name
  15475. std::string issuer_str = cert.issuer_name();
  15476. ASSERT_FALSE(issuer_str.empty());
  15477. // The client certificate should be issued by our test CA
  15478. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15479. res.set_content("authenticated", "text/plain");
  15480. });
  15481. thread t = thread([&]() { ASSERT_TRUE(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. // Connect with a client certificate issued by the CA
  15489. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15490. cli.enable_server_certificate_verification(false);
  15491. cli.set_connection_timeout(30);
  15492. auto res = cli.Get("/test");
  15493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15494. ASSERT_EQ(StatusCode::OK_200, res->status);
  15495. ASSERT_TRUE(handler_called);
  15496. EXPECT_EQ("authenticated", res->body);
  15497. }
  15498. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15499. using namespace httplib::tls;
  15500. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15501. ASSERT_TRUE(svr.is_valid());
  15502. svr.Get("/test", [](const Request &, Response &res) {
  15503. res.set_content("ok", "text/plain");
  15504. });
  15505. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15506. auto se = detail::scope_exit([&] {
  15507. svr.stop();
  15508. t.join();
  15509. });
  15510. svr.wait_until_ready();
  15511. SSLClient cli(HOST, PORT);
  15512. cli.enable_server_certificate_verification(false);
  15513. cli.set_connection_timeout(30);
  15514. bool cert_checked = false;
  15515. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15516. if (ctx.cert) {
  15517. auto sans = ctx.sans();
  15518. // Test certificate may or may not have SANs - just verify the API
  15519. // works If SANs exist, verify the types are valid
  15520. for (const auto &san : sans) {
  15521. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15522. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15523. san.type == SanType::OTHER);
  15524. EXPECT_FALSE(san.value.empty());
  15525. }
  15526. cert_checked = true;
  15527. }
  15528. return true;
  15529. });
  15530. auto res = cli.Get("/test");
  15531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15532. EXPECT_TRUE(cert_checked);
  15533. }
  15534. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15535. using namespace httplib::tls;
  15536. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15537. ASSERT_TRUE(svr.is_valid());
  15538. svr.Get("/test", [](const Request &, Response &res) {
  15539. res.set_content("ok", "text/plain");
  15540. });
  15541. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15542. auto se = detail::scope_exit([&] {
  15543. svr.stop();
  15544. t.join();
  15545. });
  15546. svr.wait_until_ready();
  15547. SSLClient cli(HOST, PORT);
  15548. cli.enable_server_certificate_verification(false);
  15549. cli.set_connection_timeout(30);
  15550. bool validity_checked = false;
  15551. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15552. if (ctx.cert) {
  15553. time_t not_before = 0, not_after = 0;
  15554. bool result = ctx.validity(not_before, not_after);
  15555. EXPECT_TRUE(result);
  15556. // Verify that not_before < now < not_after for a valid cert
  15557. time_t now = time(nullptr);
  15558. EXPECT_LT(not_before, now);
  15559. EXPECT_GT(not_after, now);
  15560. validity_checked = true;
  15561. }
  15562. return true;
  15563. });
  15564. auto res = cli.Get("/test");
  15565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15566. EXPECT_TRUE(validity_checked);
  15567. }
  15568. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15569. using namespace httplib::tls;
  15570. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15571. ASSERT_TRUE(svr.is_valid());
  15572. svr.Get("/test", [](const Request &, Response &res) {
  15573. res.set_content("ok", "text/plain");
  15574. });
  15575. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15576. auto se = detail::scope_exit([&] {
  15577. svr.stop();
  15578. t.join();
  15579. });
  15580. svr.wait_until_ready();
  15581. SSLClient cli(HOST, PORT);
  15582. cli.enable_server_certificate_verification(false);
  15583. cli.set_connection_timeout(30);
  15584. bool serial_checked = false;
  15585. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15586. if (ctx.cert) {
  15587. std::string serial = ctx.serial();
  15588. EXPECT_FALSE(serial.empty());
  15589. // Serial should be a hex string
  15590. for (char c : serial) {
  15591. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15592. (c >= 'a' && c <= 'f'));
  15593. }
  15594. serial_checked = true;
  15595. }
  15596. return true;
  15597. });
  15598. auto res = cli.Get("/test");
  15599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15600. EXPECT_TRUE(serial_checked);
  15601. }
  15602. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15603. // Test 1: Valid CA file - no error should be recorded
  15604. {
  15605. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15606. CLIENT_CA_CERT_FILE);
  15607. ASSERT_TRUE(svr.is_valid());
  15608. // With valid setup, last_ssl_error should be 0
  15609. EXPECT_EQ(0, svr.ssl_last_error());
  15610. }
  15611. // Test 2: Invalid CA file content
  15612. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15613. {
  15614. // Create a temporary file with completely invalid content
  15615. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15616. {
  15617. std::ofstream ofs(temp_invalid_ca);
  15618. ofs << "This is not a certificate file at all\n";
  15619. ofs << "Just plain text content\n";
  15620. }
  15621. // Create server with invalid CA file
  15622. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15623. // Clean up temporary file
  15624. std::remove(temp_invalid_ca);
  15625. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15626. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15627. // Note: SSL_CTX_load_verify_locations typically fails first,
  15628. // but our error handling code path is still exercised
  15629. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15630. }
  15631. }
  15632. TEST(VerifyCallbackTest, VerifyContextFields) {
  15633. using namespace httplib::tls;
  15634. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15635. ASSERT_TRUE(svr.is_valid());
  15636. svr.Get("/test", [](const Request &, Response &res) {
  15637. res.set_content("ok", "text/plain");
  15638. });
  15639. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15640. auto se = detail::scope_exit([&] {
  15641. svr.stop();
  15642. t.join();
  15643. });
  15644. svr.wait_until_ready();
  15645. SSLClient cli(HOST, PORT);
  15646. cli.enable_server_certificate_verification(false);
  15647. cli.set_connection_timeout(30);
  15648. int callback_count = 0;
  15649. bool saw_leaf_cert = false;
  15650. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15651. if (ctx.cert) {
  15652. callback_count++;
  15653. // We should see at least one certificate (the leaf)
  15654. std::string cn = ctx.subject_cn();
  15655. if (!cn.empty()) { saw_leaf_cert = true; }
  15656. // Verify context fields are populated
  15657. EXPECT_NE(ctx.session, nullptr);
  15658. EXPECT_GE(ctx.depth, 0);
  15659. }
  15660. return true;
  15661. });
  15662. auto res = cli.Get("/test");
  15663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15664. EXPECT_GT(callback_count, 0);
  15665. EXPECT_TRUE(saw_leaf_cert);
  15666. }
  15667. // A verifier that accepts runs alongside the built-in verification, and is the
  15668. // only check once that is turned off.
  15669. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15670. using namespace httplib::tls;
  15671. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15672. ASSERT_TRUE(svr.is_valid());
  15673. svr.Get("/test", [](const Request &, Response &res) {
  15674. res.set_content("ok", "text/plain");
  15675. });
  15676. auto port = svr.bind_to_any_port(HOST);
  15677. thread t([&]() { svr.listen_after_bind(); });
  15678. auto se = detail::scope_exit([&] {
  15679. svr.stop();
  15680. t.join();
  15681. });
  15682. svr.wait_until_ready();
  15683. SSLClient cli(HOST, port);
  15684. cli.enable_server_hostname_verification(false);
  15685. auto calls = 0;
  15686. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15687. calls++;
  15688. return true;
  15689. });
  15690. // cert.pem is not trusted
  15691. auto res = cli.Get("/test");
  15692. ASSERT_FALSE(res);
  15693. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15694. EXPECT_GT(calls, 0);
  15695. cli.enable_server_certificate_verification(false);
  15696. res = cli.Get("/test");
  15697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15698. EXPECT_EQ("ok", res->body);
  15699. }
  15700. // A verifier belongs to the client that set it, not to the thread that set it.
  15701. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15702. using namespace httplib::tls;
  15703. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15704. ASSERT_TRUE(svr.is_valid());
  15705. svr.Get("/test", [](const Request &, Response &res) {
  15706. res.set_content("ok", "text/plain");
  15707. });
  15708. auto port = svr.bind_to_any_port(HOST);
  15709. thread t([&]() { svr.listen_after_bind(); });
  15710. auto se = detail::scope_exit([&] {
  15711. svr.stop();
  15712. t.join();
  15713. });
  15714. svr.wait_until_ready();
  15715. auto rejecting_calls = 0;
  15716. SSLClient rejecting(HOST, port);
  15717. rejecting.enable_server_certificate_verification(false);
  15718. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15719. rejecting_calls++;
  15720. return false;
  15721. });
  15722. auto accepting_calls = 0;
  15723. SSLClient accepting(HOST, port);
  15724. accepting.enable_server_certificate_verification(false);
  15725. // Set on another thread than the requests below.
  15726. thread([&]() {
  15727. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15728. accepting_calls++;
  15729. return true;
  15730. });
  15731. }).join();
  15732. // Requested on another thread than the verifier was set on.
  15733. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15734. EXPECT_GT(rejecting_calls, 0);
  15735. auto res = accepting.Get("/test");
  15736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15737. EXPECT_GT(accepting_calls, 0);
  15738. }
  15739. // A verifier replaced while a handshake runs it lives until it returns.
  15740. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15741. using namespace httplib::tls;
  15742. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15743. ASSERT_TRUE(svr.is_valid());
  15744. svr.Get("/test", [](const Request &, Response &res) {
  15745. res.set_content("ok", "text/plain");
  15746. });
  15747. auto port = svr.bind_to_any_port(HOST);
  15748. thread t([&]() { svr.listen_after_bind(); });
  15749. auto se = detail::scope_exit([&] {
  15750. svr.stop();
  15751. t.join();
  15752. });
  15753. svr.wait_until_ready();
  15754. SSLClient cli(HOST, port);
  15755. cli.enable_server_certificate_verification(false);
  15756. std::promise<void> entered;
  15757. std::promise<void> replaced;
  15758. auto replaced_future = replaced.get_future();
  15759. auto first_call = true;
  15760. // Long enough to live on the heap
  15761. std::string expected(64, 'v');
  15762. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15763. if (first_call) {
  15764. first_call = false;
  15765. entered.set_value();
  15766. replaced_future.wait();
  15767. }
  15768. return expected == std::string(64, 'v');
  15769. });
  15770. thread request([&]() {
  15771. auto res = cli.Get("/test");
  15772. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15773. });
  15774. entered.get_future().wait();
  15775. cli.set_server_certificate_verifier(
  15776. [](const VerifyContext &) { return true; });
  15777. replaced.set_value();
  15778. request.join();
  15779. }
  15780. // VerifyContext::session is the same handle the other tls:: functions take.
  15781. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15782. using namespace httplib::tls;
  15783. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15784. ASSERT_TRUE(svr.is_valid());
  15785. svr.Get("/test", [](const Request &, Response &res) {
  15786. res.set_content("ok", "text/plain");
  15787. });
  15788. auto port = svr.bind_to_any_port(HOST);
  15789. thread t([&]() { svr.listen_after_bind(); });
  15790. auto se = detail::scope_exit([&] {
  15791. svr.stop();
  15792. t.join();
  15793. });
  15794. svr.wait_until_ready();
  15795. SSLClient cli(HOST, port);
  15796. cli.enable_server_certificate_verification(false);
  15797. session_t verifier_session = nullptr;
  15798. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15799. verifier_session = ctx.session;
  15800. return true;
  15801. });
  15802. session_t session_verifier_session = nullptr;
  15803. cli.set_session_verifier([&](session_t session) {
  15804. session_verifier_session = session;
  15805. return SSLVerifierResponse::NoDecisionMade;
  15806. });
  15807. auto res = cli.Get("/test");
  15808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15809. EXPECT_NE(nullptr, verifier_session);
  15810. EXPECT_EQ(session_verifier_session, verifier_session);
  15811. }
  15812. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15813. using httplib::tls::TlsError;
  15814. // Test that verify_error_to_string returns empty for success
  15815. std::string success_str = TlsError::verify_error_to_string(0);
  15816. EXPECT_TRUE(success_str.empty());
  15817. // Test that verify_error_to_string returns non-empty for error codes
  15818. // Using a common error code (certificate expired)
  15819. std::string error_str =
  15820. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15821. EXPECT_FALSE(error_str.empty());
  15822. }
  15823. TEST(SessionVerifierTest, CertificateAccepted) {
  15824. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15825. ASSERT_TRUE(svr.is_valid());
  15826. svr.Get("/test", [](const Request &, Response &res) {
  15827. res.set_content("ok", "text/plain");
  15828. });
  15829. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15830. auto se = detail::scope_exit([&] {
  15831. svr.stop();
  15832. t.join();
  15833. });
  15834. svr.wait_until_ready();
  15835. SSLClient cli(HOST, PORT);
  15836. cli.enable_server_certificate_verification(false);
  15837. cli.set_connection_timeout(30);
  15838. bool callback_called = false;
  15839. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15840. EXPECT_NE(session, nullptr);
  15841. callback_called = true;
  15842. return SSLVerifierResponse::CertificateAccepted;
  15843. });
  15844. auto res = cli.Get("/test");
  15845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15846. EXPECT_EQ(200, res->status);
  15847. EXPECT_TRUE(callback_called);
  15848. }
  15849. TEST(SessionVerifierTest, CertificateRejected) {
  15850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15851. ASSERT_TRUE(svr.is_valid());
  15852. svr.Get("/test", [](const Request &, Response &res) {
  15853. res.set_content("ok", "text/plain");
  15854. });
  15855. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15856. auto se = detail::scope_exit([&] {
  15857. svr.stop();
  15858. t.join();
  15859. });
  15860. svr.wait_until_ready();
  15861. SSLClient cli(HOST, PORT);
  15862. cli.enable_server_certificate_verification(false);
  15863. cli.set_connection_timeout(30);
  15864. bool callback_called = false;
  15865. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15866. EXPECT_NE(session, nullptr);
  15867. callback_called = true;
  15868. return SSLVerifierResponse::CertificateRejected;
  15869. });
  15870. auto res = cli.Get("/test");
  15871. EXPECT_FALSE(res);
  15872. EXPECT_TRUE(callback_called);
  15873. }
  15874. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15875. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15876. ASSERT_TRUE(svr.is_valid());
  15877. svr.Get("/test", [](const Request &, Response &res) {
  15878. res.set_content("ok", "text/plain");
  15879. });
  15880. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15881. auto se = detail::scope_exit([&] {
  15882. svr.stop();
  15883. t.join();
  15884. });
  15885. svr.wait_until_ready();
  15886. // NoDecisionMade with verification disabled should succeed (no default check)
  15887. SSLClient cli(HOST, PORT);
  15888. cli.enable_server_certificate_verification(false);
  15889. cli.set_connection_timeout(30);
  15890. bool callback_called = false;
  15891. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15892. EXPECT_NE(session, nullptr);
  15893. callback_called = true;
  15894. return SSLVerifierResponse::NoDecisionMade;
  15895. });
  15896. auto res = cli.Get("/test");
  15897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15898. EXPECT_EQ(200, res->status);
  15899. EXPECT_TRUE(callback_called);
  15900. }
  15901. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15902. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15903. ASSERT_TRUE(svr.is_valid());
  15904. svr.Get("/test", [](const Request &, Response &res) {
  15905. res.set_content("ok", "text/plain");
  15906. });
  15907. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15908. auto se = detail::scope_exit([&] {
  15909. svr.stop();
  15910. t.join();
  15911. });
  15912. svr.wait_until_ready();
  15913. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15914. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15915. // so we only check that the request fails, not whether the callback was
  15916. // called.
  15917. SSLClient cli(HOST, PORT);
  15918. cli.enable_server_certificate_verification(true);
  15919. cli.set_connection_timeout(30);
  15920. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15921. EXPECT_NE(session, nullptr);
  15922. return SSLVerifierResponse::NoDecisionMade;
  15923. });
  15924. auto res = cli.Get("/test");
  15925. EXPECT_FALSE(res);
  15926. }
  15927. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15928. // Test SSL server using PemMemory constructor with client CA certificates
  15929. // Read PEM files
  15930. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15931. read_file(SERVER_CERT_FILE, server_cert_pem);
  15932. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15933. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15934. // Create SSLServer with PemMemory constructor including client CA
  15935. SSLServer::PemMemory server_pem = {
  15936. server_cert_pem.c_str(),
  15937. server_cert_pem.size(),
  15938. server_key_pem.c_str(),
  15939. server_key_pem.size(),
  15940. client_ca_pem.c_str(),
  15941. client_ca_pem.size(),
  15942. nullptr // no password for server key
  15943. };
  15944. SSLServer svr(server_pem);
  15945. ASSERT_TRUE(svr.is_valid());
  15946. // No SSL error should be recorded for valid setup
  15947. EXPECT_EQ(0, svr.ssl_last_error());
  15948. // Set up server endpoints
  15949. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15950. res.set_content("ok", "text/plain");
  15951. });
  15952. // Start server in a thread
  15953. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15954. svr.wait_until_ready();
  15955. // Connect with client certificate (using constructor with paths)
  15956. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15957. cli.enable_server_certificate_verification(false);
  15958. auto res = cli.Get("/test-pem-ca");
  15959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15960. EXPECT_EQ(200, res->status);
  15961. EXPECT_EQ("ok", res->body);
  15962. svr.stop();
  15963. server_thread.join();
  15964. }
  15965. #endif
  15966. #ifdef _WIN32
  15967. TEST(CleanupTest, WSACleanup) {
  15968. int ret = WSACleanup();
  15969. ASSERT_EQ(0, ret);
  15970. }
  15971. #endif
  15972. #ifndef CPPHTTPLIB_SSL_ENABLED
  15973. TEST(NoSSLSupport, SimpleInterface) {
  15974. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15975. }
  15976. #endif
  15977. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15978. TEST(InvalidScheme, SimpleInterface) {
  15979. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15980. }
  15981. #endif
  15982. TEST(NoScheme, SimpleInterface) {
  15983. Client cli("yahoo.com:80");
  15984. ASSERT_TRUE(cli.is_valid());
  15985. }
  15986. TEST(SendAPI, SimpleInterface_Online) {
  15987. Client cli("http://yahoo.com");
  15988. Request req;
  15989. req.method = "GET";
  15990. req.path = "/";
  15991. auto res = cli.send(req);
  15992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15993. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15994. }
  15995. TEST(SendAPI, WithParamsInRequest) {
  15996. Server svr;
  15997. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15998. EXPECT_TRUE(req.has_param("test"));
  15999. EXPECT_EQ("test_value", req.get_param_value("test"));
  16000. });
  16001. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16002. auto se = detail::scope_exit([&] {
  16003. svr.stop();
  16004. t.join();
  16005. ASSERT_FALSE(svr.is_running());
  16006. });
  16007. svr.wait_until_ready();
  16008. Client cli(HOST, PORT);
  16009. {
  16010. Request req;
  16011. req.method = "GET";
  16012. req.path = "/";
  16013. req.params.emplace("test", "test_value");
  16014. auto res = cli.send(req);
  16015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16016. }
  16017. {
  16018. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  16019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16020. }
  16021. }
  16022. TEST(ClientImplMethods, GetSocketTest) {
  16023. httplib::Server svr;
  16024. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  16025. res.status = StatusCode::OK_200;
  16026. });
  16027. auto port = svr.bind_to_any_port("127.0.0.1");
  16028. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16029. auto se = detail::scope_exit([&] {
  16030. svr.stop();
  16031. thread.join();
  16032. ASSERT_FALSE(svr.is_running());
  16033. });
  16034. svr.wait_until_ready();
  16035. {
  16036. httplib::Client cli("127.0.0.1", port);
  16037. cli.set_keep_alive(true);
  16038. // Use the behavior of cpp-httplib of opening the connection
  16039. // only when the first request happens. If that changes,
  16040. // this test would be obsolete.
  16041. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  16042. // This also implicitly tests the server. But other tests would fail much
  16043. // earlier than this one to be considered.
  16044. auto res = cli.Get("/");
  16045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16046. EXPECT_EQ(StatusCode::OK_200, res->status);
  16047. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  16048. }
  16049. }
  16050. #ifdef CPPHTTPLIB_SSL_ENABLED
  16051. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  16052. Client cli("http://yahoo.com");
  16053. auto res = cli.Get("/");
  16054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16055. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  16056. cli.set_follow_location(true);
  16057. res = cli.Get("/");
  16058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16059. EXPECT_EQ(StatusCode::OK_200, res->status);
  16060. EXPECT_EQ("https://www.yahoo.com/", res->location);
  16061. }
  16062. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  16063. Client cli("https://yahoo.com");
  16064. auto res = cli.Get("/");
  16065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16066. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  16067. cli.set_follow_location(true);
  16068. res = cli.Get("/");
  16069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16070. EXPECT_EQ(StatusCode::OK_200, res->status);
  16071. EXPECT_EQ("https://www.yahoo.com/", res->location);
  16072. }
  16073. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  16074. Client cli("https://yahoo.com");
  16075. auto res = cli.Get("/");
  16076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16077. ASSERT_FALSE(!res);
  16078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16079. ASSERT_FALSE(res == nullptr);
  16080. ASSERT_TRUE(res != nullptr);
  16081. EXPECT_EQ(Error::Success, res.error());
  16082. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  16083. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  16084. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  16085. cli.set_follow_location(true);
  16086. res = cli.Get("/");
  16087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16088. EXPECT_EQ(Error::Success, res.error());
  16089. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  16090. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  16091. EXPECT_EQ(StatusCode::OK_200, res->status);
  16092. EXPECT_EQ("https://www.yahoo.com/", res->location);
  16093. }
  16094. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16095. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  16096. Client cli("https://cdnjs.cloudflare.com");
  16097. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  16098. Headers{{"Accept-Encoding", "br"}});
  16099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16100. EXPECT_EQ(StatusCode::OK_200, res->status);
  16101. EXPECT_EQ(287630U, res->body.size());
  16102. EXPECT_EQ("application/javascript; charset=utf-8",
  16103. res->get_header_value("Content-Type"));
  16104. }
  16105. #endif
  16106. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  16107. #undef REDIR_HOST // Silence compiler warning
  16108. #define REDIR_HOST "https://httpbingo.org"
  16109. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  16110. Client cli(REDIR_HOST);
  16111. cli.set_follow_location(true);
  16112. auto res = retry_service_failures([&] {
  16113. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  16114. });
  16115. SKIP_ON_SERVICE_FAILURE(res);
  16116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16117. EXPECT_EQ(StatusCode::OK_200, res->status);
  16118. }
  16119. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  16120. Client cli(REDIR_HOST);
  16121. cli.set_follow_location(true);
  16122. Params params;
  16123. params.emplace("url", "http://example.com");
  16124. params.emplace("status_code", "302");
  16125. auto res = retry_service_failures(
  16126. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  16127. SKIP_ON_SERVICE_FAILURE(res);
  16128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16129. EXPECT_EQ(StatusCode::OK_200, res->status);
  16130. }
  16131. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  16132. Client cli(REDIR_HOST);
  16133. cli.set_follow_location(true);
  16134. Params params;
  16135. params.emplace("url", "http://example.com");
  16136. auto res = retry_service_failures([&] {
  16137. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  16138. });
  16139. SKIP_ON_SERVICE_FAILURE(res);
  16140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16141. EXPECT_EQ(StatusCode::OK_200, res->status);
  16142. }
  16143. TEST(HttpToHttpsRedirectTest, CertFile) {
  16144. auto ssl_port = PORT + 1;
  16145. Server svr;
  16146. ASSERT_TRUE(svr.is_valid());
  16147. svr.Get("/index", [&](const Request &, Response &res) {
  16148. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16149. "/index");
  16150. svr.stop();
  16151. });
  16152. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16153. ASSERT_TRUE(ssl_svr.is_valid());
  16154. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  16155. res.set_content("test", "text/plain");
  16156. ssl_svr.stop();
  16157. });
  16158. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16159. thread t2 =
  16160. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  16161. auto se = detail::scope_exit([&] {
  16162. t2.join();
  16163. t.join();
  16164. ASSERT_FALSE(svr.is_running());
  16165. });
  16166. svr.wait_until_ready();
  16167. ssl_svr.wait_until_ready();
  16168. Client cli("127.0.0.1", PORT);
  16169. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16170. cli.enable_server_certificate_verification(true);
  16171. cli.set_follow_location(true);
  16172. cli.set_connection_timeout(30);
  16173. auto res = cli.Get("/index");
  16174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16175. ASSERT_EQ(StatusCode::OK_200, res->status);
  16176. }
  16177. TEST(UppercaseSchemeTest, UsesTLS) {
  16178. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16179. ASSERT_TRUE(ssl_svr.is_valid());
  16180. ssl_svr.Get("/index", [](const Request &, Response &res) {
  16181. res.set_content("test", "text/plain");
  16182. });
  16183. auto ssl_port = ssl_svr.bind_to_any_port("127.0.0.1");
  16184. auto https_url = "HTTPS://127.0.0.1:" + std::to_string(ssl_port);
  16185. Server svr;
  16186. svr.Get("/index", [&](const Request &, Response &res) {
  16187. res.set_redirect(https_url + "/index");
  16188. });
  16189. auto port = svr.bind_to_any_port("127.0.0.1");
  16190. auto t = thread([&] { ssl_svr.listen_after_bind(); });
  16191. auto t2 = thread([&] { svr.listen_after_bind(); });
  16192. auto se = detail::scope_exit([&] {
  16193. svr.stop();
  16194. ssl_svr.stop();
  16195. t2.join();
  16196. t.join();
  16197. });
  16198. ssl_svr.wait_until_ready();
  16199. svr.wait_until_ready();
  16200. {
  16201. Client cli(https_url);
  16202. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16203. auto res = cli.Get("/index");
  16204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16205. EXPECT_EQ("test", res->body);
  16206. }
  16207. {
  16208. Client cli("127.0.0.1", port);
  16209. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16210. cli.set_follow_location(true);
  16211. auto res = cli.Get("/index");
  16212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16213. EXPECT_EQ("test", res->body);
  16214. }
  16215. }
  16216. TEST(SSLClientRedirectTest, CertFile) {
  16217. auto ssl_port = PORT + 1;
  16218. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16219. ASSERT_TRUE(ssl_svr1.is_valid());
  16220. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16221. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16222. "/index");
  16223. ssl_svr1.stop();
  16224. });
  16225. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16226. ASSERT_TRUE(ssl_svr2.is_valid());
  16227. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16228. res.set_content("test", "text/plain");
  16229. ssl_svr2.stop();
  16230. });
  16231. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16232. thread t2 =
  16233. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16234. auto se = detail::scope_exit([&] {
  16235. t2.join();
  16236. t.join();
  16237. ASSERT_FALSE(ssl_svr1.is_running());
  16238. });
  16239. ssl_svr1.wait_until_ready();
  16240. ssl_svr2.wait_until_ready();
  16241. SSLClient cli("127.0.0.1", PORT);
  16242. std::string cert;
  16243. read_file(SERVER_CERT2_FILE, cert);
  16244. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16245. cli.enable_server_certificate_verification(true);
  16246. cli.set_follow_location(true);
  16247. cli.set_connection_timeout(30);
  16248. auto res = cli.Get("/index");
  16249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16250. ASSERT_EQ(StatusCode::OK_200, res->status);
  16251. }
  16252. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  16253. // another port, so the client follows it with a new client.
  16254. static Result GetThroughTlsRedirectToDifferentPort(
  16255. const std::function<void(SSLClient &)> &setup,
  16256. const char *target_cert = SERVER_CERT2_FILE,
  16257. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  16258. auto ssl_port = PORT + 1;
  16259. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16260. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16261. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16262. "/index");
  16263. });
  16264. SSLServer ssl_svr2(target_cert, target_key);
  16265. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16266. res.set_content("test", "text/plain");
  16267. });
  16268. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  16269. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  16270. auto se = detail::scope_exit([&] {
  16271. ssl_svr2.stop();
  16272. ssl_svr1.stop();
  16273. t2.join();
  16274. t.join();
  16275. });
  16276. ssl_svr1.wait_until_ready();
  16277. ssl_svr2.wait_until_ready();
  16278. SSLClient cli("127.0.0.1", PORT);
  16279. cli.set_follow_location(true);
  16280. cli.set_connection_timeout(30);
  16281. setup(cli);
  16282. return cli.Get("/index");
  16283. }
  16284. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  16285. auto calls = 0;
  16286. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  16287. cli.enable_server_certificate_verification(false);
  16288. // Accept the first server only.
  16289. cli.set_session_verifier([&](tls::session_t) {
  16290. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  16291. : SSLVerifierResponse::CertificateRejected;
  16292. });
  16293. });
  16294. ASSERT_FALSE(res);
  16295. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16296. EXPECT_EQ(2, calls);
  16297. }
  16298. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  16299. std::string pinned;
  16300. auto res = GetThroughTlsRedirectToDifferentPort(
  16301. [&](SSLClient &cli) {
  16302. cli.enable_server_certificate_verification(false);
  16303. // Pin the first certificate seen.
  16304. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  16305. if (pinned.empty()) { pinned = ctx.serial(); }
  16306. return ctx.serial() == pinned;
  16307. });
  16308. },
  16309. // A certificate other than the first server's.
  16310. SERVER_CERT_FILE);
  16311. EXPECT_FALSE(res);
  16312. EXPECT_FALSE(pinned.empty());
  16313. }
  16314. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  16315. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  16316. std::string cert;
  16317. read_file(SERVER_CERT2_FILE, cert);
  16318. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16319. });
  16320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16321. EXPECT_EQ(StatusCode::OK_200, res->status);
  16322. }
  16323. // The target's certificate is signed by the root CA, which the first server's
  16324. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  16325. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  16326. auto res = GetThroughTlsRedirectToDifferentPort(
  16327. [](SSLClient &cli) {
  16328. std::string root_ca, cert;
  16329. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16330. read_file(SERVER_CERT2_FILE, cert);
  16331. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16332. cli.load_ca_cert_store(cert.data(), cert.size());
  16333. cli.enable_server_hostname_verification(false);
  16334. },
  16335. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16337. EXPECT_EQ(StatusCode::OK_200, res->status);
  16338. }
  16339. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16340. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  16341. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  16342. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  16343. auto res = GetThroughTlsRedirectToDifferentPort(
  16344. [](SSLClient &cli) {
  16345. std::string root_ca, cert;
  16346. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16347. read_file(SERVER_CERT2_FILE, cert);
  16348. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16349. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16350. cli.enable_server_hostname_verification(false);
  16351. },
  16352. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16353. ASSERT_FALSE(res);
  16354. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16355. }
  16356. #endif
  16357. #endif
  16358. #ifdef CPPHTTPLIB_SSL_ENABLED
  16359. // Test that set_ca_cert_store() skips system certs (consistent with
  16360. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  16361. // should be trusted - system certs should NOT be loaded.
  16362. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  16363. // Load a specific cert that is NOT a system CA cert
  16364. std::string cert;
  16365. read_file(SERVER_CERT2_FILE, cert);
  16366. SSLClient cli("google.com");
  16367. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16368. cli.enable_server_certificate_verification(true);
  16369. // This should FAIL because:
  16370. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  16371. // 2. System certs should NOT be loaded when custom store is set
  16372. // If system certs WERE loaded, this would succeed
  16373. auto res = cli.Get("/");
  16374. ASSERT_FALSE(res);
  16375. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16376. }
  16377. // Same as above, but through the native store handle path. Regression test:
  16378. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  16379. // merged system certs into the user-provided store.
  16380. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  16381. std::string cert;
  16382. read_file(SERVER_CERT2_FILE, cert);
  16383. SSLClient cli("google.com");
  16384. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16385. cli.enable_server_certificate_verification(true);
  16386. auto res = cli.Get("/");
  16387. ASSERT_FALSE(res);
  16388. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16389. }
  16390. // A custom store set via the native handle must still verify a server whose
  16391. // cert it does contain.
  16392. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  16393. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16394. ASSERT_TRUE(svr.is_valid());
  16395. svr.Get("/test", [&](const Request &, Response &res) {
  16396. res.set_content("test", "text/plain");
  16397. });
  16398. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16399. auto se = detail::scope_exit([&] {
  16400. svr.stop();
  16401. t.join();
  16402. ASSERT_FALSE(svr.is_running());
  16403. });
  16404. svr.wait_until_ready();
  16405. SSLClient cli("127.0.0.1", PORT);
  16406. std::string cert;
  16407. read_file(SERVER_CERT2_FILE, cert);
  16408. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16409. cli.enable_server_certificate_verification(true);
  16410. cli.set_connection_timeout(30);
  16411. auto res = cli.Get("/test");
  16412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16413. ASSERT_EQ(StatusCode::OK_200, res->status);
  16414. }
  16415. // CA certs loaded through the universal Client must be transferred to the
  16416. // client created internally for following an HTTPS redirect. Regression test:
  16417. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  16418. // the CA data for redirect transfer.
  16419. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  16420. auto ssl_port = PORT + 1;
  16421. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16422. ASSERT_TRUE(ssl_svr1.is_valid());
  16423. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16424. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16425. "/index");
  16426. });
  16427. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16428. ASSERT_TRUE(ssl_svr2.is_valid());
  16429. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16430. res.set_content("test", "text/plain");
  16431. });
  16432. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16433. thread t2 =
  16434. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16435. auto se = detail::scope_exit([&] {
  16436. ssl_svr2.stop();
  16437. ssl_svr1.stop();
  16438. t2.join();
  16439. t.join();
  16440. ASSERT_FALSE(ssl_svr1.is_running());
  16441. });
  16442. ssl_svr1.wait_until_ready();
  16443. ssl_svr2.wait_until_ready();
  16444. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16445. std::string cert;
  16446. read_file(SERVER_CERT2_FILE, cert);
  16447. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16448. cli.enable_server_certificate_verification(true);
  16449. cli.set_follow_location(true);
  16450. cli.set_connection_timeout(30);
  16451. auto res = cli.Get("/index");
  16452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16453. ASSERT_EQ(StatusCode::OK_200, res->status);
  16454. }
  16455. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16456. // so a host signed by a system CA verifies even though a custom CA is set
  16457. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16458. std::string cert;
  16459. read_file(SERVER_CERT2_FILE, cert);
  16460. SSLClient cli("google.com");
  16461. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16462. cli.enable_system_ca(true);
  16463. cli.enable_server_certificate_verification(true);
  16464. auto res = cli.Get("/");
  16465. // Any status: Google may redirect or rate-limit CI runners.
  16466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16467. }
  16468. // The custom CA remains effective when combined with the system CA
  16469. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16470. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16471. ASSERT_TRUE(svr.is_valid());
  16472. svr.Get("/test", [&](const Request &, Response &res) {
  16473. res.set_content("test", "text/plain");
  16474. });
  16475. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16476. auto se = detail::scope_exit([&] {
  16477. svr.stop();
  16478. t.join();
  16479. ASSERT_FALSE(svr.is_running());
  16480. });
  16481. svr.wait_until_ready();
  16482. SSLClient cli("127.0.0.1", PORT);
  16483. std::string cert;
  16484. read_file(SERVER_CERT2_FILE, cert);
  16485. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16486. cli.enable_system_ca(true);
  16487. cli.enable_server_certificate_verification(true);
  16488. cli.set_connection_timeout(30);
  16489. auto res = cli.Get("/test");
  16490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16491. ASSERT_EQ(StatusCode::OK_200, res->status);
  16492. }
  16493. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16494. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16495. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16496. static CFDictionaryRef
  16497. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16498. const SecTrustSettingsResult *result) {
  16499. auto constraint =
  16500. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16501. &kCFTypeDictionaryValueCallBacks);
  16502. if (policy) {
  16503. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16504. }
  16505. if (policy_string) {
  16506. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16507. kCFStringEncodingUTF8);
  16508. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16509. CFRelease(str);
  16510. }
  16511. if (result) {
  16512. auto number_value = static_cast<SInt32>(*result);
  16513. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16514. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16515. CFRelease(number);
  16516. }
  16517. return constraint;
  16518. }
  16519. static SecTrustSettingsResult
  16520. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16521. auto trust_settings =
  16522. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16523. for (auto constraint : constraints) {
  16524. CFArrayAppendValue(trust_settings, constraint);
  16525. CFRelease(constraint);
  16526. }
  16527. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16528. CFRelease(trust_settings);
  16529. return result;
  16530. }
  16531. // The system CA loader takes a Keychain certificate as a trusted root only
  16532. // when its Trust Settings say so for SSL, not merely because it has some.
  16533. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16534. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16535. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16536. const auto deny = kSecTrustSettingsResultDeny;
  16537. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16538. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16539. auto x509_policy = SecPolicyCreateBasicX509();
  16540. // "Always Trust", which stores no constraint at all
  16541. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16542. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16543. ssl_trust_settings_result(
  16544. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16545. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16546. ssl_trust_settings_result(
  16547. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16548. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16549. ssl_trust_settings_result(
  16550. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16551. // "Never Trust", for everything or for SSL
  16552. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16553. ssl_trust_settings_result(
  16554. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16555. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16556. ssl_trust_settings_result(
  16557. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16558. // Trusted for another policy, for one host, or not at all
  16559. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16560. ssl_trust_settings_result(
  16561. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16562. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16563. ssl_trust_settings_result({make_usage_constraint(
  16564. ssl_policy, "www.example.com", &trust_root)}));
  16565. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16566. ssl_trust_settings_result(
  16567. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16568. // The first constraint that applies to SSL decides
  16569. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16570. ssl_trust_settings_result(
  16571. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16572. make_usage_constraint(nullptr, nullptr, &deny)}));
  16573. CFRelease(x509_policy);
  16574. CFRelease(ssl_policy);
  16575. }
  16576. #endif
  16577. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16578. // skip chain verification entirely (only the certificate identity was
  16579. // checked), so a server presenting an untrusted certificate with a matching
  16580. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16581. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16582. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16583. ASSERT_TRUE(svr.is_valid());
  16584. svr.Get("/test", [&](const Request &, Response &res) {
  16585. res.set_content("test", "text/plain");
  16586. });
  16587. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16588. auto se = detail::scope_exit([&] {
  16589. svr.stop();
  16590. t.join();
  16591. ASSERT_FALSE(svr.is_running());
  16592. });
  16593. svr.wait_until_ready();
  16594. SSLClient cli("127.0.0.1", PORT);
  16595. std::string cert;
  16596. // A trusted CA that did not sign the server certificate. The server cert
  16597. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16598. // this connection.
  16599. read_file(CLIENT_CA_CERT_FILE, cert);
  16600. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16601. cli.enable_server_certificate_verification(true);
  16602. cli.set_connection_timeout(30);
  16603. auto res = cli.Get("/test");
  16604. ASSERT_FALSE(res);
  16605. }
  16606. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16607. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16608. // CA that failed to come through fails verification instead of trusting them.
  16609. // (wolfSSL does not list the system CAs it loaded.)
  16610. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16611. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16612. ASSERT_TRUE(svr.is_valid());
  16613. auto port = svr.bind_to_any_port("127.0.0.1");
  16614. ASSERT_LT(0, port);
  16615. thread t = thread([&] { svr.listen_after_bind(); });
  16616. auto se = detail::scope_exit([&] {
  16617. svr.stop();
  16618. t.join();
  16619. ASSERT_FALSE(svr.is_running());
  16620. });
  16621. svr.wait_until_ready();
  16622. // The CAs a client trusts once its first request has loaded them
  16623. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16624. Client cli("https://127.0.0.1:" + std::to_string(port));
  16625. setup(cli);
  16626. cli.Get("/");
  16627. return tls::get_ca_names(cli.tls_context()).size();
  16628. };
  16629. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16630. EXPECT_EQ(0u,
  16631. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16632. }
  16633. #endif
  16634. // A TLS setting changed between requests applies to the next one, not just to
  16635. // the next connection
  16636. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16637. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16638. ASSERT_TRUE(svr.is_valid());
  16639. svr.Get("/", [](const Request &req, Response &res) {
  16640. res.set_content(std::to_string(req.remote_port), "text/plain");
  16641. });
  16642. auto port = svr.bind_to_any_port("127.0.0.1");
  16643. ASSERT_LT(0, port);
  16644. thread t = thread([&] { svr.listen_after_bind(); });
  16645. auto se = detail::scope_exit([&] {
  16646. svr.stop();
  16647. t.join();
  16648. ASSERT_FALSE(svr.is_running());
  16649. });
  16650. svr.wait_until_ready();
  16651. SSLClient cli("127.0.0.1", port);
  16652. cli.set_keep_alive(true);
  16653. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16654. cli.enable_server_certificate_verification(false);
  16655. // The port the request went out from, so a new one means a new connection
  16656. auto client_port = [&] {
  16657. auto res = cli.Get("/");
  16658. return res ? res->body : std::string();
  16659. };
  16660. auto last = client_port();
  16661. ASSERT_FALSE(last.empty());
  16662. // Setting a value it already has keeps the connection
  16663. cli.enable_server_certificate_verification(false);
  16664. cli.enable_server_hostname_verification(true);
  16665. EXPECT_EQ(last, client_port());
  16666. cli.enable_server_certificate_verification(true);
  16667. auto res = cli.Get("/");
  16668. EXPECT_FALSE(res);
  16669. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16670. std::string ca;
  16671. read_file(SERVER_CERT2_FILE, ca);
  16672. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16673. last = client_port();
  16674. ASSERT_FALSE(last.empty());
  16675. std::vector<std::function<void()>> setters = {
  16676. [&] { cli.enable_server_hostname_verification(false); },
  16677. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16678. [&] {
  16679. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16680. },
  16681. [&] {
  16682. cli.set_server_certificate_verifier(
  16683. [](const tls::VerifyContext &) { return true; });
  16684. },
  16685. [&] {
  16686. cli.set_session_verifier(
  16687. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16688. },
  16689. };
  16690. for (const auto &setter : setters) {
  16691. setter();
  16692. auto next = client_port();
  16693. ASSERT_FALSE(next.empty());
  16694. EXPECT_NE(last, next);
  16695. last = next;
  16696. }
  16697. cli.set_session_verifier(
  16698. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16699. auto handle = cli.open_stream("GET", "/");
  16700. EXPECT_FALSE(handle.is_valid());
  16701. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16702. }
  16703. // A PEM given to create_ca_store() needs no NUL after it
  16704. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16705. std::string pem;
  16706. read_file(SERVER_CERT2_FILE, pem);
  16707. auto buf = pem + "X";
  16708. auto store = tls::create_ca_store(buf.data(), pem.size());
  16709. EXPECT_TRUE(store != nullptr);
  16710. SSLClient cli("localhost");
  16711. cli.set_ca_cert_store(store);
  16712. }
  16713. // enable_system_ca(false) prevents system CA loading entirely
  16714. TEST(SSLClientTest, DisableSystemCa_Online) {
  16715. SSLClient cli("google.com");
  16716. cli.enable_system_ca(false);
  16717. cli.enable_server_certificate_verification(true);
  16718. auto res = cli.Get("/");
  16719. ASSERT_FALSE(res);
  16720. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16721. // itself when the CA chain is empty
  16722. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16723. res.error() == Error::SSLConnection);
  16724. }
  16725. // The universal Client forwards enable_system_ca()
  16726. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16727. std::string cert;
  16728. read_file(SERVER_CERT2_FILE, cert);
  16729. Client cli("https://google.com");
  16730. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16731. cli.enable_system_ca(true);
  16732. cli.enable_server_certificate_verification(true);
  16733. auto res = cli.Get("/");
  16734. // Any status: Google may redirect or rate-limit CI runners.
  16735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16736. }
  16737. // The system CA policy must carry over to the client created internally for
  16738. // following a cross-host HTTPS redirect
  16739. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16740. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16741. ASSERT_TRUE(svr.is_valid());
  16742. svr.Get("/index", [&](const Request &, Response &res) {
  16743. res.set_redirect("https://www.google.com/");
  16744. });
  16745. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16746. auto se = detail::scope_exit([&] {
  16747. svr.stop();
  16748. t.join();
  16749. ASSERT_FALSE(svr.is_running());
  16750. });
  16751. svr.wait_until_ready();
  16752. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16753. std::string cert;
  16754. read_file(SERVER_CERT2_FILE, cert);
  16755. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16756. cli.enable_system_ca(true);
  16757. cli.enable_server_certificate_verification(true);
  16758. cli.set_follow_location(true);
  16759. cli.set_connection_timeout(30);
  16760. // Receiving any response proves the redirect client completed the TLS
  16761. // handshake with a system-CA-signed host
  16762. auto res = cli.Get("/index");
  16763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16764. }
  16765. TEST(MultipartFormDataTest, LargeData) {
  16766. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16767. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16768. const ContentReader &content_reader) {
  16769. if (req.is_multipart_form_data()) {
  16770. std::vector<FormData> items;
  16771. content_reader(
  16772. [&](const FormData &file) {
  16773. items.push_back(file);
  16774. return true;
  16775. },
  16776. [&](const char *data, size_t data_length) {
  16777. items.back().content.append(data, data_length);
  16778. return true;
  16779. });
  16780. EXPECT_TRUE(std::string(items[0].name) == "document");
  16781. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16782. EXPECT_TRUE(items[0].filename == "2MB_data");
  16783. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16784. EXPECT_TRUE(items[1].name == "hello");
  16785. EXPECT_TRUE(items[1].content == "world");
  16786. EXPECT_TRUE(items[1].filename == "");
  16787. EXPECT_TRUE(items[1].content_type == "");
  16788. } else {
  16789. std::string body;
  16790. content_reader([&](const char *data, size_t data_length) {
  16791. body.append(data, data_length);
  16792. return true;
  16793. });
  16794. }
  16795. });
  16796. auto port = svr.bind_to_any_port(HOST);
  16797. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16798. auto se = detail::scope_exit([&] {
  16799. svr.stop();
  16800. t.join();
  16801. ASSERT_FALSE(svr.is_running());
  16802. });
  16803. svr.wait_until_ready();
  16804. {
  16805. std::string data(1024 * 1024 * 2, '.');
  16806. std::stringstream buffer;
  16807. buffer << data;
  16808. SSLClient cli(HOST, port);
  16809. cli.enable_server_certificate_verification(false);
  16810. UploadFormDataItems items{
  16811. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16812. {"hello", "world", "", ""},
  16813. };
  16814. auto res = cli.Post("/post", items);
  16815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16816. ASSERT_EQ(StatusCode::OK_200, res->status);
  16817. }
  16818. }
  16819. TEST(MultipartFormDataTest, DataProviderItems) {
  16820. std::random_device seed_gen;
  16821. std::mt19937 random(seed_gen());
  16822. std::string rand1;
  16823. rand1.resize(1000);
  16824. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16825. std::string rand2;
  16826. rand2.resize(3000);
  16827. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16828. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16829. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16830. const ContentReader &content_reader) {
  16831. ASSERT_FALSE(req.is_multipart_form_data());
  16832. std::string body;
  16833. content_reader([&](const char *data, size_t data_length) {
  16834. body.append(data, data_length);
  16835. return true;
  16836. });
  16837. EXPECT_EQ(body, "");
  16838. });
  16839. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16840. const ContentReader &content_reader) {
  16841. ASSERT_TRUE(req.is_multipart_form_data());
  16842. std::vector<FormData> items;
  16843. content_reader(
  16844. [&](const FormData &file) {
  16845. items.push_back(file);
  16846. return true;
  16847. },
  16848. [&](const char *data, size_t data_length) {
  16849. items.back().content.append(data, data_length);
  16850. return true;
  16851. });
  16852. ASSERT_TRUE(items.size() == 2);
  16853. EXPECT_EQ(std::string(items[0].name), "name1");
  16854. EXPECT_EQ(items[0].content, "Testing123");
  16855. EXPECT_EQ(items[0].filename, "filename1");
  16856. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16857. EXPECT_EQ(items[1].name, "name2");
  16858. EXPECT_EQ(items[1].content, "Testing456");
  16859. EXPECT_EQ(items[1].filename, "");
  16860. EXPECT_EQ(items[1].content_type, "");
  16861. });
  16862. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16863. const ContentReader &content_reader) {
  16864. ASSERT_TRUE(req.is_multipart_form_data());
  16865. std::vector<FormData> items;
  16866. content_reader(
  16867. [&](const FormData &file) {
  16868. items.push_back(file);
  16869. return true;
  16870. },
  16871. [&](const char *data, size_t data_length) {
  16872. items.back().content.append(data, data_length);
  16873. return true;
  16874. });
  16875. ASSERT_TRUE(items.size() == 2);
  16876. EXPECT_EQ(items[0].name, "name3");
  16877. EXPECT_EQ(items[0].content, rand1);
  16878. EXPECT_EQ(items[0].filename, "filename3");
  16879. EXPECT_EQ(items[0].content_type, "");
  16880. EXPECT_EQ(items[1].name, "name4");
  16881. EXPECT_EQ(items[1].content, rand2);
  16882. EXPECT_EQ(items[1].filename, "filename4");
  16883. EXPECT_EQ(items[1].content_type, "");
  16884. });
  16885. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16886. const ContentReader &content_reader) {
  16887. ASSERT_TRUE(req.is_multipart_form_data());
  16888. std::vector<FormData> items;
  16889. content_reader(
  16890. [&](const FormData &file) {
  16891. items.push_back(file);
  16892. return true;
  16893. },
  16894. [&](const char *data, size_t data_length) {
  16895. items.back().content.append(data, data_length);
  16896. return true;
  16897. });
  16898. ASSERT_TRUE(items.size() == 4);
  16899. EXPECT_EQ(std::string(items[0].name), "name1");
  16900. EXPECT_EQ(items[0].content, "Testing123");
  16901. EXPECT_EQ(items[0].filename, "filename1");
  16902. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16903. EXPECT_EQ(items[1].name, "name2");
  16904. EXPECT_EQ(items[1].content, "Testing456");
  16905. EXPECT_EQ(items[1].filename, "");
  16906. EXPECT_EQ(items[1].content_type, "");
  16907. EXPECT_EQ(items[2].name, "name3");
  16908. EXPECT_EQ(items[2].content, rand1);
  16909. EXPECT_EQ(items[2].filename, "filename3");
  16910. EXPECT_EQ(items[2].content_type, "");
  16911. EXPECT_EQ(items[3].name, "name4");
  16912. EXPECT_EQ(items[3].content, rand2);
  16913. EXPECT_EQ(items[3].filename, "filename4");
  16914. EXPECT_EQ(items[3].content_type, "");
  16915. });
  16916. auto port = svr.bind_to_any_port("localhost");
  16917. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16918. auto se = detail::scope_exit([&] {
  16919. svr.stop();
  16920. t.join();
  16921. ASSERT_FALSE(svr.is_running());
  16922. });
  16923. svr.wait_until_ready();
  16924. {
  16925. SSLClient cli("localhost", port);
  16926. cli.enable_server_certificate_verification(false);
  16927. UploadFormDataItems items{
  16928. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16929. {"name2", "Testing456", "", ""}, // not a file
  16930. };
  16931. {
  16932. auto res = cli.Post("/post-none", {}, {}, {});
  16933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16934. ASSERT_EQ(StatusCode::OK_200, res->status);
  16935. }
  16936. FormDataProviderItems providers;
  16937. {
  16938. auto res =
  16939. cli.Post("/post-items", {}, items, providers); // empty providers
  16940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16941. ASSERT_EQ(StatusCode::OK_200, res->status);
  16942. }
  16943. providers.push_back({"name3",
  16944. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16945. // test the offset is given correctly at each step
  16946. if (!offset)
  16947. sink.os.write(rand1.data(), 30);
  16948. else if (offset == 30)
  16949. sink.os.write(rand1.data() + 30, 300);
  16950. else if (offset == 330)
  16951. sink.os.write(rand1.data() + 330, 670);
  16952. else if (offset == rand1.size())
  16953. sink.done();
  16954. return true;
  16955. },
  16956. "filename3",
  16957. {}});
  16958. providers.push_back({"name4",
  16959. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16960. // test the offset is given correctly at each step
  16961. if (!offset)
  16962. sink.os.write(rand2.data(), 2000);
  16963. else if (offset == 2000)
  16964. sink.os.write(rand2.data() + 2000, 1);
  16965. else if (offset == 2001)
  16966. sink.os.write(rand2.data() + 2001, 999);
  16967. else if (offset == rand2.size())
  16968. sink.done();
  16969. return true;
  16970. },
  16971. "filename4",
  16972. {}});
  16973. {
  16974. auto res = cli.Post("/post-providers", {}, {}, providers);
  16975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16976. ASSERT_EQ(StatusCode::OK_200, res->status);
  16977. }
  16978. {
  16979. auto res = cli.Post("/post-both", {}, items, providers);
  16980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16981. ASSERT_EQ(StatusCode::OK_200, res->status);
  16982. }
  16983. }
  16984. }
  16985. TEST(MultipartFormDataTest, BadHeader) {
  16986. Server svr;
  16987. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16988. res.set_content("ok", "text/plain");
  16989. });
  16990. thread t = thread([&] { svr.listen(HOST, PORT); });
  16991. auto se = detail::scope_exit([&] {
  16992. svr.stop();
  16993. t.join();
  16994. ASSERT_FALSE(svr.is_running());
  16995. });
  16996. svr.wait_until_ready();
  16997. const std::string body =
  16998. "This is the preamble. It is to be ignored, though it\r\n"
  16999. "is a handy place for composition agents to include an\r\n"
  17000. "explanatory note to non-MIME conformant readers.\r\n"
  17001. "\r\n"
  17002. "\r\n"
  17003. "--simple boundary\r\n"
  17004. "Content-Disposition: form-data; name=\"field1\"\r\n"
  17005. ": BAD...\r\n"
  17006. "\r\n"
  17007. "value1\r\n"
  17008. "--simple boundary\r\n"
  17009. "Content-Disposition: form-data; name=\"field2\"; "
  17010. "filename=\"example.txt\"\r\n"
  17011. "\r\n"
  17012. "value2\r\n"
  17013. "--simple boundary--\r\n"
  17014. "This is the epilogue. It is also to be ignored.\r\n";
  17015. std::string content_type =
  17016. R"(multipart/form-data; boundary="simple boundary")";
  17017. Client cli(HOST, PORT);
  17018. auto res = cli.Post("/post", body, content_type.c_str());
  17019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17020. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17021. }
  17022. TEST(MultipartFormDataTest, WithPreamble) {
  17023. Server svr;
  17024. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17025. res.set_content("ok", "text/plain");
  17026. });
  17027. thread t = thread([&] { svr.listen(HOST, PORT); });
  17028. auto se = detail::scope_exit([&] {
  17029. svr.stop();
  17030. t.join();
  17031. ASSERT_FALSE(svr.is_running());
  17032. });
  17033. svr.wait_until_ready();
  17034. const std::string body =
  17035. "This is the preamble. It is to be ignored, though it\r\n"
  17036. "is a handy place for composition agents to include an\r\n"
  17037. "explanatory note to non-MIME conformant readers.\r\n"
  17038. "\r\n"
  17039. "\r\n"
  17040. "--simple boundary\r\n"
  17041. "Content-Disposition: form-data; name=\"field1\"\r\n"
  17042. "\r\n"
  17043. "value1\r\n"
  17044. "--simple boundary\r\n"
  17045. "Content-Disposition: form-data; name=\"field2\"; "
  17046. "filename=\"example.txt\"\r\n"
  17047. "\r\n"
  17048. "value2\r\n"
  17049. "--simple boundary--\r\n"
  17050. "This is the epilogue. It is also to be ignored.\r\n";
  17051. std::string content_type =
  17052. R"(multipart/form-data; boundary="simple boundary")";
  17053. Client cli(HOST, PORT);
  17054. auto res = cli.Post("/post", body, content_type.c_str());
  17055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17056. EXPECT_EQ(StatusCode::OK_200, res->status);
  17057. }
  17058. TEST(MultipartFormDataTest, PostCustomBoundary) {
  17059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17060. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  17061. const ContentReader &content_reader) {
  17062. if (req.is_multipart_form_data()) {
  17063. std::vector<FormData> items;
  17064. content_reader(
  17065. [&](const FormData &file) {
  17066. items.push_back(file);
  17067. return true;
  17068. },
  17069. [&](const char *data, size_t data_length) {
  17070. items.back().content.append(data, data_length);
  17071. return true;
  17072. });
  17073. EXPECT_TRUE(std::string(items[0].name) == "document");
  17074. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  17075. EXPECT_TRUE(items[0].filename == "2MB_data");
  17076. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  17077. EXPECT_TRUE(items[1].name == "hello");
  17078. EXPECT_TRUE(items[1].content == "world");
  17079. EXPECT_TRUE(items[1].filename == "");
  17080. EXPECT_TRUE(items[1].content_type == "");
  17081. } else {
  17082. std::string body;
  17083. content_reader([&](const char *data, size_t data_length) {
  17084. body.append(data, data_length);
  17085. return true;
  17086. });
  17087. }
  17088. });
  17089. auto port = svr.bind_to_any_port("localhost");
  17090. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17091. auto se = detail::scope_exit([&] {
  17092. svr.stop();
  17093. t.join();
  17094. ASSERT_FALSE(svr.is_running());
  17095. });
  17096. svr.wait_until_ready();
  17097. {
  17098. std::string data(1024 * 1024 * 2, '.');
  17099. std::stringstream buffer;
  17100. buffer << data;
  17101. SSLClient cli("localhost", port);
  17102. cli.enable_server_certificate_verification(false);
  17103. UploadFormDataItems items{
  17104. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17105. {"hello", "world", "", ""},
  17106. };
  17107. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  17108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17109. ASSERT_EQ(StatusCode::OK_200, res->status);
  17110. }
  17111. }
  17112. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  17113. std::string data(1024 * 1024 * 2, '&');
  17114. std::stringstream buffer;
  17115. buffer << data;
  17116. Client cli("https://localhost:8080");
  17117. UploadFormDataItems items{
  17118. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17119. {"hello", "world", "", ""},
  17120. };
  17121. for (const char &c : " \t\r\n") {
  17122. auto res =
  17123. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  17124. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  17125. ASSERT_FALSE(res);
  17126. }
  17127. }
  17128. TEST(MultipartFormDataTest, PutFormData) {
  17129. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17130. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  17131. const ContentReader &content_reader) {
  17132. if (req.is_multipart_form_data()) {
  17133. std::vector<FormData> items;
  17134. content_reader(
  17135. [&](const FormData &file) {
  17136. items.push_back(file);
  17137. return true;
  17138. },
  17139. [&](const char *data, size_t data_length) {
  17140. items.back().content.append(data, data_length);
  17141. return true;
  17142. });
  17143. EXPECT_TRUE(std::string(items[0].name) == "document");
  17144. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  17145. EXPECT_TRUE(items[0].filename == "2MB_data");
  17146. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  17147. EXPECT_TRUE(items[1].name == "hello");
  17148. EXPECT_TRUE(items[1].content == "world");
  17149. EXPECT_TRUE(items[1].filename == "");
  17150. EXPECT_TRUE(items[1].content_type == "");
  17151. } else {
  17152. std::string body;
  17153. content_reader([&](const char *data, size_t data_length) {
  17154. body.append(data, data_length);
  17155. return true;
  17156. });
  17157. }
  17158. });
  17159. auto port = svr.bind_to_any_port("localhost");
  17160. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17161. auto se = detail::scope_exit([&] {
  17162. svr.stop();
  17163. t.join();
  17164. ASSERT_FALSE(svr.is_running());
  17165. });
  17166. svr.wait_until_ready();
  17167. {
  17168. std::string data(1024 * 1024 * 2, '&');
  17169. std::stringstream buffer;
  17170. buffer << data;
  17171. SSLClient cli("localhost", port);
  17172. cli.enable_server_certificate_verification(false);
  17173. UploadFormDataItems items{
  17174. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17175. {"hello", "world", "", ""},
  17176. };
  17177. auto res = cli.Put("/put", items);
  17178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17179. ASSERT_EQ(StatusCode::OK_200, res->status);
  17180. }
  17181. }
  17182. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  17183. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17184. svr.Put("/put_customboundary",
  17185. [&](const Request &req, const Response & /*res*/,
  17186. const ContentReader &content_reader) {
  17187. if (req.is_multipart_form_data()) {
  17188. std::vector<FormData> items;
  17189. content_reader(
  17190. [&](const FormData &file) {
  17191. items.push_back(file);
  17192. return true;
  17193. },
  17194. [&](const char *data, size_t data_length) {
  17195. items.back().content.append(data, data_length);
  17196. return true;
  17197. });
  17198. EXPECT_TRUE(std::string(items[0].name) == "document");
  17199. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  17200. EXPECT_TRUE(items[0].filename == "2MB_data");
  17201. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  17202. EXPECT_TRUE(items[1].name == "hello");
  17203. EXPECT_TRUE(items[1].content == "world");
  17204. EXPECT_TRUE(items[1].filename == "");
  17205. EXPECT_TRUE(items[1].content_type == "");
  17206. } else {
  17207. std::string body;
  17208. content_reader([&](const char *data, size_t data_length) {
  17209. body.append(data, data_length);
  17210. return true;
  17211. });
  17212. }
  17213. });
  17214. auto port = svr.bind_to_any_port("localhost");
  17215. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17216. auto se = detail::scope_exit([&] {
  17217. svr.stop();
  17218. t.join();
  17219. ASSERT_FALSE(svr.is_running());
  17220. });
  17221. svr.wait_until_ready();
  17222. {
  17223. std::string data(1024 * 1024 * 2, '&');
  17224. std::stringstream buffer;
  17225. buffer << data;
  17226. SSLClient cli("localhost", port);
  17227. cli.enable_server_certificate_verification(false);
  17228. UploadFormDataItems items{
  17229. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17230. {"hello", "world", "", ""},
  17231. };
  17232. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  17233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17234. ASSERT_EQ(StatusCode::OK_200, res->status);
  17235. }
  17236. }
  17237. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  17238. std::string data(1024 * 1024 * 2, '&');
  17239. std::stringstream buffer;
  17240. buffer << data;
  17241. Client cli("https://localhost:8080");
  17242. cli.enable_server_certificate_verification(false);
  17243. UploadFormDataItems items{
  17244. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17245. {"hello", "world", "", ""},
  17246. };
  17247. for (const char &c : " \t\r\n") {
  17248. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  17249. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  17250. ASSERT_FALSE(res);
  17251. }
  17252. }
  17253. TEST(MultipartFormDataTest, AlternateFilename) {
  17254. auto handled = false;
  17255. Server svr;
  17256. svr.Post("/test", [&](const Request &req, Response &res) {
  17257. ASSERT_EQ(2u, req.form.files.size());
  17258. ASSERT_EQ(1u, req.form.fields.size());
  17259. // Test files
  17260. const auto &file1 = req.form.get_file("file1");
  17261. ASSERT_EQ("file1", file1.name);
  17262. ASSERT_EQ("A.txt", file1.filename);
  17263. ASSERT_EQ("text/plain", file1.content_type);
  17264. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  17265. const auto &file2 = req.form.get_file("file2");
  17266. ASSERT_EQ("file2", file2.name);
  17267. ASSERT_EQ("a.html", file2.filename);
  17268. ASSERT_EQ("text/html", file2.content_type);
  17269. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  17270. file2.content);
  17271. // Test text field
  17272. const auto &text = req.form.get_field("text");
  17273. ASSERT_EQ("text default", text);
  17274. res.set_content("ok", "text/plain");
  17275. handled = true;
  17276. });
  17277. thread t = thread([&] { svr.listen(HOST, PORT); });
  17278. auto se = detail::scope_exit([&] {
  17279. svr.stop();
  17280. t.join();
  17281. ASSERT_FALSE(svr.is_running());
  17282. ASSERT_TRUE(handled);
  17283. });
  17284. svr.wait_until_ready();
  17285. auto req = "POST /test HTTP/1.1\r\n"
  17286. "Host: localhost\r\n"
  17287. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17288. "Content-Length: 399\r\n"
  17289. "\r\n"
  17290. "----------\r\n"
  17291. "Content-Disposition: form-data; name=\"text\"\r\n"
  17292. "\r\n"
  17293. "text default\r\n"
  17294. "----------\r\n"
  17295. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  17296. "filename=\"a.txt\"; name=\"file1\"\r\n"
  17297. "Content-Type: text/plain\r\n"
  17298. "\r\n"
  17299. "Content of a.txt.\r\n"
  17300. "\r\n"
  17301. "----------\r\n"
  17302. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  17303. "\"a.html\"\r\n"
  17304. "Content-Type: text/html\r\n"
  17305. "\r\n"
  17306. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  17307. "\r\n"
  17308. "------------\r\n";
  17309. ASSERT_TRUE(send_request(1, req));
  17310. }
  17311. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  17312. auto handled = false;
  17313. Server svr;
  17314. svr.Post("/test", [&](const Request &req, Response &res) {
  17315. // Case-insensitive "utf-8''" prefix with a long value
  17316. const auto &file = req.form.get_file("file1");
  17317. ASSERT_EQ("file1", file.name);
  17318. // 8000 chars exercises both the Content-Disposition parser and the
  17319. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  17320. // Prior to the fix, std::regex_match on this header would cause O(N)
  17321. // stack recursion in libstdc++, leading to SIGSEGV.
  17322. std::string expected_filename(8000, 'A');
  17323. ASSERT_EQ(expected_filename, file.filename);
  17324. res.set_content("ok", "text/plain");
  17325. handled = true;
  17326. });
  17327. thread t = thread([&] { svr.listen(HOST, PORT); });
  17328. auto se = detail::scope_exit([&] {
  17329. svr.stop();
  17330. t.join();
  17331. ASSERT_FALSE(svr.is_running());
  17332. ASSERT_TRUE(handled);
  17333. });
  17334. svr.wait_until_ready();
  17335. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  17336. // Regression test for GHSA-qq6v-r583-3h69
  17337. std::string long_filename(8000, 'A');
  17338. std::string body = "----------\r\n"
  17339. "Content-Disposition: form-data; name=\"file1\"; "
  17340. "filename*=\"Utf-8''" +
  17341. long_filename +
  17342. "\"\r\n"
  17343. "\r\n"
  17344. "hello\r\n"
  17345. "------------\r\n";
  17346. auto req = "POST /test HTTP/1.1\r\n"
  17347. "Host: localhost\r\n"
  17348. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17349. "Content-Length: " +
  17350. std::to_string(body.size()) + "\r\n\r\n" + body;
  17351. ASSERT_TRUE(send_request(1, req));
  17352. }
  17353. TEST(MultipartFormDataTest, AlternateFilenameWithLanguageTag) {
  17354. auto handled = false;
  17355. Server svr;
  17356. svr.Post("/test", [&](const Request &req, Response &res) {
  17357. ASSERT_EQ("A.txt", req.form.get_file("file1").filename);
  17358. ASSERT_EQ("na\xC3\xAFve.txt", req.form.get_file("file2").filename);
  17359. res.set_content("ok", "text/plain");
  17360. handled = true;
  17361. });
  17362. thread t = thread([&] { svr.listen(HOST, PORT); });
  17363. auto se = detail::scope_exit([&] {
  17364. svr.stop();
  17365. t.join();
  17366. ASSERT_FALSE(svr.is_running());
  17367. ASSERT_TRUE(handled);
  17368. });
  17369. svr.wait_until_ready();
  17370. std::string body = "----------\r\n"
  17371. "Content-Disposition: form-data; name=\"file1\"; "
  17372. "filename*=UTF-8'en'%41.txt\r\n"
  17373. "\r\n"
  17374. "hello\r\n"
  17375. "----------\r\n"
  17376. "Content-Disposition: form-data; name=\"file2\"; "
  17377. "filename*=utf-8'fr-CA'na%C3%AFve.txt\r\n"
  17378. "\r\n"
  17379. "bonjour\r\n"
  17380. "------------\r\n";
  17381. auto req = "POST /test HTTP/1.1\r\n"
  17382. "Host: localhost\r\n"
  17383. "Connection: close\r\n"
  17384. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17385. "Content-Length: " +
  17386. std::to_string(body.size()) + "\r\n\r\n" + body;
  17387. ASSERT_TRUE(send_request(1, req));
  17388. }
  17389. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  17390. auto handled = false;
  17391. Server svr;
  17392. svr.Post("/test", [&](const Request &req, Response &) {
  17393. ASSERT_EQ(2u, req.form.fields.size());
  17394. const auto &text1 = req.form.get_field("text1");
  17395. ASSERT_EQ("text1", text1);
  17396. const auto &text2 = req.form.get_field("text2");
  17397. ASSERT_EQ("text2", text2);
  17398. handled = true;
  17399. });
  17400. thread t = thread([&] { svr.listen(HOST, PORT); });
  17401. auto se = detail::scope_exit([&] {
  17402. svr.stop();
  17403. t.join();
  17404. ASSERT_FALSE(svr.is_running());
  17405. ASSERT_TRUE(handled);
  17406. });
  17407. svr.wait_until_ready();
  17408. auto req = "POST /test HTTP/1.1\r\n"
  17409. "Host: localhost\r\n"
  17410. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17411. "Content-Length: 146\r\n"
  17412. "\r\n----------\r\n"
  17413. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17414. "\r\n"
  17415. "text1"
  17416. "\r\n----------\r\n"
  17417. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17418. "\r\n"
  17419. "text2"
  17420. "\r\n------------";
  17421. std::string response;
  17422. ASSERT_TRUE(send_request(1, req, &response));
  17423. ASSERT_EQ("200", response.substr(9, 3));
  17424. }
  17425. TEST(MultipartFormDataTest, ContentLength) {
  17426. auto handled = false;
  17427. Server svr;
  17428. svr.Post("/test", [&](const Request &req, Response &) {
  17429. ASSERT_EQ(2u, req.form.fields.size());
  17430. const auto &text1 = req.form.get_field("text1");
  17431. ASSERT_EQ("text1", text1);
  17432. const auto &text2 = req.form.get_field("text2");
  17433. ASSERT_EQ("text2", text2);
  17434. handled = true;
  17435. });
  17436. thread t = thread([&] { svr.listen(HOST, PORT); });
  17437. auto se = detail::scope_exit([&] {
  17438. svr.stop();
  17439. t.join();
  17440. ASSERT_FALSE(svr.is_running());
  17441. ASSERT_TRUE(handled);
  17442. });
  17443. svr.wait_until_ready();
  17444. auto req = "POST /test HTTP/1.1\r\n"
  17445. "Host: localhost\r\n"
  17446. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17447. "Content-Length: 167\r\n"
  17448. "\r\n----------\r\n"
  17449. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17450. "Content-Length: 5\r\n"
  17451. "\r\n"
  17452. "text1"
  17453. "\r\n----------\r\n"
  17454. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17455. "\r\n"
  17456. "text2"
  17457. "\r\n------------\r\n";
  17458. std::string response;
  17459. ASSERT_TRUE(send_request(1, req, &response));
  17460. ASSERT_EQ("200", response.substr(9, 3));
  17461. }
  17462. TEST(MultipartFormDataTest, AccessPartHeaders) {
  17463. auto handled = false;
  17464. Server svr;
  17465. svr.Post("/test", [&](const Request &req, Response &) {
  17466. ASSERT_EQ(2u, req.form.fields.size());
  17467. const auto &text1 = req.form.get_field("text1");
  17468. ASSERT_EQ("text1", text1);
  17469. // TODO: Add header access for text fields if needed
  17470. const auto &text2 = req.form.get_field("text2");
  17471. ASSERT_EQ("text2", text2);
  17472. // TODO: Header access for text fields needs to be implemented
  17473. // auto &headers = it->second.headers;
  17474. // ASSERT_EQ(3U, headers.size());
  17475. // auto custom_header = headers.find("x-whatever");
  17476. // ASSERT_TRUE(custom_header != headers.end());
  17477. // ASSERT_NE("customvalue", custom_header->second);
  17478. // ASSERT_EQ("CustomValue", custom_header->second);
  17479. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  17480. handled = true;
  17481. });
  17482. thread t = thread([&] { svr.listen(HOST, PORT); });
  17483. auto se = detail::scope_exit([&] {
  17484. svr.stop();
  17485. t.join();
  17486. ASSERT_FALSE(svr.is_running());
  17487. ASSERT_TRUE(handled);
  17488. });
  17489. svr.wait_until_ready();
  17490. auto req = "POST /test HTTP/1.1\r\n"
  17491. "Host: localhost\r\n"
  17492. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17493. "Content-Length: 232\r\n"
  17494. "\r\n----------\r\n"
  17495. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17496. "Content-Length: 5\r\n"
  17497. "X-Test: 1\r\n"
  17498. "\r\n"
  17499. "text1"
  17500. "\r\n----------\r\n"
  17501. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17502. "Content-Type: text/plain\r\n"
  17503. "X-Whatever: CustomValue\r\n"
  17504. "\r\n"
  17505. "text2"
  17506. "\r\n------------\r\n"
  17507. "That should be disregarded. Not even read";
  17508. std::string response;
  17509. ASSERT_TRUE(send_request(1, req, &response));
  17510. ASSERT_EQ("200", response.substr(9, 3));
  17511. }
  17512. TEST(MultipartFormDataTest, LargeHeader) {
  17513. auto handled = false;
  17514. Server svr;
  17515. svr.Post("/test", [&](const Request &req, Response &) {
  17516. ASSERT_EQ(1u, req.form.fields.size());
  17517. const auto &text = req.form.get_field("name1");
  17518. ASSERT_EQ("text1", text);
  17519. handled = true;
  17520. });
  17521. thread t = thread([&] { svr.listen(HOST, PORT); });
  17522. auto se = detail::scope_exit([&] {
  17523. svr.stop();
  17524. t.join();
  17525. ASSERT_FALSE(svr.is_running());
  17526. ASSERT_TRUE(handled);
  17527. });
  17528. svr.wait_until_ready();
  17529. auto boundary = std::string("cpp-httplib-multipart-data");
  17530. std::string content = "--" + boundary +
  17531. "\r\n"
  17532. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17533. "\r\n"
  17534. "text1\r\n"
  17535. "--" +
  17536. boundary + "--\r\n";
  17537. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17538. "Host: localhost\r\n"
  17539. "Content-Type: multipart/form-data;boundary=" +
  17540. boundary +
  17541. "\r\n"
  17542. "Content-Length: " +
  17543. std::to_string(content.size()) +
  17544. "\r\n"
  17545. "Dummy-Header: ";
  17546. std::string header_suffix = "\r\n"
  17547. "\r\n";
  17548. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17549. size_t header_dummy_size =
  17550. read_buff_size -
  17551. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17552. auto header_dummy = std::string(header_dummy_size, '@');
  17553. auto req = header_prefix + header_dummy + header_suffix + content;
  17554. std::string response;
  17555. ASSERT_TRUE(send_request(1, req, &response));
  17556. ASSERT_EQ("200", response.substr(9, 3));
  17557. }
  17558. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17559. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17560. // (not chunked Transfer-Encoding) after the streaming refactor.
  17561. auto handled = false;
  17562. Server svr;
  17563. svr.Post("/upload", [&](const Request &req, Response &res) {
  17564. auto cl_it = req.headers.find("Content-Length");
  17565. EXPECT_TRUE(cl_it != req.headers.end());
  17566. auto te_it = req.headers.find("Transfer-Encoding");
  17567. EXPECT_TRUE(te_it == req.headers.end());
  17568. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17569. res.set_content("ok", "text/plain");
  17570. handled = true;
  17571. });
  17572. auto port = svr.bind_to_any_port(HOST);
  17573. auto t = thread([&] { svr.listen_after_bind(); });
  17574. auto se = detail::scope_exit([&] {
  17575. svr.stop();
  17576. t.join();
  17577. ASSERT_FALSE(svr.is_running());
  17578. ASSERT_TRUE(handled);
  17579. });
  17580. svr.wait_until_ready();
  17581. UploadFormDataItems items = {
  17582. {"field1", "hello", "", "text/plain"},
  17583. {"file1", "world", "test.txt", "application/octet-stream"},
  17584. };
  17585. Client cli(HOST, port);
  17586. auto res = cli.Post("/upload", {}, items);
  17587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17588. EXPECT_EQ(StatusCode::OK_200, res->status);
  17589. }
  17590. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17591. // Verify that make_multipart_content_provider coalesces many small segments
  17592. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17593. constexpr size_t kItemCount = 1000;
  17594. UploadFormDataItems items;
  17595. items.reserve(kItemCount);
  17596. for (size_t i = 0; i < kItemCount; i++) {
  17597. items.push_back(
  17598. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17599. }
  17600. const std::string boundary = "----test-boundary";
  17601. auto content_length = detail::get_multipart_content_length(items, boundary);
  17602. auto provider = detail::make_multipart_content_provider(items, boundary);
  17603. // Drive the provider the same way write_content_with_progress does
  17604. size_t write_count = 0;
  17605. size_t total_bytes = 0;
  17606. DataSink sink;
  17607. size_t offset = 0;
  17608. sink.write = [&](const char *d, size_t l) -> bool {
  17609. (void)d;
  17610. write_count++;
  17611. total_bytes += l;
  17612. offset += l;
  17613. return true;
  17614. };
  17615. sink.is_writable = []() -> bool { return true; };
  17616. while (offset < content_length) {
  17617. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17618. }
  17619. EXPECT_EQ(content_length, total_bytes);
  17620. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17621. // With buffering into 64KB blocks, write_count should be much smaller.
  17622. auto segment_count = 3 * kItemCount + 1;
  17623. EXPECT_LT(write_count, segment_count / 10);
  17624. }
  17625. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17626. // Integration test: send many UploadFormDataItems and verify the server
  17627. // receives all of them correctly (#2410).
  17628. constexpr size_t kItemCount = 500;
  17629. auto handled = false;
  17630. Server svr;
  17631. svr.Post("/upload", [&](const Request &req, Response &res) {
  17632. EXPECT_EQ(kItemCount, req.form.fields.size());
  17633. for (size_t i = 0; i < kItemCount; i++) {
  17634. auto key = "field" + std::to_string(i);
  17635. auto val = "value" + std::to_string(i);
  17636. auto it = req.form.fields.find(key);
  17637. if (it != req.form.fields.end()) {
  17638. EXPECT_EQ(val, it->second.content);
  17639. } else {
  17640. ADD_FAILURE() << "Missing field: " << key;
  17641. }
  17642. }
  17643. res.set_content("ok", "text/plain");
  17644. handled = true;
  17645. });
  17646. auto port = svr.bind_to_any_port(HOST);
  17647. auto t = thread([&] { svr.listen_after_bind(); });
  17648. auto se = detail::scope_exit([&] {
  17649. svr.stop();
  17650. t.join();
  17651. ASSERT_FALSE(svr.is_running());
  17652. ASSERT_TRUE(handled);
  17653. });
  17654. svr.wait_until_ready();
  17655. UploadFormDataItems items;
  17656. items.reserve(kItemCount);
  17657. for (size_t i = 0; i < kItemCount; i++) {
  17658. items.push_back(
  17659. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17660. }
  17661. Client cli(HOST, port);
  17662. auto res = cli.Post("/upload", items);
  17663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17664. EXPECT_EQ(StatusCode::OK_200, res->status);
  17665. }
  17666. TEST(MultipartFormDataTest, MakeFileProvider) {
  17667. // Verify make_file_provider sends a file's contents correctly.
  17668. const std::string file_content(4096, 'Z');
  17669. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17670. {
  17671. std::ofstream ofs(tmp_path, std::ios::binary);
  17672. ofs.write(file_content.data(),
  17673. static_cast<std::streamsize>(file_content.size()));
  17674. }
  17675. auto handled = false;
  17676. Server svr;
  17677. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17678. const ContentReader &content_reader) {
  17679. ASSERT_TRUE(req.is_multipart_form_data());
  17680. std::vector<FormData> items;
  17681. content_reader(
  17682. [&](const FormData &file) {
  17683. items.push_back(file);
  17684. return true;
  17685. },
  17686. [&](const char *data, size_t data_length) {
  17687. items.back().content.append(data, data_length);
  17688. return true;
  17689. });
  17690. ASSERT_EQ(1u, items.size());
  17691. EXPECT_EQ("myfile", items[0].name);
  17692. EXPECT_EQ("data.bin", items[0].filename);
  17693. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17694. EXPECT_EQ(file_content, items[0].content);
  17695. handled = true;
  17696. });
  17697. auto port = svr.bind_to_any_port(HOST);
  17698. auto t = thread([&] { svr.listen_after_bind(); });
  17699. auto se = detail::scope_exit([&] {
  17700. svr.stop();
  17701. t.join();
  17702. ASSERT_FALSE(svr.is_running());
  17703. ASSERT_TRUE(handled);
  17704. std::remove(tmp_path.c_str());
  17705. });
  17706. svr.wait_until_ready();
  17707. FormDataProviderItems providers;
  17708. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17709. "application/octet-stream"));
  17710. Client cli(HOST, port);
  17711. auto res = cli.Post("/upload", {}, {}, providers);
  17712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17713. EXPECT_EQ(StatusCode::OK_200, res->status);
  17714. }
  17715. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17716. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17717. // (100) headers is rejected with a 400 Bad Request response.
  17718. Server svr;
  17719. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17720. res.set_content("ok", "text/plain");
  17721. });
  17722. thread t = thread([&] { svr.listen(HOST, PORT); });
  17723. auto se = detail::scope_exit([&] {
  17724. svr.stop();
  17725. t.join();
  17726. ASSERT_FALSE(svr.is_running());
  17727. });
  17728. svr.wait_until_ready();
  17729. // Build a multipart part with 101 custom headers (exceeding
  17730. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17731. std::stringstream body;
  17732. body << "--simpleboundary\r\n"
  17733. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17734. for (int i = 0; i < 101; i++) {
  17735. body << "X-Custom-Header-" << i << ": value\r\n";
  17736. }
  17737. body << "\r\n"
  17738. << "value1\r\n"
  17739. << "--simpleboundary--\r\n";
  17740. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17741. Client cli(HOST, PORT);
  17742. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17744. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17745. }
  17746. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17747. // A body that never contains the declared boundary must not be accumulated
  17748. // while the parser waits for it. Buffering it would also make every read
  17749. // rescan everything seen so far, which is quadratic in the body size.
  17750. Server svr;
  17751. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17752. res.set_content("ok", "text/plain");
  17753. });
  17754. auto port = svr.bind_to_any_port(HOST);
  17755. thread t = thread([&] { svr.listen_after_bind(); });
  17756. auto se = detail::scope_exit([&] {
  17757. svr.stop();
  17758. t.join();
  17759. ASSERT_FALSE(svr.is_running());
  17760. });
  17761. svr.wait_until_ready();
  17762. Client cli(HOST, port);
  17763. cli.set_read_timeout(60, 0);
  17764. cli.set_write_timeout(60, 0);
  17765. // '-' is the worst case: it matches the first character of the boundary, so
  17766. // every position has to be checked against it.
  17767. auto post_dashes = [&](size_t size) {
  17768. const std::string body(size, '-');
  17769. auto start = std::chrono::steady_clock::now();
  17770. auto res =
  17771. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17772. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17773. std::chrono::steady_clock::now() - start)
  17774. .count();
  17775. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17776. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17777. return ms;
  17778. };
  17779. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17780. // Windows.
  17781. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17782. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17783. // Comparing the two sizes rather than checking an absolute duration keeps
  17784. // this meaningful across build types and CI load, both of which move the
  17785. // absolute numbers by more than an order of magnitude. Four times the bytes
  17786. // costs about four times the time when parsing is linear, and about sixteen
  17787. // times when the body is buffered and rescanned.
  17788. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17789. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17790. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17791. << "ms, which suggests the body is being buffered and rescanned";
  17792. }
  17793. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17794. // A boundary can only be followed by CRLF or by "--", so anything else is
  17795. // malformed no matter what comes next. The parser must say so right away
  17796. // instead of buffering the rest of the declared body.
  17797. Server svr;
  17798. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17799. res.set_content("ok", "text/plain");
  17800. });
  17801. auto port = svr.bind_to_any_port(HOST);
  17802. thread t = thread([&] { svr.listen_after_bind(); });
  17803. auto se = detail::scope_exit([&] {
  17804. svr.stop();
  17805. t.join();
  17806. ASSERT_FALSE(svr.is_running());
  17807. });
  17808. svr.wait_until_ready();
  17809. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17810. // buffers instead of failing would still be waiting for the remaining bytes.
  17811. const std::string body = "--zzzz\r\n"
  17812. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17813. "\r\n"
  17814. "text1"
  17815. "\r\n--zzzzXX";
  17816. const std::string req = "POST /post HTTP/1.1\r\n"
  17817. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17818. "Content-Length: 1048576\r\n"
  17819. "\r\n" +
  17820. body;
  17821. std::string response;
  17822. ASSERT_TRUE(send_request(3, req, &response, port));
  17823. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17824. EXPECT_EQ("400", response.substr(9, 3));
  17825. }
  17826. // Posts a multipart body split into two writes, so that the server sees the
  17827. // split at whatever offset the caller chose, and expects the single "text1"
  17828. // field to come through.
  17829. static void expect_split_multipart_ok(const std::string &body1,
  17830. const std::string &body2) {
  17831. auto handled = false;
  17832. Server svr;
  17833. svr.Post("/post", [&](const Request &req, Response &) {
  17834. EXPECT_EQ(1u, req.form.fields.size());
  17835. EXPECT_EQ("text1", req.form.get_field("text1"));
  17836. handled = true;
  17837. });
  17838. auto port = svr.bind_to_any_port(HOST);
  17839. thread t = thread([&] { svr.listen_after_bind(); });
  17840. auto se = detail::scope_exit([&] {
  17841. svr.stop();
  17842. t.join();
  17843. ASSERT_FALSE(svr.is_running());
  17844. ASSERT_TRUE(handled);
  17845. });
  17846. svr.wait_until_ready();
  17847. // "Connection: close" makes the server close once it has answered, so the
  17848. // response drain ends immediately instead of idling until the read timeout.
  17849. const std::string head =
  17850. "POST /post HTTP/1.1\r\n"
  17851. "Host: localhost\r\n"
  17852. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17853. "Connection: close\r\n"
  17854. "Content-Length: " +
  17855. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17856. std::string response;
  17857. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17858. ASSERT_GE(response.size(), 12u) << "no response";
  17859. EXPECT_EQ("200", response.substr(9, 3));
  17860. }
  17861. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17862. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17863. // ignored, including when it does not arrive in the same read as the
  17864. // close-delimiter itself.
  17865. expect_split_multipart_ok("--zzzz\r\n"
  17866. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17867. "\r\n"
  17868. "text1"
  17869. "\r\n--zzzz--",
  17870. "\r\nthis epilogue must be ignored\r\n");
  17871. }
  17872. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17873. // The initial boundary may be preceded by a preamble of any length and may
  17874. // straddle a read boundary. Discarding data while waiting for it must not
  17875. // throw away a partial boundary sitting at the end of the buffer.
  17876. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17877. "zz\r\n"
  17878. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17879. "\r\n"
  17880. "text1"
  17881. "\r\n--zzzz--\r\n");
  17882. }
  17883. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17884. // The received boundary was only checked for being non-empty, so it could be
  17885. // as long as a header is allowed to be. The parser scans the body for
  17886. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17887. // costs a nearly full comparison at nearly every position, making the
  17888. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17889. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17890. Server svr;
  17891. svr.Post("/post", [](const Request &req, Response &res) {
  17892. EXPECT_EQ(1u, req.form.fields.size());
  17893. EXPECT_EQ("text1", req.form.get_field("text1"));
  17894. res.set_content("ok", "text/plain");
  17895. });
  17896. auto port = svr.bind_to_any_port(HOST);
  17897. thread t = thread([&] { svr.listen_after_bind(); });
  17898. auto se = detail::scope_exit([&] {
  17899. svr.stop();
  17900. t.join();
  17901. ASSERT_FALSE(svr.is_running());
  17902. });
  17903. svr.wait_until_ready();
  17904. Client cli(HOST, port);
  17905. auto post_with_boundary_of_length = [&](size_t len) {
  17906. const std::string boundary(len, 'a');
  17907. const std::string body =
  17908. "--" + boundary +
  17909. "\r\n"
  17910. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17911. "\r\n"
  17912. "text1"
  17913. "\r\n--" +
  17914. boundary + "--\r\n";
  17915. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17916. };
  17917. auto res = post_with_boundary_of_length(70);
  17918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17919. EXPECT_EQ(StatusCode::OK_200, res->status);
  17920. res = post_with_boundary_of_length(71);
  17921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17922. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17923. }
  17924. TEST(MakeFileBodyTest, Basic) {
  17925. const std::string file_content(4096, 'Z');
  17926. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17927. {
  17928. std::ofstream ofs(tmp_path, std::ios::binary);
  17929. ofs.write(file_content.data(),
  17930. static_cast<std::streamsize>(file_content.size()));
  17931. }
  17932. auto handled = false;
  17933. Server svr;
  17934. svr.Post("/upload", [&](const Request &req, Response &res) {
  17935. EXPECT_EQ(file_content, req.body);
  17936. handled = true;
  17937. res.status = StatusCode::OK_200;
  17938. });
  17939. auto port = svr.bind_to_any_port(HOST);
  17940. auto t = thread([&] { svr.listen_after_bind(); });
  17941. auto se = detail::scope_exit([&] {
  17942. svr.stop();
  17943. t.join();
  17944. ASSERT_FALSE(svr.is_running());
  17945. ASSERT_TRUE(handled);
  17946. std::remove(tmp_path.c_str());
  17947. });
  17948. svr.wait_until_ready();
  17949. auto fb = make_file_body(tmp_path);
  17950. ASSERT_GT(fb.first, 0u);
  17951. Client cli(HOST, port);
  17952. auto res =
  17953. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17955. EXPECT_EQ(StatusCode::OK_200, res->status);
  17956. }
  17957. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17958. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17959. {
  17960. std::ofstream ofs(path, std::ios::binary);
  17961. const std::string content(100, 'A');
  17962. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17963. }
  17964. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17965. auto body = make_file_body(path);
  17966. ASSERT_EQ(100u, body.first);
  17967. ASSERT_TRUE(static_cast<bool>(body.second));
  17968. // Rewritten shorter after its length was measured - and, on a server, after
  17969. // that length has already gone out as Content-Length.
  17970. {
  17971. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17972. const std::string content(10, 'A');
  17973. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17974. }
  17975. std::string written;
  17976. DataSink sink;
  17977. sink.write = [&](const char *d, size_t l) {
  17978. written.append(d, l);
  17979. return true;
  17980. };
  17981. // The provider has to report failure. write_content_with_progress() advances
  17982. // its offset only by what was written, so a provider that returns true
  17983. // without completing the length it promised is called again straight away,
  17984. // and again.
  17985. EXPECT_FALSE(body.second(0, body.first, sink));
  17986. EXPECT_EQ(std::string(10, 'A'), written);
  17987. }
  17988. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17989. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17990. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17991. {
  17992. std::ofstream ofs(path, std::ios::binary);
  17993. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17994. }
  17995. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17996. auto body = make_file_body(path);
  17997. ASSERT_EQ(content.size(), body.first);
  17998. ASSERT_TRUE(static_cast<bool>(body.second));
  17999. std::string written;
  18000. DataSink sink;
  18001. sink.write = [&](const char *d, size_t l) {
  18002. written.append(d, l);
  18003. return true;
  18004. };
  18005. EXPECT_TRUE(body.second(0, body.first, sink));
  18006. EXPECT_EQ(content, written);
  18007. }
  18008. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  18009. static constexpr unsigned int number_of_tasks{1000000};
  18010. std::atomic_uint count{0};
  18011. std::unique_ptr<TaskQueue> task_queue{
  18012. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  18013. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  18014. auto queued = task_queue->enqueue(
  18015. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  18016. EXPECT_TRUE(queued);
  18017. }
  18018. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  18019. task_queue->shutdown();
  18020. #else
  18021. EXPECT_NO_THROW(task_queue->shutdown());
  18022. #endif
  18023. EXPECT_EQ(number_of_tasks, count.load());
  18024. }
  18025. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  18026. static constexpr unsigned int number_of_tasks{1000000};
  18027. static constexpr unsigned int qlimit{2};
  18028. unsigned int queued_count{0};
  18029. std::atomic_uint count{0};
  18030. std::unique_ptr<TaskQueue> task_queue{
  18031. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  18032. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  18033. if (task_queue->enqueue(
  18034. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  18035. queued_count++;
  18036. }
  18037. }
  18038. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  18039. task_queue->shutdown();
  18040. #else
  18041. EXPECT_NO_THROW(task_queue->shutdown());
  18042. #endif
  18043. EXPECT_EQ(queued_count, count.load());
  18044. EXPECT_TRUE(queued_count <= number_of_tasks);
  18045. EXPECT_TRUE(queued_count >= qlimit);
  18046. }
  18047. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  18048. // Use a short idle timeout so a dynamic thread spawns, times out and
  18049. // exits during the test, and the pool keeps working afterwards.
  18050. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  18051. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  18052. /*idle_timeout_sec=*/1}};
  18053. std::atomic_uint count{0};
  18054. std::condition_variable cv;
  18055. std::mutex mtx;
  18056. bool release = false;
  18057. // Block the base thread so the second task spawns a dynamic thread.
  18058. EXPECT_TRUE(task_queue->enqueue([&] {
  18059. std::unique_lock<std::mutex> lock(mtx);
  18060. while (!release) {
  18061. cv.wait(lock);
  18062. }
  18063. count++;
  18064. }));
  18065. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  18066. // Let the dynamic thread finish its task and exceed the idle timeout.
  18067. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  18068. {
  18069. std::unique_lock<std::mutex> lock(mtx);
  18070. release = true;
  18071. }
  18072. cv.notify_all();
  18073. // The pool must still accept and run tasks after the dynamic thread exited.
  18074. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  18075. task_queue->shutdown();
  18076. EXPECT_EQ(3u, count.load());
  18077. }
  18078. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  18079. static constexpr size_t number_of_tasks{32};
  18080. std::unique_ptr<TaskQueue> task_queue{
  18081. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  18082. // Let the base threads go idle so the burst below finds them waiting.
  18083. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18084. std::mutex mtx;
  18085. std::condition_variable cv;
  18086. size_t running = 0;
  18087. bool release = false;
  18088. for (size_t i = 0; i < number_of_tasks; i++) {
  18089. EXPECT_TRUE(task_queue->enqueue([&] {
  18090. std::unique_lock<std::mutex> lock(mtx);
  18091. running++;
  18092. cv.notify_all();
  18093. cv.wait(lock, [&] { return release; });
  18094. }));
  18095. }
  18096. {
  18097. std::unique_lock<std::mutex> lock(mtx);
  18098. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  18099. [&] { return running == number_of_tasks; }));
  18100. release = true;
  18101. }
  18102. cv.notify_all();
  18103. task_queue->shutdown();
  18104. }
  18105. TEST(TaskQueueTest, MaxQueuedRequests) {
  18106. static constexpr unsigned int qlimit{3};
  18107. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  18108. std::condition_variable sem_cv;
  18109. std::mutex sem_mtx;
  18110. int credits = 0;
  18111. bool queued;
  18112. /* Fill up the queue with tasks that will block until we give them credits to
  18113. * complete. */
  18114. for (unsigned int n = 0; n <= qlimit;) {
  18115. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  18116. std::unique_lock<std::mutex> lock(sem_mtx);
  18117. while (credits <= 0) {
  18118. sem_cv.wait(lock);
  18119. }
  18120. /* Consume the credit and signal the test code if they are all gone. */
  18121. if (--credits == 0) { sem_cv.notify_one(); }
  18122. });
  18123. if (n < qlimit) {
  18124. /* The first qlimit enqueues must succeed. */
  18125. EXPECT_TRUE(queued);
  18126. } else {
  18127. /* The last one will succeed only when the worker thread
  18128. * starts and dequeues the first blocking task. Although
  18129. * not necessary for the correctness of this test, we sleep for
  18130. * a short while to avoid busy waiting. */
  18131. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18132. }
  18133. if (queued) { n++; }
  18134. }
  18135. /* Further enqueues must fail since the queue is full. */
  18136. for (auto i = 0; i < 4; i++) {
  18137. queued = task_queue->enqueue([] {});
  18138. EXPECT_FALSE(queued);
  18139. }
  18140. /* Give the credits to allow the previous tasks to complete. */
  18141. {
  18142. std::unique_lock<std::mutex> lock(sem_mtx);
  18143. credits += qlimit + 1;
  18144. }
  18145. sem_cv.notify_all();
  18146. /* Wait for all the credits to be consumed. */
  18147. {
  18148. std::unique_lock<std::mutex> lock(sem_mtx);
  18149. while (credits > 0) {
  18150. sem_cv.wait(lock);
  18151. }
  18152. }
  18153. /* Check that we are able again to enqueue at least qlimit tasks. */
  18154. for (unsigned int i = 0; i < qlimit; i++) {
  18155. queued = task_queue->enqueue([] {});
  18156. EXPECT_TRUE(queued);
  18157. }
  18158. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  18159. task_queue->shutdown();
  18160. #else
  18161. EXPECT_NO_THROW(task_queue->shutdown());
  18162. #endif
  18163. }
  18164. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  18165. Server svr;
  18166. std::string method;
  18167. std::string body;
  18168. auto has_content_length = false;
  18169. auto has_transfer_encoding = false;
  18170. std::atomic<int> bad_requests{0};
  18171. // Leftover body bytes get parsed as a malformed request and answered with
  18172. // 400
  18173. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  18174. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  18175. });
  18176. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  18177. res.set_redirect("/down", StatusCode::SeeOther_303);
  18178. });
  18179. svr.Get("/down", [&](const Request &req, Response &res) {
  18180. method = req.method;
  18181. body = req.body;
  18182. has_content_length = req.has_header("Content-Length");
  18183. has_transfer_encoding = req.has_header("Transfer-Encoding");
  18184. res.set_content("ok", "text/plain");
  18185. });
  18186. auto port = svr.bind_to_any_port(HOST);
  18187. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18188. auto se = detail::scope_exit([&] {
  18189. svr.stop();
  18190. thread.join();
  18191. ASSERT_FALSE(svr.is_running());
  18192. });
  18193. svr.wait_until_ready();
  18194. const std::string payload = "SECRET-BODY";
  18195. auto check = [&](Client &cli, const Result &res) {
  18196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18197. EXPECT_EQ(StatusCode::OK_200, res->status);
  18198. EXPECT_EQ("ok", res->body);
  18199. EXPECT_EQ("GET", method);
  18200. EXPECT_TRUE(body.empty());
  18201. EXPECT_FALSE(has_content_length);
  18202. EXPECT_FALSE(has_transfer_encoding);
  18203. // Nothing of the original body may be left on the connection
  18204. auto res2 = cli.Get("/down");
  18205. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18206. EXPECT_EQ(StatusCode::OK_200, res2->status);
  18207. EXPECT_EQ("ok", res2->body);
  18208. EXPECT_EQ(0, bad_requests);
  18209. };
  18210. // With content length
  18211. {
  18212. Client cli(HOST, port);
  18213. cli.set_keep_alive(true);
  18214. cli.set_follow_location(true);
  18215. auto res = cli.Post(
  18216. "/up", payload.size(),
  18217. [&](size_t offset, size_t length, DataSink &sink) {
  18218. return sink.write(payload.data() + offset, length);
  18219. },
  18220. "text/plain");
  18221. check(cli, res);
  18222. }
  18223. // Without content length (chunked)
  18224. {
  18225. Client cli(HOST, port);
  18226. cli.set_keep_alive(true);
  18227. cli.set_follow_location(true);
  18228. auto res = cli.Post(
  18229. "/up",
  18230. [&](size_t /*offset*/, DataSink &sink) {
  18231. sink.write(payload.data(), payload.size());
  18232. sink.done();
  18233. return true;
  18234. },
  18235. "text/plain");
  18236. check(cli, res);
  18237. }
  18238. }
  18239. TEST(RedirectTest, LocationPathIsNotDecoded) {
  18240. Server svr;
  18241. std::string target;
  18242. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  18243. // Echo the still-encoded name back in the Location
  18244. const std::string prefix = "/start/";
  18245. res.status = StatusCode::Found_302;
  18246. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  18247. });
  18248. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  18249. target = req.target;
  18250. res.set_content("ok", "text/plain");
  18251. });
  18252. auto port = svr.bind_to_any_port(HOST);
  18253. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18254. auto se = detail::scope_exit([&] {
  18255. svr.stop();
  18256. thread.join();
  18257. ASSERT_FALSE(svr.is_running());
  18258. });
  18259. svr.wait_until_ready();
  18260. // Decoding the Location path would turn the first four into a path
  18261. // separator, a query delimiter, a fragment delimiter and a different
  18262. // percent-encoded octet. The rest must keep reaching the server as they are.
  18263. const std::vector<std::string> names = {
  18264. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  18265. };
  18266. for (auto path_encode : {true, false}) {
  18267. Client cli(HOST, port);
  18268. cli.set_follow_location(true);
  18269. cli.set_path_encode(path_encode);
  18270. for (const auto &name : names) {
  18271. target.clear();
  18272. auto res = cli.Get("/start/" + name);
  18273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18274. EXPECT_EQ(StatusCode::OK_200, res->status);
  18275. EXPECT_EQ("/dest/" + name, target);
  18276. }
  18277. }
  18278. }
  18279. TEST(RedirectTest, NotModifiedIsReturned) {
  18280. Server svr;
  18281. svr.Get("/cached", [](const Request &, Response &res) {
  18282. res.status = StatusCode::NotModified_304;
  18283. });
  18284. auto port = svr.bind_to_any_port(HOST);
  18285. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18286. auto se = detail::scope_exit([&] {
  18287. svr.stop();
  18288. thread.join();
  18289. ASSERT_FALSE(svr.is_running());
  18290. });
  18291. svr.wait_until_ready();
  18292. Client cli(HOST, port);
  18293. cli.set_follow_location(true);
  18294. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  18295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18296. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  18297. }
  18298. TEST(RedirectTest, NoLocationIsReturned) {
  18299. Server svr;
  18300. svr.Get("/no-location", [](const Request &, Response &res) {
  18301. res.status = StatusCode::Found_302;
  18302. res.set_content("no location", "text/plain");
  18303. });
  18304. auto port = svr.bind_to_any_port(HOST);
  18305. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18306. auto se = detail::scope_exit([&] {
  18307. svr.stop();
  18308. thread.join();
  18309. ASSERT_FALSE(svr.is_running());
  18310. });
  18311. svr.wait_until_ready();
  18312. Client cli(HOST, port);
  18313. cli.set_follow_location(true);
  18314. auto res = cli.Get("/no-location");
  18315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18316. EXPECT_EQ(StatusCode::Found_302, res->status);
  18317. EXPECT_EQ("no location", res->body);
  18318. // The callbacks see the body of the response that is returned
  18319. auto handler_called = false;
  18320. auto progress_called = false;
  18321. std::string body;
  18322. auto res2 = cli.Get(
  18323. "/no-location",
  18324. [&](const Response &) {
  18325. handler_called = true;
  18326. return true;
  18327. },
  18328. [&](const char *data, size_t data_length) {
  18329. body.append(data, data_length);
  18330. return true;
  18331. },
  18332. [&](size_t, size_t) {
  18333. progress_called = true;
  18334. return true;
  18335. });
  18336. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18337. EXPECT_EQ(StatusCode::Found_302, res2->status);
  18338. EXPECT_TRUE(handler_called);
  18339. EXPECT_TRUE(progress_called);
  18340. EXPECT_EQ("no location", body);
  18341. }
  18342. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  18343. Server svr;
  18344. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18345. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  18346. });
  18347. svr.Get("/hello", [](const Request &req, Response &res) {
  18348. res.set_content(req.get_param_value("key"), "text/plain");
  18349. });
  18350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18351. auto se = detail::scope_exit([&] {
  18352. svr.stop();
  18353. thread.join();
  18354. ASSERT_FALSE(svr.is_running());
  18355. });
  18356. svr.wait_until_ready();
  18357. {
  18358. Client cli(HOST, PORT);
  18359. cli.set_follow_location(true);
  18360. auto res = cli.Get("/");
  18361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18362. EXPECT_EQ(StatusCode::OK_200, res->status);
  18363. EXPECT_EQ("val&key2=val2", res->body);
  18364. }
  18365. }
  18366. #endif
  18367. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  18368. Server svr;
  18369. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18370. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  18371. });
  18372. svr.Get("/hello", [](const Request &req, Response &res) {
  18373. res.set_content(req.get_param_value("key"), "text/plain");
  18374. });
  18375. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18376. auto se = detail::scope_exit([&] {
  18377. svr.stop();
  18378. thread.join();
  18379. ASSERT_FALSE(svr.is_running());
  18380. });
  18381. svr.wait_until_ready();
  18382. {
  18383. Client cli(HOST, PORT);
  18384. cli.set_follow_location(true);
  18385. auto res = cli.Get("/");
  18386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18387. EXPECT_EQ(StatusCode::OK_200, res->status);
  18388. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  18389. }
  18390. }
  18391. TEST(RedirectTest, RedirectWithPlusInPath) {
  18392. Server svr;
  18393. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18394. res.set_redirect("/a+b");
  18395. });
  18396. // Route pattern uses regex; escape + as \\+
  18397. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  18398. res.set_content(req.path, "text/plain");
  18399. });
  18400. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18401. auto se = detail::scope_exit([&] {
  18402. svr.stop();
  18403. thread.join();
  18404. ASSERT_FALSE(svr.is_running());
  18405. });
  18406. svr.wait_until_ready();
  18407. {
  18408. Client cli(HOST, PORT);
  18409. cli.set_follow_location(true);
  18410. auto res = cli.Get("/");
  18411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18412. EXPECT_EQ(StatusCode::OK_200, res->status);
  18413. EXPECT_EQ("/a+b", res->body);
  18414. }
  18415. }
  18416. TEST(RedirectTest, ResolveRelativeLocation) {
  18417. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  18418. const std::vector<std::pair<std::string, std::string>> cases = {
  18419. {"g", "/b/c/g"},
  18420. {"./g", "/b/c/g"},
  18421. {"g/", "/b/c/g/"},
  18422. {"?y", "/b/c/d;p?y"},
  18423. {"g?y", "/b/c/g?y"},
  18424. {"#s", "/b/c/d;p?q#s"},
  18425. {"g#s", "/b/c/g#s"},
  18426. {"g?y#s", "/b/c/g?y#s"},
  18427. {";x", "/b/c/;x"},
  18428. {"g;x", "/b/c/g;x"},
  18429. {".", "/b/c/"},
  18430. {"./", "/b/c/"},
  18431. {"..", "/b/"},
  18432. {"../", "/b/"},
  18433. {"../g", "/b/g"},
  18434. {"../..", "/"},
  18435. {"../../", "/"},
  18436. {"../../g", "/g"},
  18437. {"../../../g", "/g"},
  18438. {"g.", "/b/c/g."},
  18439. {".g", "/b/c/.g"},
  18440. {"g..", "/b/c/g.."},
  18441. {"..g", "/b/c/..g"},
  18442. {"./../g", "/b/g"},
  18443. {"./g/.", "/b/c/g/"},
  18444. {"g/./h", "/b/c/g/h"},
  18445. {"g/../h", "/b/c/h"},
  18446. {"g;x=1/./y", "/b/c/g;x=1/y"},
  18447. {"g;x=1/../y", "/b/c/y"},
  18448. {"g?y/./x", "/b/c/g?y/./x"},
  18449. {"g#s/../x", "/b/c/g#s/../x"},
  18450. // Not relative-path references, so left for parse_url.
  18451. {"/g", "/g"},
  18452. {"//g", "//g"},
  18453. {"http://g/x", "http://g/x"},
  18454. {"g:h", "g:h"},
  18455. };
  18456. for (const auto &c : cases) {
  18457. EXPECT_EQ(c.second,
  18458. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  18459. << c.first;
  18460. }
  18461. // A result starting with "//" is still a path, not a network-path reference
  18462. EXPECT_EQ("/.//g",
  18463. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  18464. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  18465. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  18466. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18467. }
  18468. TEST(RedirectTest, RemoveDotSegments) {
  18469. // RFC 3986 section 5.2.4
  18470. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18471. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18472. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18473. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18474. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18475. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18476. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18477. }
  18478. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18479. Server svr;
  18480. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18481. res.set_redirect("/dir/../target?x=1");
  18482. });
  18483. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18484. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18485. "/dir/./../target");
  18486. });
  18487. svr.Get("/target", [](const Request &req, Response &res) {
  18488. res.set_content(req.path, "text/plain");
  18489. });
  18490. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18491. auto se = detail::scope_exit([&] {
  18492. svr.stop();
  18493. th.join();
  18494. ASSERT_FALSE(svr.is_running());
  18495. });
  18496. svr.wait_until_ready();
  18497. Client cli("localhost", PORT);
  18498. cli.set_follow_location(true);
  18499. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18500. auto res = cli.Get(path);
  18501. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18502. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18503. EXPECT_EQ("/target", res->body) << path;
  18504. }
  18505. }
  18506. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18507. Server svr;
  18508. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18509. res.set_redirect(req.get_param_value("to"));
  18510. });
  18511. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18512. res.set_content(req.target, "text/plain");
  18513. });
  18514. svr.Get("/other", [](const Request &req, Response &res) {
  18515. res.set_content(req.target, "text/plain");
  18516. });
  18517. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18518. auto se = detail::scope_exit([&] {
  18519. svr.stop();
  18520. thread.join();
  18521. ASSERT_FALSE(svr.is_running());
  18522. });
  18523. svr.wait_until_ready();
  18524. const std::vector<std::pair<std::string, std::string>> cases = {
  18525. {"next", "/dir/next"},
  18526. {"./next?x=1", "/dir/next?x=1"},
  18527. {"next?source=https://example.com/catalog",
  18528. "/dir/next?source=https://example.com/catalog"},
  18529. {"../other", "/other"},
  18530. };
  18531. for (const auto &c : cases) {
  18532. Client cli(HOST, PORT);
  18533. cli.set_follow_location(true);
  18534. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18535. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18536. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18537. EXPECT_EQ(c.second, res->body) << c.first;
  18538. }
  18539. }
  18540. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18541. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18542. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18543. Server other;
  18544. std::atomic<int> other_hits{0};
  18545. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18546. other_hits++;
  18547. res.set_content("other", "text/plain");
  18548. });
  18549. auto other_port = other.bind_to_any_port("127.0.0.1");
  18550. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18551. Server svr;
  18552. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18553. res.set_redirect(req.get_param_value("to"));
  18554. });
  18555. svr.Get(".*", [](const Request &req, Response &res) {
  18556. res.set_content(req.path, "text/plain");
  18557. });
  18558. auto port = svr.bind_to_any_port(HOST);
  18559. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18560. auto se = detail::scope_exit([&] {
  18561. svr.stop();
  18562. thread.join();
  18563. other.stop();
  18564. other_thread.join();
  18565. ASSERT_FALSE(svr.is_running());
  18566. ASSERT_FALSE(other.is_running());
  18567. });
  18568. svr.wait_until_ready();
  18569. other.wait_until_ready();
  18570. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18571. for (const auto &to :
  18572. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18573. Client cli(HOST, port);
  18574. cli.set_follow_location(true);
  18575. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18576. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18577. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18578. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18579. }
  18580. EXPECT_EQ(0, other_hits.load());
  18581. }
  18582. #ifdef CPPHTTPLIB_SSL_ENABLED
  18583. TEST(RedirectTest, Issue2185_Online) {
  18584. SSLClient client("github.com");
  18585. client.set_follow_location(true);
  18586. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18587. "Coollab-Windows.zip");
  18588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18589. EXPECT_EQ(StatusCode::OK_200, res->status);
  18590. EXPECT_EQ(9920427U, res->body.size());
  18591. }
  18592. #endif
  18593. TEST(VulnerabilityTest, CRLFInjection) {
  18594. Server svr;
  18595. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18596. res.set_content("Hello 1", "text/plain");
  18597. });
  18598. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18599. res.set_content("Hello 2", "text/plain");
  18600. });
  18601. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18602. res.set_content("Hello 3", "text/plain");
  18603. });
  18604. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18605. res.set_content("Hello 4", "text/plain");
  18606. });
  18607. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18608. for (const auto &x : req.headers) {
  18609. auto key = x.first;
  18610. EXPECT_STRNE("evil", key.c_str());
  18611. }
  18612. });
  18613. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18614. auto se = detail::scope_exit([&] {
  18615. svr.stop();
  18616. thread.join();
  18617. ASSERT_FALSE(svr.is_running());
  18618. });
  18619. svr.wait_until_ready();
  18620. {
  18621. Client cli(HOST, PORT);
  18622. cli.Post("/test1", "A=B",
  18623. "application/x-www-form-urlencoded\r\nevil: hello1");
  18624. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18625. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18626. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18627. }
  18628. }
  18629. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18630. auto server_thread = std::thread([] {
  18631. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18632. default_socket_options(srv);
  18633. sockaddr_in addr{};
  18634. addr.sin_family = AF_INET;
  18635. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18636. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18637. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18638. ::listen(srv, 1);
  18639. sockaddr_in cli_addr{};
  18640. socklen_t cli_len = sizeof(cli_addr);
  18641. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18642. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18643. std::string buf_all;
  18644. char buf[2048];
  18645. ssize_t n;
  18646. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18647. buf_all.append(buf, static_cast<size_t>(n));
  18648. size_t pos;
  18649. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18650. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18651. auto e = request_block.find("\r\n");
  18652. if (e != std::string::npos) {
  18653. auto request_line = request_block.substr(0, e);
  18654. std::string msg =
  18655. "CRLF injection detected in request line: '" + request_line + "'";
  18656. EXPECT_FALSE(true) << msg;
  18657. }
  18658. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18659. ::send(cli,
  18660. #ifdef _WIN32
  18661. static_cast<const char *>(resp.c_str()),
  18662. static_cast<int>(resp.size()),
  18663. #else
  18664. resp.c_str(), resp.size(),
  18665. #endif
  18666. 0);
  18667. buf_all.erase(0, pos + 4);
  18668. }
  18669. }
  18670. detail::close_socket(cli);
  18671. detail::close_socket(srv);
  18672. });
  18673. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18674. auto cli = Client("127.0.0.1", PORT + 1);
  18675. auto headers = Headers{
  18676. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18677. {"Connection", "keep-alive"}};
  18678. auto res = cli.Get("/hi", headers);
  18679. EXPECT_FALSE(res);
  18680. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18681. server_thread.join();
  18682. }
  18683. // A request rejected before any byte reaches the socket must fail right away
  18684. // instead of waiting for a response the server will never send.
  18685. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18686. // The kernel completes the TCP handshake from the listen backlog, so the
  18687. // client connects, but nothing ever reads, responds or closes.
  18688. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18689. default_socket_options(srv);
  18690. sockaddr_in addr{};
  18691. addr.sin_family = AF_INET;
  18692. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18693. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18694. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18695. ASSERT_EQ(0, ::listen(srv, 8));
  18696. auto cli = Client("127.0.0.1", PORT + 1);
  18697. cli.set_read_timeout(10, 0);
  18698. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18699. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18700. std::chrono::steady_clock::now() - start)
  18701. .count();
  18702. };
  18703. {
  18704. Request req;
  18705. req.method = "GE T";
  18706. req.path = "/";
  18707. auto start = std::chrono::steady_clock::now();
  18708. auto res = cli.send(req);
  18709. EXPECT_FALSE(res);
  18710. EXPECT_EQ(Error::Write, res.error());
  18711. EXPECT_LT(elapsed_ms(start), 1000);
  18712. }
  18713. {
  18714. auto start = std::chrono::steady_clock::now();
  18715. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18716. EXPECT_FALSE(res);
  18717. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18718. EXPECT_LT(elapsed_ms(start), 1000);
  18719. }
  18720. EXPECT_FALSE(cli.is_socket_open());
  18721. detail::close_socket(srv);
  18722. }
  18723. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18724. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18725. default_socket_options(srv);
  18726. sockaddr_in addr{};
  18727. addr.sin_family = AF_INET;
  18728. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18729. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18730. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18731. ASSERT_EQ(0, ::listen(srv, 1));
  18732. std::string received;
  18733. auto server_thread = std::thread([&] {
  18734. auto sock = ::accept(srv, nullptr, nullptr);
  18735. if (sock == INVALID_SOCKET) { return; }
  18736. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18737. char buf[2048];
  18738. ssize_t n;
  18739. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18740. received.append(buf, static_cast<size_t>(n));
  18741. }
  18742. detail::close_socket(sock);
  18743. });
  18744. {
  18745. auto cli = Client("127.0.0.1", PORT + 1);
  18746. // "Z" sorts after the default headers, so writing straight to the socket
  18747. // would have sent the request line and those headers before the rejection.
  18748. auto handle =
  18749. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18750. EXPECT_FALSE(handle.is_valid());
  18751. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18752. }
  18753. server_thread.join();
  18754. detail::close_socket(srv);
  18755. EXPECT_TRUE(received.empty()) << received;
  18756. }
  18757. TEST(PathParamsTest, StaticMatch) {
  18758. const auto pattern = "/users/all";
  18759. detail::PathParamsMatcher matcher(pattern);
  18760. Request request;
  18761. request.path = "/users/all";
  18762. ASSERT_TRUE(matcher.match(request));
  18763. std::unordered_map<std::string, std::string> expected_params = {};
  18764. EXPECT_EQ(request.path_params, expected_params);
  18765. }
  18766. TEST(PathParamsTest, StaticMismatch) {
  18767. const auto pattern = "/users/all";
  18768. detail::PathParamsMatcher matcher(pattern);
  18769. Request request;
  18770. request.path = "/users/1";
  18771. ASSERT_FALSE(matcher.match(request));
  18772. }
  18773. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18774. const auto pattern = "/users/:id/subscriptions";
  18775. detail::PathParamsMatcher matcher(pattern);
  18776. Request request;
  18777. request.path = "/users/42/subscriptions";
  18778. ASSERT_TRUE(matcher.match(request));
  18779. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18780. EXPECT_EQ(request.path_params, expected_params);
  18781. }
  18782. TEST(PathParamsTest, SingleParamInTheEnd) {
  18783. const auto pattern = "/users/:id";
  18784. detail::PathParamsMatcher matcher(pattern);
  18785. Request request;
  18786. request.path = "/users/24";
  18787. ASSERT_TRUE(matcher.match(request));
  18788. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18789. EXPECT_EQ(request.path_params, expected_params);
  18790. }
  18791. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18792. const auto pattern = "/users/:id/";
  18793. detail::PathParamsMatcher matcher(pattern);
  18794. Request request;
  18795. request.path = "/users/42/";
  18796. ASSERT_TRUE(matcher.match(request));
  18797. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18798. EXPECT_EQ(request.path_params, expected_params);
  18799. }
  18800. TEST(PathParamsTest, EmptyParam) {
  18801. const auto pattern = "/users/:id/";
  18802. detail::PathParamsMatcher matcher(pattern);
  18803. Request request;
  18804. request.path = "/users//";
  18805. ASSERT_TRUE(matcher.match(request));
  18806. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18807. EXPECT_EQ(request.path_params, expected_params);
  18808. }
  18809. TEST(PathParamsTest, FragmentMismatch) {
  18810. const auto pattern = "/users/:id/";
  18811. detail::PathParamsMatcher matcher(pattern);
  18812. Request request;
  18813. request.path = "/admins/24/";
  18814. ASSERT_FALSE(matcher.match(request));
  18815. }
  18816. TEST(PathParamsTest, ExtraFragments) {
  18817. const auto pattern = "/users/:id";
  18818. detail::PathParamsMatcher matcher(pattern);
  18819. Request request;
  18820. request.path = "/users/42/subscriptions";
  18821. ASSERT_FALSE(matcher.match(request));
  18822. }
  18823. TEST(PathParamsTest, MissingTrailingParam) {
  18824. const auto pattern = "/users/:id";
  18825. detail::PathParamsMatcher matcher(pattern);
  18826. Request request;
  18827. request.path = "/users";
  18828. ASSERT_FALSE(matcher.match(request));
  18829. }
  18830. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18831. const auto pattern = "/users/:id/subscriptions";
  18832. detail::PathParamsMatcher matcher(pattern);
  18833. Request request;
  18834. request.path = "/users/subscriptions";
  18835. ASSERT_FALSE(matcher.match(request));
  18836. }
  18837. TEST(PathParamsTest, MultipleParams) {
  18838. const auto pattern = "/users/:userid/subscriptions/:subid";
  18839. detail::PathParamsMatcher matcher(pattern);
  18840. Request request;
  18841. request.path = "/users/42/subscriptions/2";
  18842. ASSERT_TRUE(matcher.match(request));
  18843. std::unordered_map<std::string, std::string> expected_params = {
  18844. {"userid", "42"}, {"subid", "2"}};
  18845. EXPECT_EQ(request.path_params, expected_params);
  18846. }
  18847. TEST(PathParamsTest, SequenceOfParams) {
  18848. const auto pattern = "/values/:x/:y/:z";
  18849. detail::PathParamsMatcher matcher(pattern);
  18850. Request request;
  18851. request.path = "/values/1/2/3";
  18852. ASSERT_TRUE(matcher.match(request));
  18853. std::unordered_map<std::string, std::string> expected_params = {
  18854. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18855. EXPECT_EQ(request.path_params, expected_params);
  18856. }
  18857. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18858. const auto pattern = "/prefix:suffix";
  18859. detail::PathParamsMatcher matcher(pattern);
  18860. Request request;
  18861. request.path = "/prefix:suffix";
  18862. ASSERT_TRUE(matcher.match(request));
  18863. const std::unordered_map<std::string, std::string> expected_params = {};
  18864. EXPECT_EQ(request.path_params, expected_params);
  18865. }
  18866. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18867. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18868. // calling thread's stack on a long enough path for a quantified pattern;
  18869. // RegexMatcher must refuse to run regex matching on paths beyond
  18870. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18871. detail::RegexMatcher matcher("/files/(.*)");
  18872. Request within_limit;
  18873. within_limit.path = "/files/" + std::string(10, 'A');
  18874. EXPECT_TRUE(matcher.match(within_limit));
  18875. Request over_limit;
  18876. over_limit.path =
  18877. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18878. EXPECT_FALSE(matcher.match(over_limit));
  18879. }
  18880. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18881. Server svr;
  18882. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18883. res.set_content("ok", "text/plain");
  18884. });
  18885. auto port = svr.bind_to_any_port(HOST);
  18886. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18887. auto se = detail::scope_exit([&] {
  18888. svr.stop();
  18889. thread.join();
  18890. ASSERT_FALSE(svr.is_running());
  18891. });
  18892. svr.wait_until_ready();
  18893. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18894. // request URI limit; this used to be able to crash the process.
  18895. std::string path =
  18896. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18897. std::string req = "GET " + path +
  18898. " HTTP/1.1\r\n"
  18899. "Host: " +
  18900. std::string(HOST) + ":" + std::to_string(port) +
  18901. "\r\n"
  18902. "Connection: close\r\n"
  18903. "\r\n";
  18904. std::string response;
  18905. ASSERT_TRUE(send_request(5, req, &response, port));
  18906. EXPECT_NE(std::string::npos, response.find("404"));
  18907. }
  18908. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18909. Server svr;
  18910. auto handler = [](const Request & /*req*/, Response &res) {
  18911. res.set_content("hit", "text/plain");
  18912. };
  18913. // No regex metacharacter, so this one is compared literally
  18914. svr.Get("/literal/route", handler);
  18915. // '.' is a regex metacharacter, so this one must keep regex semantics
  18916. svr.Get("/a.c", handler);
  18917. auto port = svr.bind_to_any_port(HOST);
  18918. std::thread t([&]() { svr.listen_after_bind(); });
  18919. auto se = detail::scope_exit([&] {
  18920. svr.stop();
  18921. t.join();
  18922. ASSERT_FALSE(svr.is_running());
  18923. });
  18924. svr.wait_until_ready();
  18925. Client cli(HOST, port);
  18926. struct {
  18927. const char *path;
  18928. int status;
  18929. } cases[] = {
  18930. {"/literal/route", StatusCode::OK_200},
  18931. {"/literal/routes", StatusCode::NotFound_404},
  18932. {"/literal/rout", StatusCode::NotFound_404},
  18933. {"/abc", StatusCode::OK_200},
  18934. {"/a.c", StatusCode::OK_200},
  18935. };
  18936. for (const auto &x : cases) {
  18937. auto res = cli.Get(x.path);
  18938. ASSERT_TRUE(res) << x.path;
  18939. EXPECT_EQ(x.status, res->status) << x.path;
  18940. }
  18941. }
  18942. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18943. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18944. // from exhausting the stack, so it must only constrain routes that actually
  18945. // run a regular expression. A literal route is matched by comparison and
  18946. // stays usable at any length.
  18947. Server svr;
  18948. const std::string pattern =
  18949. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18950. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18951. res.set_content("hit", "text/plain");
  18952. });
  18953. auto port = svr.bind_to_any_port(HOST);
  18954. std::thread t([&]() { svr.listen_after_bind(); });
  18955. auto se = detail::scope_exit([&] {
  18956. svr.stop();
  18957. t.join();
  18958. ASSERT_FALSE(svr.is_running());
  18959. });
  18960. svr.wait_until_ready();
  18961. Client cli(HOST, port);
  18962. auto res = cli.Get(pattern);
  18963. ASSERT_TRUE(res);
  18964. EXPECT_EQ(StatusCode::OK_200, res->status);
  18965. }
  18966. TEST(ParseUrlTest, VariousPatterns) {
  18967. {
  18968. detail::UrlComponents uc;
  18969. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18970. EXPECT_EQ("http", uc.scheme);
  18971. EXPECT_EQ("example.com", uc.host);
  18972. EXPECT_EQ("8080", uc.port);
  18973. EXPECT_EQ("/path", uc.path);
  18974. EXPECT_EQ("?q=1", uc.query);
  18975. }
  18976. {
  18977. detail::UrlComponents uc;
  18978. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18979. EXPECT_EQ("https", uc.scheme);
  18980. EXPECT_EQ("example.com", uc.host);
  18981. EXPECT_TRUE(uc.port.empty());
  18982. EXPECT_EQ("/path", uc.path);
  18983. }
  18984. {
  18985. detail::UrlComponents uc;
  18986. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18987. EXPECT_EQ("::1", uc.host);
  18988. EXPECT_EQ("8080", uc.port);
  18989. EXPECT_EQ("/path", uc.path);
  18990. }
  18991. {
  18992. detail::UrlComponents uc;
  18993. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18994. }
  18995. {
  18996. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18997. // the path while the connection still targets the bracketed host.
  18998. detail::UrlComponents uc;
  18999. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  19000. }
  19001. {
  19002. detail::UrlComponents uc;
  19003. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  19004. }
  19005. {
  19006. detail::UrlComponents uc;
  19007. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  19008. EXPECT_EQ("::1", uc.host);
  19009. EXPECT_TRUE(uc.port.empty());
  19010. EXPECT_EQ("/path", uc.path);
  19011. }
  19012. {
  19013. detail::UrlComponents uc;
  19014. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  19015. EXPECT_TRUE(uc.scheme.empty());
  19016. EXPECT_EQ("example.com", uc.host);
  19017. EXPECT_EQ("/path", uc.path);
  19018. EXPECT_EQ("?q=1", uc.query);
  19019. }
  19020. {
  19021. detail::UrlComponents uc;
  19022. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  19023. EXPECT_TRUE(uc.host.empty());
  19024. EXPECT_EQ("/path", uc.path);
  19025. EXPECT_EQ("?q=1", uc.query);
  19026. }
  19027. {
  19028. detail::UrlComponents uc;
  19029. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  19030. EXPECT_EQ("example.com", uc.host);
  19031. EXPECT_EQ("8080", uc.port);
  19032. }
  19033. {
  19034. // Unix socket path — must not be parsed as host
  19035. detail::UrlComponents uc;
  19036. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  19037. EXPECT_TRUE(uc.host.empty());
  19038. }
  19039. {
  19040. detail::UrlComponents uc;
  19041. ASSERT_TRUE(detail::parse_url("", uc));
  19042. EXPECT_TRUE(uc.host.empty());
  19043. EXPECT_TRUE(uc.path.empty());
  19044. }
  19045. {
  19046. detail::UrlComponents uc;
  19047. ASSERT_TRUE(detail::parse_url("HTTP://example.com/path", uc));
  19048. EXPECT_EQ("http", uc.scheme);
  19049. }
  19050. {
  19051. detail::UrlComponents uc;
  19052. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  19053. }
  19054. {
  19055. // Accepted by parse_url; callers restrict to http/https
  19056. detail::UrlComponents uc;
  19057. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  19058. EXPECT_EQ("ftp", uc.scheme);
  19059. }
  19060. {
  19061. detail::UrlComponents uc;
  19062. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  19063. }
  19064. {
  19065. detail::UrlComponents uc;
  19066. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  19067. }
  19068. }
  19069. TEST(ParseUrlTest, FragmentHandling) {
  19070. {
  19071. detail::UrlComponents uc;
  19072. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  19073. EXPECT_EQ("/path", uc.path);
  19074. EXPECT_TRUE(uc.query.empty());
  19075. }
  19076. {
  19077. detail::UrlComponents uc;
  19078. ASSERT_TRUE(detail::parse_url("#frag", uc));
  19079. EXPECT_TRUE(uc.path.empty());
  19080. EXPECT_TRUE(uc.query.empty());
  19081. }
  19082. }
  19083. TEST(ParseUrlTest, UserinfoHandling) {
  19084. // userinfo, and a backslash some parsers take for '/', are rejected: such
  19085. // parsers would see evil.com as the host.
  19086. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  19087. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  19088. for (auto url : urls) {
  19089. detail::UrlComponents uc;
  19090. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  19091. }
  19092. }
  19093. TEST(ParseUrlTest, IPv6EdgeCases) {
  19094. {
  19095. detail::UrlComponents uc;
  19096. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  19097. EXPECT_TRUE(uc.scheme.empty());
  19098. EXPECT_EQ("::1", uc.host);
  19099. EXPECT_EQ("8080", uc.port);
  19100. }
  19101. {
  19102. // Zone ID '%25' is not in [a-fA-F0-9:]
  19103. detail::UrlComponents uc;
  19104. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  19105. }
  19106. }
  19107. TEST(ParseUrlTest, SchemeEdgeCases) {
  19108. {
  19109. detail::UrlComponents uc;
  19110. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  19111. }
  19112. {
  19113. detail::UrlComponents uc;
  19114. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  19115. }
  19116. {
  19117. detail::UrlComponents uc;
  19118. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  19119. }
  19120. {
  19121. detail::UrlComponents uc;
  19122. ASSERT_TRUE(detail::parse_url("httpS://example.com/path", uc));
  19123. EXPECT_EQ("https", uc.scheme);
  19124. }
  19125. {
  19126. detail::UrlComponents uc;
  19127. ASSERT_TRUE(detail::parse_url("/path?next=https://example.com/", uc));
  19128. EXPECT_TRUE(uc.scheme.empty());
  19129. EXPECT_TRUE(uc.host.empty());
  19130. EXPECT_EQ("/path", uc.path);
  19131. EXPECT_EQ("?next=https://example.com/", uc.query);
  19132. }
  19133. }
  19134. TEST(ParseUrlTest, PortEdgeCases) {
  19135. {
  19136. detail::UrlComponents uc;
  19137. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  19138. EXPECT_TRUE(uc.port.empty());
  19139. EXPECT_EQ("/path", uc.path);
  19140. }
  19141. {
  19142. // parse_url accepts any port string; validation is done by parse_port
  19143. detail::UrlComponents uc;
  19144. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  19145. EXPECT_EQ("abc", uc.port);
  19146. }
  19147. }
  19148. TEST(ParseUrlTest, WebSocketPatterns) {
  19149. {
  19150. detail::UrlComponents uc;
  19151. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  19152. EXPECT_EQ("ws", uc.scheme);
  19153. EXPECT_EQ("echo.example.com", uc.host);
  19154. EXPECT_EQ("8080", uc.port);
  19155. EXPECT_EQ("/ws", uc.path);
  19156. }
  19157. {
  19158. detail::UrlComponents uc;
  19159. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  19160. EXPECT_EQ("wss", uc.scheme);
  19161. EXPECT_EQ("echo.example.com", uc.host);
  19162. EXPECT_TRUE(uc.port.empty());
  19163. EXPECT_EQ("/ws", uc.path);
  19164. }
  19165. }
  19166. TEST(ParseUrlTest, QueryOnly) {
  19167. detail::UrlComponents uc;
  19168. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  19169. EXPECT_TRUE(uc.host.empty());
  19170. EXPECT_TRUE(uc.path.empty());
  19171. EXPECT_EQ("?q=1&r=2", uc.query);
  19172. }
  19173. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  19174. detail::UrlComponents uc;
  19175. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  19176. EXPECT_TRUE(uc.scheme.empty());
  19177. EXPECT_EQ("example.com", uc.host);
  19178. EXPECT_EQ("443", uc.port);
  19179. EXPECT_EQ("/path", uc.path);
  19180. }
  19181. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  19182. // If ipv6 regex working, regex match codepath is taken.
  19183. // else port will default to 80 in Client impl
  19184. int clientImplMagicPort = 80;
  19185. int port = 4321;
  19186. // above ports must be different to avoid false negative
  19187. EXPECT_NE(clientImplMagicPort, port);
  19188. std::string ipV6TestURL = "http://[ff06::c3]";
  19189. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  19190. CLIENT_PRIVATE_KEY_FILE);
  19191. EXPECT_EQ(cli.port(), port);
  19192. }
  19193. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  19194. auto file_path = "./www/dir/index.html";
  19195. auto dir_path = "./www/dir";
  19196. detail::FileStat stat_file(file_path);
  19197. EXPECT_TRUE(stat_file.is_file());
  19198. EXPECT_FALSE(stat_file.is_dir());
  19199. detail::FileStat stat_dir(dir_path);
  19200. EXPECT_FALSE(stat_dir.is_file());
  19201. EXPECT_TRUE(stat_dir.is_dir());
  19202. }
  19203. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  19204. // IPv4 with default HTTP port (80)
  19205. EXPECT_EQ("example.com",
  19206. detail::make_host_and_port_string("example.com", 80, false));
  19207. // IPv4 with default HTTPS port (443)
  19208. EXPECT_EQ("example.com",
  19209. detail::make_host_and_port_string("example.com", 443, true));
  19210. // IPv4 with non-default HTTP port
  19211. EXPECT_EQ("example.com:8080",
  19212. detail::make_host_and_port_string("example.com", 8080, false));
  19213. // IPv4 with non-default HTTPS port
  19214. EXPECT_EQ("example.com:8443",
  19215. detail::make_host_and_port_string("example.com", 8443, true));
  19216. // IPv6 with default HTTP port (80)
  19217. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  19218. // IPv6 with default HTTPS port (443)
  19219. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  19220. // IPv6 with non-default HTTP port
  19221. EXPECT_EQ("[::1]:8080",
  19222. detail::make_host_and_port_string("::1", 8080, false));
  19223. // IPv6 with non-default HTTPS port
  19224. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  19225. // IPv6 full address with default port
  19226. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  19227. detail::make_host_and_port_string(
  19228. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  19229. // IPv6 full address with non-default port
  19230. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  19231. detail::make_host_and_port_string(
  19232. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  19233. // IPv6 localhost with non-default port
  19234. EXPECT_EQ("[::1]:3000",
  19235. detail::make_host_and_port_string("::1", 3000, false));
  19236. // IPv6 with zone ID (link-local address) with default port
  19237. EXPECT_EQ("[fe80::1%eth0]",
  19238. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  19239. // IPv6 with zone ID (link-local address) with non-default port
  19240. EXPECT_EQ("[fe80::1%eth0]:8080",
  19241. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  19242. // Edge case: Port 443 with is_ssl=false (should add port)
  19243. EXPECT_EQ("example.com:443",
  19244. detail::make_host_and_port_string("example.com", 443, false));
  19245. // Edge case: Port 80 with is_ssl=true (should add port)
  19246. EXPECT_EQ("example.com:80",
  19247. detail::make_host_and_port_string("example.com", 80, true));
  19248. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  19249. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  19250. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  19251. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  19252. // Security fix: Already bracketed IPv6 should not get double brackets
  19253. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  19254. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  19255. EXPECT_EQ("[::1]:8080",
  19256. detail::make_host_and_port_string("[::1]", 8080, false));
  19257. EXPECT_EQ("[2001:db8::1]:8080",
  19258. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  19259. EXPECT_EQ("[fe80::1%eth0]",
  19260. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  19261. EXPECT_EQ("[fe80::1%eth0]:8080",
  19262. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  19263. // Edge case: Empty host (should return as-is)
  19264. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  19265. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  19266. // This is a known limitation but shouldn't crash
  19267. EXPECT_EQ("[host:name]",
  19268. detail::make_host_and_port_string("host:name", 80, false));
  19269. // Port number edge cases (no validation, but should not crash)
  19270. EXPECT_EQ("example.com:0",
  19271. detail::make_host_and_port_string("example.com", 0, false));
  19272. EXPECT_EQ("example.com:-1",
  19273. detail::make_host_and_port_string("example.com", -1, false));
  19274. EXPECT_EQ("example.com:65535",
  19275. detail::make_host_and_port_string("example.com", 65535, false));
  19276. EXPECT_EQ("example.com:65536",
  19277. detail::make_host_and_port_string("example.com", 65536, false));
  19278. }
  19279. namespace httplib {
  19280. namespace detail {
  19281. std::string
  19282. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  19283. const std::string &host, int port);
  19284. } // namespace detail
  19285. } // namespace httplib
  19286. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  19287. std::map<std::string, std::string> addr_map = {
  19288. {"ipv4.example", "192.0.2.10"},
  19289. {"ipv6.example", "2001:db8::1"},
  19290. {"name.example", "internal.example.lan"},
  19291. {"empty.example", ""}};
  19292. EXPECT_EQ("192.0.2.10:443",
  19293. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  19294. EXPECT_EQ("[2001:db8::1]:443",
  19295. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  19296. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  19297. addr_map, "name.example", 8443));
  19298. // An empty or absent mapping keeps the hostname as the target
  19299. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  19300. addr_map, "empty.example", 443));
  19301. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  19302. addr_map, "other.example", 443));
  19303. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  19304. }
  19305. #ifdef CPPHTTPLIB_SSL_ENABLED
  19306. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  19307. httplib::SSLClient cli("roblox.com", 443);
  19308. cli.set_follow_location(true);
  19309. auto res = cli.Get("/");
  19310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19311. EXPECT_EQ(StatusCode::OK_200, res->status);
  19312. }
  19313. #endif
  19314. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  19315. Server svr;
  19316. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19317. EXPECT_EQ(res.status, 400);
  19318. });
  19319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19320. auto se = detail::scope_exit([&] {
  19321. svr.stop();
  19322. thread.join();
  19323. ASSERT_FALSE(svr.is_running());
  19324. });
  19325. svr.wait_until_ready();
  19326. Client cli(HOST, PORT);
  19327. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  19328. }
  19329. TEST(InvalidHeaderCharsTest, is_field_name) {
  19330. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  19331. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  19332. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  19333. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  19334. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  19335. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  19336. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  19337. EXPECT_FALSE(detail::fields::is_field_name(""));
  19338. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  19339. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  19340. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  19341. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  19342. }
  19343. TEST(InvalidHeaderCharsTest, is_field_value) {
  19344. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  19345. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  19346. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  19347. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  19348. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  19349. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  19350. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  19351. EXPECT_TRUE(detail::fields::is_field_value(""));
  19352. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  19353. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  19354. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  19355. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  19356. EXPECT_TRUE(detail::fields::is_field_value("0"));
  19357. }
  19358. TEST(InvalidHeaderCharsTest, OnServer) {
  19359. Server svr;
  19360. svr.Get("/test_name", [&](const Request &req, Response &res) {
  19361. std::string header = "Not Set";
  19362. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19363. res.set_header(header, "value");
  19364. res.set_content("Page Content Page Content", "text/plain");
  19365. });
  19366. svr.Get("/test_value", [&](const Request &req, Response &res) {
  19367. std::string header = "Not Set";
  19368. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19369. res.set_header("X-Test", header);
  19370. res.set_content("Page Content Page Content", "text/plain");
  19371. });
  19372. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19373. auto se = detail::scope_exit([&] {
  19374. svr.stop();
  19375. thread.join();
  19376. ASSERT_FALSE(svr.is_running());
  19377. });
  19378. svr.wait_until_ready();
  19379. Client cli(HOST, PORT);
  19380. {
  19381. auto res = cli.Get(
  19382. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19384. EXPECT_EQ("Page Content Page Content", res->body);
  19385. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19386. }
  19387. {
  19388. auto res = cli.Get(
  19389. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19391. EXPECT_EQ("Page Content Page Content", res->body);
  19392. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19393. }
  19394. }
  19395. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  19396. auto handled = false;
  19397. Server svr;
  19398. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19399. thread t = thread([&] { svr.listen(HOST, PORT); });
  19400. auto se = detail::scope_exit([&] {
  19401. svr.stop();
  19402. t.join();
  19403. ASSERT_FALSE(svr.is_running());
  19404. ASSERT_FALSE(handled);
  19405. });
  19406. svr.wait_until_ready();
  19407. auto req = "POST /test HTTP/1.1\r\n"
  19408. "Content-Length: x\r\n"
  19409. "\r\n";
  19410. std::string response;
  19411. ASSERT_TRUE(send_request(1, req, &response));
  19412. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19413. response.substr(0, response.find("\r\n")));
  19414. }
  19415. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  19416. // case-insensitive, and a server that receives a 100-continue expectation in
  19417. // an HTTP/1.0 request MUST ignore it.
  19418. static void probe_expect(int port, const std::string &req, bool *got_100) {
  19419. std::string response;
  19420. ASSERT_TRUE(send_request(1, req, &response, port));
  19421. *got_100 = response.find("100 Continue") != std::string::npos;
  19422. }
  19423. class ExpectTokenTest : public ::testing::Test {
  19424. protected:
  19425. void SetUp() override {
  19426. svr_.Post("/p", [](const Request &, Response &res) {
  19427. res.set_content("ok", "text/plain");
  19428. });
  19429. port_ = svr_.bind_to_any_port(HOST);
  19430. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19431. svr_.wait_until_ready();
  19432. }
  19433. void TearDown() override {
  19434. svr_.stop();
  19435. if (thread_.joinable()) { thread_.join(); }
  19436. }
  19437. std::string request(const char *version, const char *expect_value) const {
  19438. return std::string("POST /p ") + version +
  19439. "\r\n"
  19440. "Host: localhost\r\n"
  19441. "Content-Length: 2\r\n"
  19442. "Connection: close\r\n"
  19443. "Expect: " +
  19444. expect_value +
  19445. "\r\n"
  19446. "\r\n"
  19447. "hi";
  19448. }
  19449. Server svr_;
  19450. int port_ = 0;
  19451. thread thread_;
  19452. };
  19453. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  19454. bool got_100 = false;
  19455. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  19456. EXPECT_TRUE(got_100);
  19457. }
  19458. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  19459. bool got_100 = true;
  19460. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  19461. EXPECT_FALSE(got_100);
  19462. }
  19463. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  19464. bool got_100 = false;
  19465. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  19466. EXPECT_TRUE(got_100);
  19467. }
  19468. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  19469. bool got_100 = false;
  19470. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  19471. EXPECT_TRUE(got_100);
  19472. }
  19473. // `100 Continue` is sent only when the server starts reading the body, so a
  19474. // request rejected before that never invites the client to send it. The
  19475. // requests below carry the expectation but withhold the body, as a client
  19476. // waiting for `100 Continue` would.
  19477. // A POST that expects `100 Continue` and withholds its two-byte body.
  19478. static std::string expect_headers_only(const std::string &path) {
  19479. return "POST " + path +
  19480. " HTTP/1.1\r\n"
  19481. "Host: localhost\r\n"
  19482. "Content-Length: 2\r\n"
  19483. "Expect: 100-continue\r\n"
  19484. "\r\n";
  19485. }
  19486. class ExpectLazyContinueTest : public ::testing::Test {
  19487. protected:
  19488. void SetUp() override {
  19489. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19490. if (req.path == "/pre-routing") {
  19491. res.status = StatusCode::Unauthorized_401;
  19492. return Server::HandlerResponse::Handled;
  19493. }
  19494. return Server::HandlerResponse::Unhandled;
  19495. });
  19496. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19497. if (req.matched_route == "/pre-request") {
  19498. res.status = StatusCode::Forbidden_403;
  19499. return Server::HandlerResponse::Handled;
  19500. }
  19501. return Server::HandlerResponse::Unhandled;
  19502. });
  19503. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19504. res.set_content("ok", "text/plain");
  19505. });
  19506. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19507. res.set_content("ok", "text/plain");
  19508. });
  19509. svr_.Post("/reader-used", [](const Request &, Response &res,
  19510. const ContentReader &content_reader) {
  19511. std::string body;
  19512. content_reader([&](const char *data, size_t len) {
  19513. body.append(data, len);
  19514. return true;
  19515. });
  19516. res.set_content(body, "text/plain");
  19517. });
  19518. svr_.Post("/reader-unused",
  19519. [](const Request &, Response &res, const ContentReader &) {
  19520. res.set_content("ignored", "text/plain");
  19521. });
  19522. port_ = svr_.bind_to_any_port(HOST);
  19523. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19524. svr_.wait_until_ready();
  19525. }
  19526. void TearDown() override {
  19527. svr_.stop();
  19528. if (thread_.joinable()) { thread_.join(); }
  19529. }
  19530. // Sends `req` and reads until the server closes the connection. Returns
  19531. // false if the read had to wait for the client-side timeout instead.
  19532. bool send_until_closed(const std::string &req, std::string *resp) const {
  19533. auto start = std::chrono::steady_clock::now();
  19534. if (!send_request(3, req, resp, port_)) { return false; }
  19535. auto elapsed = std::chrono::steady_clock::now() - start;
  19536. return elapsed < std::chrono::seconds(2);
  19537. }
  19538. // The final response comes without `100 Continue`, and the server closes
  19539. // the connection since the body may or may not follow.
  19540. void expect_final_without_interim(const std::string &path,
  19541. const char *status_line) const {
  19542. std::string resp;
  19543. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19544. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19545. EXPECT_EQ(0u, resp.find(status_line));
  19546. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19547. }
  19548. Server svr_;
  19549. int port_ = 0;
  19550. thread thread_;
  19551. };
  19552. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19553. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19554. }
  19555. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19556. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19557. }
  19558. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19559. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19560. }
  19561. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19562. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19563. }
  19564. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19565. // The body follows once `100 Continue` has had time to arrive.
  19566. auto req = expect_headers_only("/reader-used");
  19567. req.insert(req.size() - 2, "Connection: close\r\n");
  19568. std::string resp;
  19569. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19570. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19571. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19572. EXPECT_NE(std::string::npos, resp.find("hi"));
  19573. }
  19574. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19575. // Large enough for the client to add `Expect: 100-continue` itself.
  19576. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19577. std::atomic<bool> body_sent{false};
  19578. Client cli(HOST, port_);
  19579. auto res = cli.Post(
  19580. "/pre-request", length,
  19581. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19582. body_sent = true;
  19583. std::string chunk(len, 'x');
  19584. sink.write(chunk.data(), chunk.size());
  19585. return true;
  19586. },
  19587. "application/octet-stream");
  19588. ASSERT_TRUE(res);
  19589. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19590. EXPECT_FALSE(body_sent);
  19591. }
  19592. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19593. Server svr;
  19594. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19595. return StatusCode::ExpectationFailed_417;
  19596. });
  19597. svr.Post("/p", [](const Request &, Response &res) {
  19598. res.set_content("ok", "text/plain");
  19599. });
  19600. auto port = svr.bind_to_any_port(HOST);
  19601. thread t = thread([&] { svr.listen_after_bind(); });
  19602. auto se = detail::scope_exit([&] {
  19603. svr.stop();
  19604. t.join();
  19605. });
  19606. svr.wait_until_ready();
  19607. std::string resp;
  19608. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19609. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19610. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19611. // Exactly one response: the route handler must not run after the 417.
  19612. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19613. }
  19614. #ifndef _WIN32
  19615. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19616. static constexpr char reject[] = "Unauthorized";
  19617. static constexpr char accept[] = "Upload accepted";
  19618. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19619. Server svr;
  19620. svr.set_expect_100_continue_handler(
  19621. [](const Request & /*req*/, Response &res) {
  19622. res.status = StatusCode::Unauthorized_401;
  19623. res.set_content(reject, "text/plain");
  19624. return res.status;
  19625. });
  19626. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19627. res.set_content(accept, "text/plain");
  19628. });
  19629. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19630. auto se = detail::scope_exit([&] {
  19631. svr.stop();
  19632. thread.join();
  19633. ASSERT_FALSE(svr.is_running());
  19634. });
  19635. svr.wait_until_ready();
  19636. {
  19637. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19638. curl_easy_init(), &curl_easy_cleanup};
  19639. ASSERT_NE(curl, nullptr);
  19640. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19641. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19642. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19643. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19644. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19645. &curl_slist_free_all};
  19646. ASSERT_NE(list, nullptr);
  19647. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19648. struct read_data {
  19649. uint64_t read_size;
  19650. uint64_t total_size;
  19651. } data = {0, total_size};
  19652. using read_callback_t =
  19653. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19654. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19655. void *userdata) -> size_t {
  19656. read_data *d = (read_data *)userdata;
  19657. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19658. std::fill_n(ptr, size * nmemb, 'A');
  19659. d->read_size += size * nmemb;
  19660. return size * nmemb;
  19661. };
  19662. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19663. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19664. std::vector<char> buffer;
  19665. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19666. using write_callback_t =
  19667. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19668. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19669. void *userdata) -> size_t {
  19670. std::vector<char> *buf = (std::vector<char> *)userdata;
  19671. buf->reserve(buf->size() + size * nmemb + 1);
  19672. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19673. return size * nmemb;
  19674. };
  19675. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19676. {
  19677. const auto res = curl_easy_perform(curl.get());
  19678. ASSERT_EQ(res, CURLE_OK);
  19679. }
  19680. {
  19681. auto response_code = long{};
  19682. const auto res =
  19683. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19684. ASSERT_EQ(res, CURLE_OK);
  19685. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19686. }
  19687. {
  19688. auto dl = curl_off_t{};
  19689. const auto res =
  19690. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19691. ASSERT_EQ(res, CURLE_OK);
  19692. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19693. }
  19694. {
  19695. buffer.push_back('\0');
  19696. ASSERT_STRCASEEQ(buffer.data(), reject);
  19697. }
  19698. }
  19699. }
  19700. #endif
  19701. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19702. // Regression test for #2458.
  19703. //
  19704. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19705. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19706. // ticket can make the client socket spuriously readable during the
  19707. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19708. // the client withholds the body and then blocks reading a response that never
  19709. // comes, failing with `Failed to read connection`.
  19710. //
  19711. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19712. // within the timeout. This raw OpenSSL server deliberately never sends
  19713. // `100 Continue`; the client must still deliver the body and receive 200.
  19714. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19715. signal(SIGPIPE, SIG_IGN);
  19716. const auto port = PORT + 4;
  19717. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19718. ASSERT_NE(srv, INVALID_SOCKET);
  19719. int opt = 1;
  19720. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19721. sockaddr_in addr{};
  19722. addr.sin_family = AF_INET;
  19723. addr.sin_port = htons(static_cast<uint16_t>(port));
  19724. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19725. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19726. ASSERT_EQ(0, ::listen(srv, 1));
  19727. std::atomic<size_t> server_body_bytes{0};
  19728. auto server_thread = std::thread([&] {
  19729. sockaddr_in cli_addr{};
  19730. socklen_t cli_len = sizeof(cli_addr);
  19731. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19732. if (cli == INVALID_SOCKET) { return; }
  19733. // Bound the lifetime of the server side so a buggy client (which never
  19734. // sends the body) cannot make this thread block forever on join.
  19735. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19736. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19737. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19738. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19739. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19740. SSL *ssl = SSL_new(ctx);
  19741. SSL_set_fd(ssl, static_cast<int>(cli));
  19742. if (SSL_accept(ssl) > 0) {
  19743. // Read the request headers. Reading here also flushes the TLS 1.3
  19744. // session tickets to the client. Deliberately do NOT send
  19745. // `100 Continue`.
  19746. std::string buf;
  19747. char tmp[1024];
  19748. while (buf.find("\r\n\r\n") == std::string::npos) {
  19749. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19750. if (n <= 0) { break; }
  19751. buf.append(tmp, static_cast<size_t>(n));
  19752. }
  19753. // A correct client sends the body now; count what arrives.
  19754. auto pos = buf.find("\r\n\r\n");
  19755. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19756. while (body < 4096) {
  19757. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19758. if (n <= 0) { break; }
  19759. body += static_cast<size_t>(n);
  19760. }
  19761. server_body_bytes = body;
  19762. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19763. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19764. SSL_shutdown(ssl);
  19765. }
  19766. SSL_free(ssl);
  19767. detail::close_socket(cli);
  19768. SSL_CTX_free(ctx);
  19769. });
  19770. auto se = detail::scope_exit([&] {
  19771. server_thread.join();
  19772. detail::close_socket(srv);
  19773. });
  19774. SSLClient cli("127.0.0.1", port);
  19775. cli.enable_server_certificate_verification(false);
  19776. cli.set_connection_timeout(5, 0);
  19777. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19778. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19779. std::string body(4096, 'A');
  19780. auto res = cli.Put("/api/test", body, "application/json");
  19781. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19782. EXPECT_EQ(StatusCode::OK_200, res->status);
  19783. EXPECT_EQ(body.size(), server_body_bytes.load());
  19784. }
  19785. #endif
  19786. template <typename S, typename C>
  19787. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19788. svr.Get("/stream", [&](const Request &, Response &res) {
  19789. auto data = new std::string("01234567890123456789");
  19790. res.set_content_provider(
  19791. data->size(), "text/plain",
  19792. [&, data](size_t offset, size_t length, DataSink &sink) {
  19793. const size_t DATA_CHUNK_SIZE = 4;
  19794. const auto &d = *data;
  19795. std::this_thread::sleep_for(std::chrono::seconds(1));
  19796. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19797. return true;
  19798. },
  19799. [data](bool success) {
  19800. EXPECT_FALSE(success);
  19801. delete data;
  19802. });
  19803. });
  19804. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19805. auto i = new size_t(0);
  19806. res.set_content_provider(
  19807. "text/plain",
  19808. [i](size_t, DataSink &sink) {
  19809. if (*i < 5) {
  19810. std::this_thread::sleep_for(std::chrono::seconds(1));
  19811. sink.write("abcd", 4);
  19812. (*i)++;
  19813. } else {
  19814. sink.done();
  19815. }
  19816. return true;
  19817. },
  19818. [i](bool success) {
  19819. EXPECT_FALSE(success);
  19820. delete i;
  19821. });
  19822. });
  19823. svr.Get("/chunked", [&](const Request &, Response &res) {
  19824. auto i = new size_t(0);
  19825. res.set_chunked_content_provider(
  19826. "text/plain",
  19827. [i](size_t, DataSink &sink) {
  19828. if (*i < 5) {
  19829. std::this_thread::sleep_for(std::chrono::seconds(1));
  19830. sink.os << "abcd";
  19831. (*i)++;
  19832. } else {
  19833. sink.done();
  19834. }
  19835. return true;
  19836. },
  19837. [i](bool success) {
  19838. EXPECT_FALSE(success);
  19839. delete i;
  19840. });
  19841. });
  19842. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19843. auto se = detail::scope_exit([&] {
  19844. svr.stop();
  19845. listen_thread.join();
  19846. ASSERT_FALSE(svr.is_running());
  19847. });
  19848. svr.wait_until_ready();
  19849. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19850. {
  19851. auto start = std::chrono::steady_clock::now();
  19852. auto res = cli.Get("/stream");
  19853. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19854. std::chrono::steady_clock::now() - start)
  19855. .count();
  19856. ASSERT_FALSE(res);
  19857. EXPECT_EQ(Error::Read, res.error());
  19858. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19859. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19860. }
  19861. {
  19862. auto start = std::chrono::steady_clock::now();
  19863. auto res = cli.Get("/stream_without_length");
  19864. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19865. std::chrono::steady_clock::now() - start)
  19866. .count();
  19867. ASSERT_FALSE(res);
  19868. EXPECT_EQ(Error::Read, res.error());
  19869. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19870. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19871. }
  19872. {
  19873. auto start = std::chrono::steady_clock::now();
  19874. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19875. EXPECT_EQ("abcd", string(data, data_length));
  19876. return true;
  19877. });
  19878. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19879. std::chrono::steady_clock::now() - start)
  19880. .count();
  19881. ASSERT_FALSE(res);
  19882. EXPECT_EQ(Error::Read, res.error());
  19883. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19884. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19885. }
  19886. }
  19887. TEST(MaxTimeoutTest, ContentStream) {
  19888. time_t timeout = 2000;
  19889. time_t threshold = 200;
  19890. Server svr;
  19891. Client cli("localhost", PORT);
  19892. max_timeout_test(svr, cli, timeout, threshold);
  19893. }
  19894. #ifdef CPPHTTPLIB_SSL_ENABLED
  19895. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19896. time_t timeout = 2000;
  19897. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19899. SSLClient cli("localhost", PORT);
  19900. cli.enable_server_certificate_verification(false);
  19901. max_timeout_test(svr, cli, timeout, threshold);
  19902. }
  19903. #endif
  19904. class EventDispatcher {
  19905. public:
  19906. EventDispatcher() {}
  19907. bool wait_event(DataSink *sink) {
  19908. unique_lock<mutex> lk(m_);
  19909. int id = id_;
  19910. // Wait with timeout to prevent hanging if client disconnects
  19911. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19912. [&] { return cid_ == id; })) {
  19913. return false; // Timeout occurred
  19914. }
  19915. sink->write(message_.data(), message_.size());
  19916. return true;
  19917. }
  19918. void send_event(const string &message) {
  19919. lock_guard<mutex> lk(m_);
  19920. cid_ = id_++;
  19921. message_ = message;
  19922. cv_.notify_all();
  19923. }
  19924. private:
  19925. mutex m_;
  19926. condition_variable cv_;
  19927. atomic_int id_{0};
  19928. atomic_int cid_{-1};
  19929. string message_;
  19930. };
  19931. TEST(ClientInThreadTest, Issue2068) {
  19932. EventDispatcher ed;
  19933. Server svr;
  19934. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19935. res.set_chunked_content_provider("text/event-stream",
  19936. [&](size_t /*offset*/, DataSink &sink) {
  19937. return ed.wait_event(&sink);
  19938. });
  19939. });
  19940. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19941. svr.wait_until_ready();
  19942. thread event_thread([&] {
  19943. int id = 0;
  19944. while (svr.is_running()) {
  19945. this_thread::sleep_for(chrono::milliseconds(500));
  19946. std::stringstream ss;
  19947. ss << "data: " << id << "\n\n";
  19948. ed.send_event(ss.str());
  19949. id++;
  19950. }
  19951. });
  19952. auto se = detail::scope_exit([&] {
  19953. svr.stop();
  19954. listen_thread.join();
  19955. event_thread.join();
  19956. ASSERT_FALSE(svr.is_running());
  19957. });
  19958. {
  19959. auto client = detail::make_unique<Client>(HOST, PORT);
  19960. client->set_read_timeout(std::chrono::minutes(10));
  19961. std::atomic<bool> stop{false};
  19962. std::thread t([&] {
  19963. client->Get("/event1",
  19964. [&](const char *, size_t) -> bool { return !stop; });
  19965. });
  19966. std::this_thread::sleep_for(std::chrono::seconds(2));
  19967. stop = true;
  19968. client->stop();
  19969. t.join();
  19970. // Reset client after thread has finished
  19971. client.reset();
  19972. }
  19973. }
  19974. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19975. auto handled = false;
  19976. Server svr;
  19977. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19978. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19979. auto se = detail::scope_exit([&] {
  19980. svr.stop();
  19981. t.join();
  19982. ASSERT_FALSE(svr.is_running());
  19983. ASSERT_FALSE(handled);
  19984. });
  19985. svr.wait_until_ready();
  19986. // Two Content-Length headers with different values — must be rejected
  19987. auto req = "POST /test HTTP/1.1\r\n"
  19988. "Content-Length: 5\r\n"
  19989. "Content-Length: 10\r\n"
  19990. "\r\n"
  19991. "hello";
  19992. std::string response;
  19993. ASSERT_TRUE(send_request(1, req, &response));
  19994. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19995. response.substr(0, response.find("\r\n")));
  19996. }
  19997. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19998. auto handled = false;
  19999. Server svr;
  20000. svr.Post("/test", [&](const Request &, Response &res) {
  20001. handled = true;
  20002. res.set_content("ok", "text/plain");
  20003. });
  20004. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20005. auto se = detail::scope_exit([&] {
  20006. svr.stop();
  20007. t.join();
  20008. ASSERT_FALSE(svr.is_running());
  20009. ASSERT_TRUE(handled);
  20010. });
  20011. svr.wait_until_ready();
  20012. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  20013. auto req = "POST /test HTTP/1.1\r\n"
  20014. "Host: localhost\r\n"
  20015. "Content-Length: 5\r\n"
  20016. "Content-Length: 5\r\n"
  20017. "\r\n"
  20018. "hello";
  20019. std::string response;
  20020. ASSERT_TRUE(send_request(1, req, &response));
  20021. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  20022. }
  20023. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  20024. Server svr;
  20025. svr.Get("/test", [](const Request &, Response &res) {
  20026. res.set_content("ok", "text/plain");
  20027. });
  20028. auto port = svr.bind_to_any_port(HOST);
  20029. thread t = thread([&] { svr.listen_after_bind(); });
  20030. auto se = detail::scope_exit([&] {
  20031. svr.stop();
  20032. t.join();
  20033. ASSERT_FALSE(svr.is_running());
  20034. });
  20035. svr.wait_until_ready();
  20036. auto status_line = [&](const std::string &host_lines) {
  20037. std::string res;
  20038. send_request(
  20039. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  20040. &res, port);
  20041. return res.substr(0, res.find("\r\n"));
  20042. };
  20043. const char *accepted[] = {
  20044. "Host: localhost\r\n",
  20045. "Host: a.example:8080\r\n",
  20046. "Host: my_service\r\n",
  20047. "Host: [::1]:8080\r\n",
  20048. "Host: [fe80::1%25eth0]\r\n",
  20049. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  20050. };
  20051. for (auto host_lines : accepted) {
  20052. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  20053. }
  20054. const char *rejected[] = {
  20055. "Host: a.example\r\nHost: b.example\r\n",
  20056. "Host: a.example\r\nHost: a.example\r\n",
  20057. "Host: a@b.example\r\n",
  20058. "Host: a.example/b\r\n",
  20059. "Host: a.example\\b\r\n",
  20060. "Host: a.example?b\r\n",
  20061. "Host: a.example#b\r\n",
  20062. "Host: a.example b.example\r\n",
  20063. };
  20064. for (auto host_lines : rejected) {
  20065. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  20066. << host_lines;
  20067. }
  20068. }
  20069. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  20070. Server svr;
  20071. svr.Get("/", [](const Request &req, Response &res) {
  20072. EXPECT_EQ(2U, req.trailers.size());
  20073. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  20074. // Denied
  20075. EXPECT_FALSE(req.has_trailer("Content-Length"));
  20076. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  20077. // Accepted
  20078. EXPECT_TRUE(req.has_trailer("X-Hello"));
  20079. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  20080. EXPECT_TRUE(req.has_trailer("X-World"));
  20081. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  20082. res.set_content("ok", "text/plain");
  20083. });
  20084. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20085. auto se = detail::scope_exit([&] {
  20086. svr.stop();
  20087. t.join();
  20088. ASSERT_FALSE(svr.is_running());
  20089. });
  20090. svr.wait_until_ready();
  20091. const std::string req = "GET / HTTP/1.1\r\n"
  20092. "Transfer-Encoding: chunked\r\n"
  20093. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  20094. "\r\n"
  20095. "0\r\n"
  20096. "Content-Length: 10\r\n"
  20097. "Host: internal.local\r\n"
  20098. "Content-Type: malicious/content\r\n"
  20099. "Cookie: any\r\n"
  20100. "Set-Cookie: any\r\n"
  20101. "X-Forwarded-For: attacker.com\r\n"
  20102. "X-Real-Ip: 1.1.1.1\r\n"
  20103. "X-Hello: hello\r\n"
  20104. "X-World: world\r\n"
  20105. "\r\n";
  20106. std::string res;
  20107. ASSERT_TRUE(send_request(1, req, &res));
  20108. }
  20109. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  20110. // several field lines, and the combined value is what has to be parsed. A
  20111. // Trailer field split across lines therefore declares every name it lists;
  20112. // reading only the first line silently drops the trailers the later lines
  20113. // declare. The prohibited-trailer filter still applies to every line.
  20114. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  20115. Server svr;
  20116. size_t observed_trailer_count = 0;
  20117. std::string observed_hello;
  20118. std::string observed_world;
  20119. bool observed_content_length = true;
  20120. svr.Get("/", [&](const Request &req, Response &res) {
  20121. observed_trailer_count = req.trailers.size();
  20122. observed_hello = req.get_trailer_value("X-Hello");
  20123. observed_world = req.get_trailer_value("X-World");
  20124. observed_content_length = req.has_trailer("Content-Length");
  20125. res.set_content("ok", "text/plain");
  20126. });
  20127. auto port = svr.bind_to_any_port(HOST);
  20128. thread t = thread([&]() { svr.listen_after_bind(); });
  20129. auto se = detail::scope_exit([&] {
  20130. svr.stop();
  20131. t.join();
  20132. ASSERT_FALSE(svr.is_running());
  20133. });
  20134. svr.wait_until_ready();
  20135. const std::string req = "GET / HTTP/1.1\r\n"
  20136. "Host: localhost\r\n"
  20137. "Transfer-Encoding: chunked\r\n"
  20138. "Trailer: X-Hello\r\n"
  20139. "Trailer: X-World, Content-Length\r\n"
  20140. "\r\n"
  20141. "0\r\n"
  20142. "X-Hello: hello\r\n"
  20143. "X-World: world\r\n"
  20144. "Content-Length: 10\r\n"
  20145. "\r\n";
  20146. std::string res;
  20147. ASSERT_TRUE(send_request(1, req, &res, port));
  20148. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  20149. // Accepted: both field lines contribute to the declared set
  20150. EXPECT_EQ(2U, observed_trailer_count);
  20151. EXPECT_EQ(observed_hello, "hello");
  20152. EXPECT_EQ(observed_world, "world");
  20153. // Denied: a prohibited name stays prohibited on a later field line
  20154. EXPECT_FALSE(observed_content_length);
  20155. }
  20156. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  20157. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  20158. // unbounded run of fields that are never declared, because the counter would
  20159. // only advance for declared fields.
  20160. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  20161. Server svr;
  20162. bool handler_called = false;
  20163. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  20164. handler_called = true;
  20165. res.set_content("ok", "text/plain");
  20166. });
  20167. auto port = svr.bind_to_any_port(HOST);
  20168. thread t = thread([&]() { svr.listen_after_bind(); });
  20169. auto se = detail::scope_exit([&] {
  20170. svr.stop();
  20171. t.join();
  20172. ASSERT_FALSE(svr.is_running());
  20173. });
  20174. svr.wait_until_ready();
  20175. // Declare nothing, then send far more undeclared trailer fields than the
  20176. // header-count limit. Parsing must stop and reject the request rather than
  20177. // read every line.
  20178. std::string req = "GET / HTTP/1.1\r\n"
  20179. "Transfer-Encoding: chunked\r\n"
  20180. "\r\n"
  20181. "0\r\n";
  20182. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  20183. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  20184. }
  20185. req += "\r\n";
  20186. std::string res;
  20187. ASSERT_TRUE(send_request(1, req, &res, port));
  20188. // The request is rejected before the handler runs.
  20189. EXPECT_FALSE(handler_called);
  20190. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  20191. }
  20192. // The set of declared trailer names is capped so a peer cannot grow it without
  20193. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  20194. // declared past the cap is not honored, even if the field is actually sent.
  20195. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  20196. Server svr;
  20197. // One name inside the cap and one past it, so the test tracks the cap rather
  20198. // than a fixed count.
  20199. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  20200. const std::string within_cap_name = "X-T-0";
  20201. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  20202. bool observed_within_cap = false;
  20203. bool observed_past_cap = false;
  20204. svr.Get("/", [&](const Request &req, Response &res) {
  20205. observed_within_cap = req.has_trailer(within_cap_name);
  20206. observed_past_cap = req.has_trailer(past_cap_name);
  20207. res.set_content("ok", "text/plain");
  20208. });
  20209. auto port = svr.bind_to_any_port(HOST);
  20210. thread t = thread([&]() { svr.listen_after_bind(); });
  20211. auto se = detail::scope_exit([&] {
  20212. svr.stop();
  20213. t.join();
  20214. ASSERT_FALSE(svr.is_running());
  20215. });
  20216. svr.wait_until_ready();
  20217. // Declare more trailer names than the cap in a single Trailer field, then
  20218. // actually send the first (within the cap) and the last (past it).
  20219. std::string trailer_decl = "Trailer: ";
  20220. for (int i = 0; i < declared_count; i++) {
  20221. if (i != 0) { trailer_decl += ", "; }
  20222. trailer_decl += "X-T-" + std::to_string(i);
  20223. }
  20224. trailer_decl += "\r\n";
  20225. const std::string req = "GET / HTTP/1.1\r\n"
  20226. "Host: localhost\r\n"
  20227. "Transfer-Encoding: chunked\r\n" +
  20228. trailer_decl +
  20229. "\r\n"
  20230. "0\r\n" +
  20231. within_cap_name + ": a\r\n" + past_cap_name +
  20232. ": b\r\n"
  20233. "\r\n";
  20234. std::string res;
  20235. ASSERT_TRUE(send_request(1, req, &res, port));
  20236. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  20237. // A name within the cap is honored; one declared past the cap is dropped.
  20238. EXPECT_TRUE(observed_within_cap);
  20239. EXPECT_FALSE(observed_past_cap);
  20240. }
  20241. // A direct client that is not listed in trusted_proxies must not be able to
  20242. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  20243. // the peer address on the actual TCP connection determines whether the
  20244. // header is honored.
  20245. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  20246. Server svr;
  20247. // Deliberately does NOT include the loopback address the test client
  20248. // actually connects from, so the direct connection is not a trusted proxy.
  20249. svr.set_trusted_proxies({"203.0.113.66"});
  20250. std::string observed_remote_addr;
  20251. svr.Get("/ip", [&](const Request &req, Response &res) {
  20252. observed_remote_addr = req.remote_addr;
  20253. res.set_content("ok", "text/plain");
  20254. });
  20255. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20256. auto se = detail::scope_exit([&] {
  20257. svr.stop();
  20258. t.join();
  20259. ASSERT_FALSE(svr.is_running());
  20260. });
  20261. svr.wait_until_ready();
  20262. Client cli(HOST, PORT);
  20263. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  20264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20265. EXPECT_EQ(StatusCode::OK_200, res->status);
  20266. // The connecting peer is not a trusted proxy, so the spoofed header must be
  20267. // ignored entirely and the real connection-level address retained.
  20268. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20269. observed_remote_addr == "127.0.0.1");
  20270. }
  20271. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  20272. Server svr;
  20273. std::string observed_remote_addr;
  20274. std::string observed_xff;
  20275. svr.Get("/ip", [&](const Request &req, Response &res) {
  20276. observed_remote_addr = req.remote_addr;
  20277. observed_xff = req.get_header_value("X-Forwarded-For");
  20278. res.set_content("ok", "text/plain");
  20279. });
  20280. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20281. auto se = detail::scope_exit([&] {
  20282. svr.stop();
  20283. t.join();
  20284. ASSERT_FALSE(svr.is_running());
  20285. });
  20286. svr.wait_until_ready();
  20287. Client cli(HOST, PORT);
  20288. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  20289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20290. EXPECT_EQ(StatusCode::OK_200, res->status);
  20291. EXPECT_EQ(observed_xff, "203.0.113.66");
  20292. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20293. observed_remote_addr == "127.0.0.1");
  20294. }
  20295. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  20296. Server svr;
  20297. svr.set_trusted_proxies({"203.0.113.66"});
  20298. std::string observed_remote_addr;
  20299. std::string observed_xff;
  20300. svr.Get("/ip", [&](const Request &req, Response &res) {
  20301. observed_remote_addr = req.remote_addr;
  20302. observed_xff = req.get_header_value("X-Forwarded-For");
  20303. res.set_content("ok", "text/plain");
  20304. });
  20305. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20306. auto se = detail::scope_exit([&] {
  20307. svr.stop();
  20308. t.join();
  20309. ASSERT_FALSE(svr.is_running());
  20310. });
  20311. svr.wait_until_ready();
  20312. Client cli(HOST, PORT);
  20313. auto res = cli.Get("/ip");
  20314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20315. EXPECT_EQ(StatusCode::OK_200, res->status);
  20316. EXPECT_EQ(observed_xff, "");
  20317. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20318. observed_remote_addr == "127.0.0.1");
  20319. }
  20320. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  20321. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  20322. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  20323. Server svr;
  20324. svr.set_trusted_proxies({"127.0.0.1"});
  20325. svr.Get("/ip", [](const Request &req, Response &res) {
  20326. res.set_content(req.remote_addr, "text/plain");
  20327. });
  20328. auto port = svr.bind_to_any_port("::");
  20329. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  20330. thread t = thread([&] { svr.listen_after_bind(); });
  20331. auto se = detail::scope_exit([&] {
  20332. svr.stop();
  20333. t.join();
  20334. ASSERT_FALSE(svr.is_running());
  20335. });
  20336. svr.wait_until_ready();
  20337. Client cli("127.0.0.1", port);
  20338. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  20339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20340. EXPECT_EQ("198.51.100.23", res->body);
  20341. }
  20342. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  20343. Server svr;
  20344. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20345. svr.Get("/ip", [](const Request &req, Response &res) {
  20346. res.set_content(req.remote_addr, "text/plain");
  20347. });
  20348. auto port = svr.bind_to_any_port(HOST);
  20349. ASSERT_GT(port, 0);
  20350. thread t = thread([&] { svr.listen_after_bind(); });
  20351. auto se = detail::scope_exit([&] {
  20352. svr.stop();
  20353. t.join();
  20354. ASSERT_FALSE(svr.is_running());
  20355. });
  20356. svr.wait_until_ready();
  20357. Client cli(HOST, port);
  20358. auto res = cli.Get(
  20359. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  20360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20361. EXPECT_EQ("198.51.100.23", res->body);
  20362. }
  20363. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  20364. Server svr;
  20365. // Include the loopback address the test client actually connects from, so
  20366. // the direct connection itself is recognized as the trusted proxy hop.
  20367. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  20368. std::string observed_remote_addr;
  20369. std::string observed_xff;
  20370. svr.Get("/ip", [&](const Request &req, Response &res) {
  20371. observed_remote_addr = req.remote_addr;
  20372. observed_xff = req.get_header_value("X-Forwarded-For");
  20373. res.set_content("ok", "text/plain");
  20374. });
  20375. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20376. auto se = detail::scope_exit([&] {
  20377. svr.stop();
  20378. t.join();
  20379. ASSERT_FALSE(svr.is_running());
  20380. });
  20381. svr.wait_until_ready();
  20382. Client cli(HOST, PORT);
  20383. auto res = cli.Get(
  20384. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  20385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20386. EXPECT_EQ(StatusCode::OK_200, res->status);
  20387. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  20388. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20389. }
  20390. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  20391. Server svr;
  20392. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  20393. std::string observed_remote_addr;
  20394. std::string observed_xff;
  20395. svr.Get("/ip", [&](const Request &req, Response &res) {
  20396. observed_remote_addr = req.remote_addr;
  20397. observed_xff = req.get_header_value("X-Forwarded-For");
  20398. res.set_content("ok", "text/plain");
  20399. });
  20400. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20401. auto se = detail::scope_exit([&] {
  20402. svr.stop();
  20403. t.join();
  20404. ASSERT_FALSE(svr.is_running());
  20405. });
  20406. svr.wait_until_ready();
  20407. Client cli(HOST, PORT);
  20408. auto res = cli.Get(
  20409. "/ip",
  20410. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20412. EXPECT_EQ(StatusCode::OK_200, res->status);
  20413. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20414. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20415. }
  20416. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  20417. Server svr;
  20418. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20419. std::string observed_remote_addr;
  20420. std::string observed_xff;
  20421. svr.Get("/ip", [&](const Request &req, Response &res) {
  20422. observed_remote_addr = req.remote_addr;
  20423. observed_xff = req.get_header_value("X-Forwarded-For");
  20424. res.set_content("ok", "text/plain");
  20425. });
  20426. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20427. auto se = detail::scope_exit([&] {
  20428. svr.stop();
  20429. t.join();
  20430. ASSERT_FALSE(svr.is_running());
  20431. });
  20432. svr.wait_until_ready();
  20433. Client cli(HOST, PORT);
  20434. auto res = cli.Get(
  20435. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  20436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20437. EXPECT_EQ(StatusCode::OK_200, res->status);
  20438. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  20439. // by the closest hop) is used. The leftmost entry is fully client-controlled
  20440. // and must not be selected.
  20441. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  20442. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  20443. }
  20444. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  20445. Server svr;
  20446. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  20447. std::string observed_remote_addr;
  20448. svr.Get("/ip", [&](const Request &req, Response &res) {
  20449. observed_remote_addr = req.remote_addr;
  20450. res.set_content("ok", "text/plain");
  20451. });
  20452. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20453. auto se = detail::scope_exit([&] {
  20454. svr.stop();
  20455. t.join();
  20456. ASSERT_FALSE(svr.is_running());
  20457. });
  20458. svr.wait_until_ready();
  20459. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  20460. // a forged address and the trusted proxy's own address; the forged value must
  20461. // not win over the address the trusted proxy actually recorded.
  20462. Client cli(HOST, PORT);
  20463. auto res = cli.Get(
  20464. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  20465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20466. EXPECT_EQ(StatusCode::OK_200, res->status);
  20467. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  20468. }
  20469. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  20470. Server svr;
  20471. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20472. std::string observed_remote_addr;
  20473. std::string observed_xff;
  20474. svr.Get("/ip", [&](const Request &req, Response &res) {
  20475. observed_remote_addr = req.remote_addr;
  20476. observed_xff = req.get_header_value("X-Forwarded-For");
  20477. res.set_content("ok", "text/plain");
  20478. });
  20479. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20480. auto se = detail::scope_exit([&] {
  20481. svr.stop();
  20482. t.join();
  20483. ASSERT_FALSE(svr.is_running());
  20484. });
  20485. svr.wait_until_ready();
  20486. Client cli(HOST, PORT);
  20487. auto res = cli.Get(
  20488. "/ip",
  20489. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20491. EXPECT_EQ(StatusCode::OK_200, res->status);
  20492. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20493. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20494. }
  20495. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20496. Server svr;
  20497. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20498. std::string observed_remote_addr;
  20499. std::string observed_xff;
  20500. svr.Get("/ip", [&](const Request &req, Response &res) {
  20501. observed_remote_addr = req.remote_addr;
  20502. observed_xff = req.get_header_value("X-Forwarded-For");
  20503. res.set_content("ok", "text/plain");
  20504. });
  20505. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20506. auto se = detail::scope_exit([&] {
  20507. svr.stop();
  20508. t.join();
  20509. ASSERT_FALSE(svr.is_running());
  20510. });
  20511. svr.wait_until_ready();
  20512. std::string raw_req =
  20513. "GET /ip HTTP/1.1\r\n"
  20514. "Host: localhost\r\n"
  20515. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20516. "Connection: close\r\n"
  20517. "\r\n";
  20518. std::string out;
  20519. ASSERT_TRUE(send_request(5, raw_req, &out));
  20520. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20521. // Header parser trims surrounding whitespace of the header value
  20522. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20523. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20524. }
  20525. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20526. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20527. // their own X-Forwarded-For as a separate field line rather than extending the
  20528. // one the client sent, so every occurrence has to be taken into account.
  20529. // Reading only the first one hands back the address the client chose.
  20530. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20531. Server svr;
  20532. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20533. std::string observed_remote_addr;
  20534. size_t observed_xff_count = 0;
  20535. svr.Get("/ip", [&](const Request &req, Response &res) {
  20536. observed_remote_addr = req.remote_addr;
  20537. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20538. res.set_content("ok", "text/plain");
  20539. });
  20540. auto port = svr.bind_to_any_port(HOST);
  20541. thread t = thread([&]() { svr.listen_after_bind(); });
  20542. auto se = detail::scope_exit([&] {
  20543. svr.stop();
  20544. t.join();
  20545. ASSERT_FALSE(svr.is_running());
  20546. });
  20547. svr.wait_until_ready();
  20548. // The client supplies the first field line; the trusted proxy appends the
  20549. // address it observed as a second one.
  20550. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20551. "Host: localhost\r\n"
  20552. "X-Forwarded-For: 1.2.3.4\r\n"
  20553. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20554. "Connection: close\r\n"
  20555. "\r\n";
  20556. std::string out;
  20557. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20558. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20559. EXPECT_EQ(observed_xff_count, 2U);
  20560. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20561. // The same chain spread over one field line per hop derives the same client
  20562. // address, i.e. the split and the comma-joined representations agree.
  20563. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20564. "Host: localhost\r\n"
  20565. "X-Forwarded-For: 1.2.3.4\r\n"
  20566. "X-Forwarded-For: 198.51.100.23\r\n"
  20567. "X-Forwarded-For: 192.0.2.45\r\n"
  20568. "Connection: close\r\n"
  20569. "\r\n";
  20570. out.clear();
  20571. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20572. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20573. EXPECT_EQ(observed_xff_count, 3U);
  20574. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20575. }
  20576. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20577. // crash the server (it used to call front() on an empty vector inside
  20578. // get_client_ip). The connection-level remote address must be retained instead.
  20579. static void run_malformed_xff_test(const std::string &xff_value) {
  20580. Server svr;
  20581. svr.set_trusted_proxies({"192.0.2.45"});
  20582. std::string observed_remote_addr;
  20583. svr.Get("/ip", [&](const Request &req, Response &res) {
  20584. observed_remote_addr = req.remote_addr;
  20585. res.set_content("ok", "text/plain");
  20586. });
  20587. int port = 0;
  20588. thread t = thread([&]() {
  20589. port = svr.bind_to_any_port(HOST);
  20590. svr.listen_after_bind();
  20591. });
  20592. auto se = detail::scope_exit([&] {
  20593. svr.stop();
  20594. t.join();
  20595. ASSERT_FALSE(svr.is_running());
  20596. });
  20597. svr.wait_until_ready();
  20598. Client cli(HOST, port);
  20599. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20601. EXPECT_EQ(StatusCode::OK_200, res->status);
  20602. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20603. observed_remote_addr == "127.0.0.1");
  20604. }
  20605. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20606. run_malformed_xff_test("");
  20607. }
  20608. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20609. run_malformed_xff_test(",");
  20610. }
  20611. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20612. run_malformed_xff_test(", , ,");
  20613. }
  20614. // The same rule applies to Accept: a request whose acceptable types are spread
  20615. // over several field lines must be negotiated against all of them.
  20616. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20617. // case-insensitive connection options. Comparing the whole field value against
  20618. // one option misses a client that sends several of them, and misses every
  20619. // casing but the one written in the comparison.
  20620. //
  20621. // Sends req, reads the response, then reuses the same socket for a second
  20622. // request to find out whether the server kept the connection.
  20623. static void probe_connection_reuse(int port, const std::string &req,
  20624. bool *announced_close, bool *reusable) {
  20625. auto error = Error::Success;
  20626. auto sock = detail::create_client_socket(
  20627. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20628. /*connection_timeout_sec=*/5, 0,
  20629. /*read_timeout_sec=*/1, 0,
  20630. /*write_timeout_sec=*/5, 0, std::string(), error);
  20631. ASSERT_NE(sock, INVALID_SOCKET);
  20632. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20633. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20634. "Host: localhost\r\n"
  20635. "Connection: close\r\n"
  20636. "\r\n";
  20637. std::string first_response;
  20638. std::string second_response;
  20639. detail::process_client_socket(
  20640. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20641. [&](Stream &strm) {
  20642. if (strm.write(req.data(), req.size()) !=
  20643. static_cast<ssize_t>(req.size())) {
  20644. return false;
  20645. }
  20646. char buf[512];
  20647. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20648. // Headers plus the two-byte body of the handler below
  20649. while (reader.getline()) {
  20650. first_response += reader.ptr();
  20651. if (first_response.find("ok") != std::string::npos) { break; }
  20652. }
  20653. if (strm.write(second.data(), second.size()) !=
  20654. static_cast<ssize_t>(second.size())) {
  20655. return true;
  20656. }
  20657. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20658. while (reader2.getline()) {
  20659. second_response += reader2.ptr();
  20660. if (second_response.find("ok") != std::string::npos) { break; }
  20661. }
  20662. return true;
  20663. });
  20664. *announced_close =
  20665. first_response.find("Connection: close") != std::string::npos;
  20666. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20667. }
  20668. class ConnectionTokenTest : public ::testing::Test {
  20669. protected:
  20670. void SetUp() override {
  20671. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20672. res.set_content("ok", "text/plain");
  20673. });
  20674. port_ = svr_.bind_to_any_port(HOST);
  20675. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20676. svr_.wait_until_ready();
  20677. }
  20678. void TearDown() override {
  20679. svr_.stop();
  20680. if (thread_.joinable()) { thread_.join(); }
  20681. }
  20682. Server svr_;
  20683. int port_ = 0;
  20684. thread thread_;
  20685. };
  20686. // "close" alongside another option still closes the connection, and the
  20687. // response says so rather than leaving the peer to discover it.
  20688. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20689. bool announced_close = false;
  20690. bool reusable = true;
  20691. probe_connection_reuse(port_,
  20692. "GET /keepalive HTTP/1.1\r\n"
  20693. "Host: localhost\r\n"
  20694. "Connection: keep-alive, close\r\n"
  20695. "\r\n",
  20696. &announced_close, &reusable);
  20697. EXPECT_TRUE(announced_close);
  20698. EXPECT_FALSE(reusable);
  20699. }
  20700. // "close" split over two field lines is the same list, so it is honored too.
  20701. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20702. bool announced_close = false;
  20703. bool reusable = true;
  20704. probe_connection_reuse(port_,
  20705. "GET /keepalive HTTP/1.1\r\n"
  20706. "Host: localhost\r\n"
  20707. "Connection: keep-alive\r\n"
  20708. "Connection: close\r\n"
  20709. "\r\n",
  20710. &announced_close, &reusable);
  20711. EXPECT_TRUE(announced_close);
  20712. EXPECT_FALSE(reusable);
  20713. }
  20714. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20715. // keep-alive in the spelling everyone actually sends keeps its connection.
  20716. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20717. bool announced_close = false;
  20718. bool reusable = false;
  20719. probe_connection_reuse(port_,
  20720. "GET /keepalive HTTP/1.0\r\n"
  20721. "Host: localhost\r\n"
  20722. "Connection: keep-alive\r\n"
  20723. "\r\n",
  20724. &announced_close, &reusable);
  20725. EXPECT_FALSE(announced_close);
  20726. EXPECT_TRUE(reusable);
  20727. }
  20728. // A token the value merely contains is not the token itself.
  20729. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20730. bool announced_close = false;
  20731. bool reusable = false;
  20732. probe_connection_reuse(port_,
  20733. "GET /keepalive HTTP/1.1\r\n"
  20734. "Host: localhost\r\n"
  20735. "Connection: notclose\r\n"
  20736. "\r\n",
  20737. &announced_close, &reusable);
  20738. EXPECT_FALSE(announced_close);
  20739. EXPECT_TRUE(reusable);
  20740. }
  20741. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20742. Server svr;
  20743. std::vector<std::string> observed_types;
  20744. svr.Get("/", [&](const Request &req, Response &res) {
  20745. observed_types = req.accept_content_types;
  20746. res.set_content("ok", "text/plain");
  20747. });
  20748. auto port = svr.bind_to_any_port(HOST);
  20749. thread t = thread([&]() { svr.listen_after_bind(); });
  20750. auto se = detail::scope_exit([&] {
  20751. svr.stop();
  20752. t.join();
  20753. ASSERT_FALSE(svr.is_running());
  20754. });
  20755. svr.wait_until_ready();
  20756. Client cli(HOST, port);
  20757. Headers headers;
  20758. headers.emplace("Accept", "text/plain;q=0.5");
  20759. headers.emplace("Accept", "application/json");
  20760. auto res = cli.Get("/", headers);
  20761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20762. EXPECT_EQ(StatusCode::OK_200, res->status);
  20763. // Sorted by q-value, so the second field line's type comes first
  20764. ASSERT_EQ(2U, observed_types.size());
  20765. EXPECT_EQ("application/json", observed_types[0]);
  20766. EXPECT_EQ("text/plain", observed_types[1]);
  20767. }
  20768. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20769. // empty field line must not contribute a bare comma to the combined value.
  20770. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20771. Server svr;
  20772. std::vector<std::string> observed_types;
  20773. svr.Get("/", [&](const Request &req, Response &res) {
  20774. observed_types = req.accept_content_types;
  20775. res.set_content("ok", "text/plain");
  20776. });
  20777. auto port = svr.bind_to_any_port(HOST);
  20778. thread t = thread([&]() { svr.listen_after_bind(); });
  20779. auto se = detail::scope_exit([&] {
  20780. svr.stop();
  20781. t.join();
  20782. ASSERT_FALSE(svr.is_running());
  20783. });
  20784. svr.wait_until_ready();
  20785. // Empty first field line, then a real one
  20786. std::string raw_req = "GET / HTTP/1.1\r\n"
  20787. "Host: localhost\r\n"
  20788. "Accept:\r\n"
  20789. "Accept: application/json\r\n"
  20790. "Connection: close\r\n"
  20791. "\r\n";
  20792. std::string out;
  20793. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20794. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20795. ASSERT_EQ(1U, observed_types.size());
  20796. EXPECT_EQ("application/json", observed_types[0]);
  20797. }
  20798. // The skip in get_combined_header_value() is what keeps an empty field line
  20799. // from contributing a bare comma. Only a trailing empty field line exercises
  20800. // it: a leading one is already covered by the "combined is still empty" check,
  20801. // and parse_accept_header() now ignores the empty element either way, so the
  20802. // request-level test above can no longer tell the two apart.
  20803. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20804. Headers headers;
  20805. headers.emplace("Accept", "text/html");
  20806. headers.emplace("Accept", "");
  20807. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20808. headers.clear();
  20809. headers.emplace("Accept", "");
  20810. headers.emplace("Accept", "application/json");
  20811. EXPECT_EQ("application/json",
  20812. detail::get_combined_header_value(headers, "Accept"));
  20813. }
  20814. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20815. // An encoding offered on a later Accept-Encoding field line is still offered.
  20816. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20817. Server svr;
  20818. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20819. res.set_content(std::string(1024, 'x'), "text/plain");
  20820. });
  20821. auto port = svr.bind_to_any_port(HOST);
  20822. thread t = thread([&]() { svr.listen_after_bind(); });
  20823. auto se = detail::scope_exit([&] {
  20824. svr.stop();
  20825. t.join();
  20826. ASSERT_FALSE(svr.is_running());
  20827. });
  20828. svr.wait_until_ready();
  20829. Client cli(HOST, port);
  20830. cli.set_decompress(false);
  20831. Headers headers;
  20832. headers.emplace("Accept-Encoding", "identity");
  20833. headers.emplace("Accept-Encoding", "gzip");
  20834. auto res = cli.Get("/", headers);
  20835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20836. EXPECT_EQ(StatusCode::OK_200, res->status);
  20837. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20838. }
  20839. #endif
  20840. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20841. // Transfer-Encoding is not its body.
  20842. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20843. Server svr;
  20844. svr.set_payload_max_length(8);
  20845. svr.Post("/test", [](const Request &, Response &res) {
  20846. res.set_content("ok", "text/plain");
  20847. });
  20848. auto port = svr.bind_to_any_port(HOST);
  20849. ASSERT_GT(port, 0);
  20850. thread t = thread([&] { svr.listen_after_bind(); });
  20851. auto se = detail::scope_exit([&] {
  20852. svr.stop();
  20853. t.join();
  20854. ASSERT_FALSE(svr.is_running());
  20855. });
  20856. svr.wait_until_ready();
  20857. std::string resp;
  20858. ASSERT_TRUE(send_request(1,
  20859. "POST /test HTTP/1.1\r\n"
  20860. "Host: localhost\r\n"
  20861. "Connection: close\r\n"
  20862. "\r\n" +
  20863. std::string(16, 'X'),
  20864. &resp, port));
  20865. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20866. }
  20867. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20868. Server svr;
  20869. svr.Post("/post", [&](const Request &req, Response &res) {
  20870. res.set_content(req.body, "text/plain");
  20871. });
  20872. svr.Put("/put", [&](const Request &req, Response &res) {
  20873. res.set_content(req.body, "text/plain");
  20874. });
  20875. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20876. res.set_content(req.body, "text/plain");
  20877. });
  20878. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20879. res.set_content(req.body, "text/plain");
  20880. });
  20881. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20882. auto se = detail::scope_exit([&] {
  20883. svr.stop();
  20884. t.join();
  20885. ASSERT_FALSE(svr.is_running());
  20886. });
  20887. svr.wait_until_ready();
  20888. std::string resp;
  20889. // POST without Content-Length
  20890. ASSERT_TRUE(send_request(5,
  20891. "POST /post HTTP/1.1\r\n"
  20892. "Host: localhost\r\n"
  20893. "Connection: close\r\n"
  20894. "\r\n",
  20895. &resp));
  20896. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20897. // PUT without Content-Length
  20898. resp.clear();
  20899. ASSERT_TRUE(send_request(5,
  20900. "PUT /put HTTP/1.1\r\n"
  20901. "Host: localhost\r\n"
  20902. "Connection: close\r\n"
  20903. "\r\n",
  20904. &resp));
  20905. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20906. // PATCH without Content-Length
  20907. resp.clear();
  20908. ASSERT_TRUE(send_request(5,
  20909. "PATCH /patch HTTP/1.1\r\n"
  20910. "Host: localhost\r\n"
  20911. "Connection: close\r\n"
  20912. "\r\n",
  20913. &resp));
  20914. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20915. // DELETE without Content-Length
  20916. resp.clear();
  20917. ASSERT_TRUE(send_request(5,
  20918. "DELETE /delete HTTP/1.1\r\n"
  20919. "Host: localhost\r\n"
  20920. "Connection: close\r\n"
  20921. "\r\n",
  20922. &resp));
  20923. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20924. }
  20925. //==============================================================================
  20926. // open_stream() Tests
  20927. //==============================================================================
  20928. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20929. std::string result;
  20930. char buf[8192];
  20931. ssize_t n;
  20932. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20933. result.append(buf, static_cast<size_t>(n));
  20934. }
  20935. return result;
  20936. }
  20937. // Mock stream for unit tests
  20938. class MockStream : public Stream {
  20939. public:
  20940. std::string data;
  20941. size_t pos = 0;
  20942. ssize_t error_after = -1; // -1 = no error
  20943. explicit MockStream(const std::string &d, ssize_t err = -1)
  20944. : data(d), error_after(err) {}
  20945. bool is_readable() const override { return true; }
  20946. bool wait_readable() const override { return true; }
  20947. bool wait_writable() const override { return true; }
  20948. ssize_t read(char *ptr, size_t size) override {
  20949. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20950. if (pos >= data.size()) return 0;
  20951. size_t limit =
  20952. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20953. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20954. std::memcpy(ptr, data.data() + pos, to_read);
  20955. pos += to_read;
  20956. return static_cast<ssize_t>(to_read);
  20957. }
  20958. ssize_t write(const char *, size_t) override { return -1; }
  20959. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20960. ip = "127.0.0.1";
  20961. port = 0;
  20962. }
  20963. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20964. ip = "127.0.0.1";
  20965. port = 0;
  20966. }
  20967. socket_t socket() const override { return INVALID_SOCKET; }
  20968. time_t duration() const override { return 0; }
  20969. };
  20970. TEST(StreamHandleTest, Basic) {
  20971. ClientImpl::StreamHandle handle;
  20972. EXPECT_FALSE(handle.is_valid());
  20973. handle.response = detail::make_unique<Response>();
  20974. handle.error = Error::Connection;
  20975. EXPECT_FALSE(handle.is_valid());
  20976. handle.error = Error::Success;
  20977. EXPECT_TRUE(handle.is_valid());
  20978. }
  20979. TEST(BodyReaderTest, Basic) {
  20980. MockStream stream("Hello, World!");
  20981. detail::BodyReader reader;
  20982. reader.stream = &stream;
  20983. reader.content_length = 13;
  20984. char buf[32];
  20985. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20986. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20987. EXPECT_TRUE(reader.eof);
  20988. }
  20989. TEST(BodyReaderTest, NoStream) {
  20990. detail::BodyReader reader;
  20991. char buf[32];
  20992. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20993. EXPECT_EQ(Error::Connection, reader.last_error);
  20994. }
  20995. TEST(BodyReaderTest, Error) {
  20996. MockStream stream("Hello, World!", 5);
  20997. detail::BodyReader reader;
  20998. reader.stream = &stream;
  20999. reader.content_length = 13;
  21000. char buf[32];
  21001. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  21002. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  21003. EXPECT_EQ(Error::Read, reader.last_error);
  21004. }
  21005. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  21006. // Mock-based StreamHandle tests relying on private internals are removed.
  21007. class OpenStreamTest : public ::testing::Test {
  21008. protected:
  21009. void SetUp() override {
  21010. svr_.Get("/hello", [](const Request &, Response &res) {
  21011. res.set_content("Hello World!", "text/plain");
  21012. });
  21013. svr_.Get("/large", [](const Request &, Response &res) {
  21014. res.set_content(std::string(10000, 'X'), "text/plain");
  21015. });
  21016. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  21017. res.set_content("Hello World!", "image/jpeg");
  21018. res.set_header("Content-Encoding", "UTF-8");
  21019. });
  21020. svr_.Get("/chunked", [](const Request &, Response &res) {
  21021. res.set_chunked_content_provider("text/plain",
  21022. [](size_t offset, DataSink &sink) {
  21023. if (offset < 15) {
  21024. sink.write("chunk", 5);
  21025. return true;
  21026. }
  21027. sink.done();
  21028. return true;
  21029. });
  21030. });
  21031. svr_.Get("/compressible", [](const Request &, Response &res) {
  21032. res.set_chunked_content_provider("text/plain", [](size_t offset,
  21033. DataSink &sink) {
  21034. if (offset < 100 * 1024) {
  21035. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  21036. sink.write(chunk.data(), chunk.size());
  21037. return true;
  21038. }
  21039. sink.done();
  21040. return true;
  21041. });
  21042. });
  21043. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  21044. [](const Request & /*req*/, Response &res) {
  21045. auto i = new int(0);
  21046. res.set_header("Trailer", "Content-Length, X-Allowed");
  21047. res.set_chunked_content_provider(
  21048. "text/plain",
  21049. [i](size_t /*offset*/, DataSink &sink) {
  21050. switch (*i) {
  21051. case 0: sink.os << "123"; break;
  21052. case 1: sink.os << "456"; break;
  21053. case 2: sink.os << "789"; break;
  21054. case 3: {
  21055. sink.done_with_trailer(
  21056. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  21057. } break;
  21058. }
  21059. (*i)++;
  21060. return true;
  21061. },
  21062. [i](bool success) {
  21063. EXPECT_TRUE(success);
  21064. delete i;
  21065. });
  21066. });
  21067. // Echo headers endpoint for header-related tests
  21068. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  21069. std::string body;
  21070. for (const auto &h : req.headers) {
  21071. body.append(h.first);
  21072. body.push_back(':');
  21073. body.append(h.second);
  21074. body.push_back('\n');
  21075. }
  21076. res.set_content(body, "text/plain");
  21077. });
  21078. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  21079. std::string body;
  21080. for (const auto &h : req.headers) {
  21081. body.append(h.first);
  21082. body.push_back(':');
  21083. body.append(h.second);
  21084. body.push_back('\n');
  21085. }
  21086. res.set_content(body, "text/plain");
  21087. });
  21088. port_ = svr_.bind_to_any_port("127.0.0.1");
  21089. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21090. svr_.wait_until_ready();
  21091. }
  21092. void TearDown() override {
  21093. svr_.stop();
  21094. if (thread_.joinable()) thread_.join();
  21095. }
  21096. Server svr_;
  21097. std::thread thread_;
  21098. int port_ = 0;
  21099. };
  21100. TEST_F(OpenStreamTest, Basic) {
  21101. Client cli("127.0.0.1", port_);
  21102. auto handle = cli.open_stream("GET", "/hello");
  21103. EXPECT_TRUE(handle.is_valid());
  21104. EXPECT_EQ("Hello World!", read_all(handle));
  21105. }
  21106. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  21107. Client cli("127.0.0.1", port_);
  21108. auto handle = cli.open_stream("GET", "/unknown-encoding");
  21109. ASSERT_TRUE(handle.is_valid());
  21110. EXPECT_EQ("Hello World!", read_all(handle));
  21111. }
  21112. TEST_F(OpenStreamTest, SmallBuffer) {
  21113. Client cli("127.0.0.1", port_);
  21114. auto handle = cli.open_stream("GET", "/hello");
  21115. std::string result;
  21116. char buf[4];
  21117. ssize_t n;
  21118. while ((n = handle.read(buf, sizeof(buf))) > 0)
  21119. result.append(buf, static_cast<size_t>(n));
  21120. EXPECT_EQ("Hello World!", result);
  21121. }
  21122. TEST_F(OpenStreamTest, DefaultHeaders) {
  21123. Client cli("127.0.0.1", port_);
  21124. // open_stream GET should include Host, User-Agent and Accept-Encoding
  21125. {
  21126. auto handle = cli.open_stream("GET", "/echo-headers");
  21127. ASSERT_TRUE(handle.is_valid());
  21128. auto body = read_all(handle);
  21129. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  21130. std::string::npos);
  21131. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  21132. std::string::npos);
  21133. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  21134. }
  21135. // open_stream POST with body and no explicit content_type should NOT add
  21136. // text/plain Content-Type (behavior differs from non-streaming path), but
  21137. // should include Content-Length
  21138. {
  21139. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  21140. ASSERT_TRUE(handle.is_valid());
  21141. auto body = read_all(handle);
  21142. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  21143. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  21144. }
  21145. // open_stream POST with explicit Content-Type should preserve it
  21146. {
  21147. auto handle = cli.open_stream("POST", "/echo-headers", {},
  21148. {{"Content-Type", "application/custom"}},
  21149. "{}", "application/custom");
  21150. ASSERT_TRUE(handle.is_valid());
  21151. auto body = read_all(handle);
  21152. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  21153. }
  21154. // User-specified User-Agent must not be overwritten for stream API
  21155. {
  21156. auto handle = cli.open_stream("GET", "/echo-headers", {},
  21157. {{"User-Agent", "MyAgent/1.2"}});
  21158. ASSERT_TRUE(handle.is_valid());
  21159. auto body = read_all(handle);
  21160. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  21161. }
  21162. }
  21163. TEST_F(OpenStreamTest, Large) {
  21164. Client cli("127.0.0.1", port_);
  21165. auto handle = cli.open_stream("GET", "/large");
  21166. EXPECT_EQ(10000u, read_all(handle).size());
  21167. }
  21168. TEST_F(OpenStreamTest, ConnectionError) {
  21169. Client cli("127.0.0.1", 9999);
  21170. auto handle = cli.open_stream("GET", "/hello");
  21171. EXPECT_FALSE(handle.is_valid());
  21172. }
  21173. TEST_F(OpenStreamTest, Chunked) {
  21174. Client cli("127.0.0.1", port_);
  21175. auto handle = cli.open_stream("GET", "/chunked");
  21176. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21177. "Transfer-Encoding") == "chunked");
  21178. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  21179. }
  21180. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  21181. Client cli("127.0.0.1", port_);
  21182. auto handle =
  21183. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  21184. ASSERT_TRUE(handle.is_valid());
  21185. // Consume body to allow trailers to be received/parsed
  21186. auto body = read_all(handle);
  21187. // Explicitly parse trailers (ensure trailers are available for assertion)
  21188. handle.parse_trailers_if_needed();
  21189. EXPECT_EQ(std::string("123456789"), body);
  21190. // The response should include a Trailer header declaring both names
  21191. ASSERT_TRUE(handle.response);
  21192. EXPECT_TRUE(handle.response->has_header("Trailer"));
  21193. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  21194. handle.response->get_header_value("Trailer"));
  21195. // Prohibited trailer must not be present
  21196. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  21197. // Allowed trailer should be present
  21198. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  21199. EXPECT_EQ(std::string("yes"),
  21200. handle.response->get_trailer_value("X-Allowed"));
  21201. // Verify trailers are NOT present as regular headers
  21202. EXPECT_EQ(std::string(""),
  21203. handle.response->get_header_value("Content-Length"));
  21204. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  21205. }
  21206. // Accepts one connection on an OS-assigned port, which it hands over through
  21207. // port_promise, reads the request head and sends back response. after_send,
  21208. // if given, runs on the connection before it is closed.
  21209. static std::thread
  21210. serve_single_response(std::promise<int> &port_promise,
  21211. const std::string &response,
  21212. std::function<void(socket_t)> after_send = nullptr) {
  21213. return std::thread([&port_promise, response, after_send] {
  21214. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21215. default_socket_options(srv);
  21216. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21217. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21218. sockaddr_in addr{};
  21219. addr.sin_family = AF_INET;
  21220. addr.sin_port = htons(0); // Let OS assign a free port
  21221. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21222. int opt = 1;
  21223. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  21224. #ifdef _WIN32
  21225. reinterpret_cast<const char *>(&opt),
  21226. #else
  21227. &opt,
  21228. #endif
  21229. sizeof(opt));
  21230. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21231. ::listen(srv, 1) != 0) {
  21232. port_promise.set_value(-1);
  21233. detail::close_socket(srv);
  21234. return;
  21235. }
  21236. socklen_t addr_len = sizeof(addr);
  21237. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21238. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21239. sockaddr_in cli_addr{};
  21240. socklen_t cli_len = sizeof(cli_addr);
  21241. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21242. if (cli != INVALID_SOCKET) {
  21243. // Read the complete HTTP request (until the blank line that terminates
  21244. // headers) before sending the response. If the server closes the socket
  21245. // while the client's request data is still unread in the kernel receive
  21246. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  21247. // connection on both sides: it discards the client's receive buffer
  21248. // (which already holds our response) and causes any in-progress write on
  21249. // the client to fail with ECONNRESET. Reading all request data first
  21250. // ensures close() emits a graceful FIN.
  21251. {
  21252. char rbuf[256];
  21253. std::string req;
  21254. while (req.find("\r\n\r\n") == std::string::npos) {
  21255. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  21256. if (n <= 0) { break; }
  21257. req.append(rbuf, static_cast<size_t>(n));
  21258. }
  21259. }
  21260. ::send(cli,
  21261. #ifdef _WIN32
  21262. static_cast<const char *>(response.c_str()),
  21263. static_cast<int>(response.size()),
  21264. #else
  21265. response.c_str(), response.size(),
  21266. #endif
  21267. 0);
  21268. if (after_send) { after_send(cli); }
  21269. detail::close_socket(cli);
  21270. }
  21271. detail::close_socket(srv);
  21272. });
  21273. }
  21274. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  21275. #ifndef _WIN32
  21276. signal(SIGPIPE, SIG_IGN);
  21277. #endif
  21278. std::promise<int> port_promise;
  21279. auto port_future = port_promise.get_future();
  21280. auto server_thread =
  21281. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  21282. "Content-Type: text/plain\r\n"
  21283. "Content-Length: not-a-number\r\n"
  21284. "Connection: close\r\n"
  21285. "\r\n"
  21286. "hello");
  21287. auto port = port_future.get();
  21288. ASSERT_GT(port, 0);
  21289. Client cli("127.0.0.1", port);
  21290. auto handle = cli.open_stream("GET", "/");
  21291. EXPECT_FALSE(handle.is_valid());
  21292. server_thread.join();
  21293. }
  21294. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  21295. #ifndef _WIN32
  21296. signal(SIGPIPE, SIG_IGN);
  21297. #endif
  21298. std::promise<int> port_promise;
  21299. auto port_future = port_promise.get_future();
  21300. auto server_thread = serve_single_response(
  21301. port_promise, "HTTP/1.1 200 OK\r\n"
  21302. "Content-Type: text/plain\r\n"
  21303. "Content-Length: 99999999999999999999999999\r\n"
  21304. "Connection: close\r\n"
  21305. "\r\n"
  21306. "hello");
  21307. auto port = port_future.get();
  21308. ASSERT_GT(port, 0);
  21309. // Historically std::stoull would throw std::out_of_range here and crash
  21310. // the process, then parsing silently clamped to a bogus framing length and
  21311. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  21312. // so the stream fails to open, matching the not-a-number case above. The
  21313. // process still must NOT terminate.
  21314. Client cli("127.0.0.1", port);
  21315. auto handle = cli.open_stream("GET", "/");
  21316. EXPECT_FALSE(handle.is_valid());
  21317. server_thread.join();
  21318. }
  21319. #ifndef _WIN32
  21320. // As above for the body of a streamed request: a send() cut short by the write
  21321. // timeout must not leave the rest of the body unsent.
  21322. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  21323. signal(SIGPIPE, SIG_IGN);
  21324. Server svr;
  21325. svr.set_socket_options([](socket_t sock) {
  21326. int size = 8192;
  21327. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  21328. reinterpret_cast<const char *>(&size), sizeof(size));
  21329. });
  21330. svr.Post("/size", [](const Request &, Response &res,
  21331. const ContentReader &content_reader) {
  21332. // Outlast the client's write timeout before reading the body.
  21333. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  21334. size_t received = 0;
  21335. content_reader([&](const char *, size_t len) {
  21336. received += len;
  21337. return true;
  21338. });
  21339. res.set_content(std::to_string(received), "text/plain");
  21340. });
  21341. auto port = svr.bind_to_any_port(HOST);
  21342. std::thread t([&]() { svr.listen_after_bind(); });
  21343. auto se = detail::scope_exit([&] {
  21344. svr.stop();
  21345. t.join();
  21346. });
  21347. svr.wait_until_ready();
  21348. Client cli(HOST, port);
  21349. cli.set_write_timeout(0, 500000);
  21350. cli.set_socket_options([](socket_t sock) {
  21351. int size = 8192;
  21352. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  21353. reinterpret_cast<const char *>(&size), sizeof(size));
  21354. });
  21355. const std::string body(4 * 1024 * 1024, 'A');
  21356. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  21357. "application/octet-stream");
  21358. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21359. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  21360. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  21361. }
  21362. #endif
  21363. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  21364. std::promise<void> slow_started;
  21365. auto slow_started_future = slow_started.get_future();
  21366. Server svr;
  21367. svr.Get("/slow", [&](const Request &, Response &res) {
  21368. slow_started.set_value();
  21369. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21370. res.set_content("slow", "text/plain");
  21371. });
  21372. svr.Get("/fast", [](const Request &, Response &res) {
  21373. res.set_content("fast", "text/plain");
  21374. });
  21375. auto port = svr.bind_to_any_port(HOST);
  21376. std::thread t([&]() { svr.listen_after_bind(); });
  21377. auto se = detail::scope_exit([&] {
  21378. svr.stop();
  21379. t.join();
  21380. });
  21381. svr.wait_until_ready();
  21382. Client cli(HOST, port);
  21383. std::string slow_body;
  21384. std::thread slow_thread([&] {
  21385. auto res = cli.Get("/slow");
  21386. if (res) { slow_body = res->body; }
  21387. });
  21388. slow_started_future.wait();
  21389. auto result = stream::Get(cli, "/fast");
  21390. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  21391. slow_thread.join();
  21392. EXPECT_EQ("slow", slow_body);
  21393. EXPECT_EQ("fast", fast_body);
  21394. }
  21395. // Serves `response` to the single request `fn` makes with a fresh client.
  21396. template <typename Fn>
  21397. static void with_single_response(const std::string &response, Fn fn) {
  21398. #ifndef _WIN32
  21399. signal(SIGPIPE, SIG_IGN);
  21400. #endif
  21401. std::promise<int> port_promise;
  21402. auto port_future = port_promise.get_future();
  21403. auto server_thread = serve_single_response(port_promise, response);
  21404. auto se = detail::scope_exit([&] { server_thread.join(); });
  21405. auto port = port_future.get();
  21406. ASSERT_GT(port, 0);
  21407. Client cli("127.0.0.1", port);
  21408. fn(cli);
  21409. }
  21410. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  21411. // too, also in a build without the decoder for the advertised coding.
  21412. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  21413. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  21414. const auto response = "HTTP/1.1 200 OK\r\n"
  21415. "Content-Encoding: gzip\r\n"
  21416. "Content-Length: " +
  21417. std::to_string(gzipped.size()) +
  21418. "\r\n"
  21419. "Connection: close\r\n\r\n" +
  21420. gzipped;
  21421. with_single_response(response, [&](Client &cli) {
  21422. cli.set_decompress(false);
  21423. auto handle = cli.open_stream("GET", "/");
  21424. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21425. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21426. EXPECT_EQ(gzipped, read_all(handle));
  21427. EXPECT_FALSE(handle.has_read_error());
  21428. });
  21429. with_single_response(response, [&](Client &cli) {
  21430. cli.set_decompress(false);
  21431. auto res = stream::Get(cli, "/", 7);
  21432. ASSERT_TRUE(res) << to_string(res.error());
  21433. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  21434. EXPECT_EQ(gzipped, res.read_all());
  21435. EXPECT_FALSE(res.has_read_error());
  21436. });
  21437. }
  21438. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  21439. // Neither Content-Length nor chunked: the body ends at the close
  21440. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  21441. "Connection: close\r\n"
  21442. "\r\n"
  21443. "hello";
  21444. with_single_response(close_delimited, [](Client &cli) {
  21445. auto handle = cli.open_stream("GET", "/");
  21446. ASSERT_TRUE(handle.is_valid());
  21447. EXPECT_EQ("hello", read_all(handle));
  21448. EXPECT_FALSE(handle.has_read_error());
  21449. });
  21450. // A close before the end of the Content-Length is still an error
  21451. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  21452. "Content-Length: 10\r\n"
  21453. "\r\n"
  21454. "hello";
  21455. with_single_response(short_content_length, [](Client &cli) {
  21456. auto handle = cli.open_stream("GET", "/");
  21457. ASSERT_TRUE(handle.is_valid());
  21458. read_all(handle);
  21459. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  21460. });
  21461. // So is a close before the last chunk
  21462. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  21463. "Transfer-Encoding: chunked\r\n"
  21464. "\r\n"
  21465. "5\r\nhello\r\n";
  21466. with_single_response(short_chunked, [](Client &cli) {
  21467. auto handle = cli.open_stream("GET", "/");
  21468. ASSERT_TRUE(handle.is_valid());
  21469. read_all(handle);
  21470. EXPECT_TRUE(handle.has_read_error());
  21471. });
  21472. }
  21473. #ifdef CPPHTTPLIB_SSL_ENABLED
  21474. // Serves `response` to one request, then closes with or without a close_notify
  21475. template <typename Fn>
  21476. static void with_single_tls_response(const std::string &response,
  21477. bool close_notify, Fn fn) {
  21478. #ifndef _WIN32
  21479. signal(SIGPIPE, SIG_IGN);
  21480. #endif
  21481. std::promise<int> port_promise;
  21482. auto port_future = port_promise.get_future();
  21483. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21484. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21485. default_socket_options(srv);
  21486. sockaddr_in addr{};
  21487. addr.sin_family = AF_INET;
  21488. addr.sin_port = htons(0);
  21489. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21490. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21491. ::listen(srv, 1) != 0) {
  21492. port_promise.set_value(-1);
  21493. detail::close_socket(srv);
  21494. return;
  21495. }
  21496. socklen_t addr_len = sizeof(addr);
  21497. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21498. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21499. auto cli = ::accept(srv, nullptr, nullptr);
  21500. if (cli != INVALID_SOCKET) {
  21501. auto ctx = tls::create_server_context();
  21502. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21503. nullptr);
  21504. auto session = tls::create_session(ctx, cli);
  21505. tls::TlsError err;
  21506. if (tls::accept_nonblocking(session, cli, 5, 0, &err, nullptr)) {
  21507. // The request head first, so that closing the socket sends a FIN
  21508. // rather than an RST for the unread bytes.
  21509. std::string req;
  21510. char buf[256];
  21511. while (req.find("\r\n\r\n") == std::string::npos) {
  21512. auto n = tls::read(session, buf, sizeof(buf), err);
  21513. if (n <= 0) { break; }
  21514. req.append(buf, static_cast<size_t>(n));
  21515. }
  21516. size_t sent = 0;
  21517. while (sent < response.size()) {
  21518. auto n = tls::write(session, response.data() + sent,
  21519. response.size() - sent, err);
  21520. if (n <= 0) { break; }
  21521. sent += static_cast<size_t>(n);
  21522. }
  21523. if (close_notify) { tls::shutdown(session, true); }
  21524. }
  21525. tls::free_session(session);
  21526. detail::close_socket(cli);
  21527. tls::free_context(ctx);
  21528. }
  21529. detail::close_socket(srv);
  21530. });
  21531. auto se = detail::scope_exit([&] { server_thread.join(); });
  21532. auto port = port_future.get();
  21533. ASSERT_GT(port, 0);
  21534. SSLClient cli("127.0.0.1", port);
  21535. cli.enable_server_certificate_verification(false);
  21536. fn(cli);
  21537. }
  21538. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21539. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21540. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21541. "Connection: close\r\n"
  21542. "\r\n"
  21543. "hello";
  21544. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21545. auto res = cli.Get("/");
  21546. ASSERT_TRUE(res) << to_string(res.error());
  21547. EXPECT_EQ("hello", res->body);
  21548. });
  21549. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21550. auto res = cli.Get("/");
  21551. ASSERT_FALSE(res);
  21552. EXPECT_EQ(Error::Read, res.error());
  21553. });
  21554. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21555. auto handle = cli.open_stream("GET", "/");
  21556. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21557. read_all(handle);
  21558. EXPECT_TRUE(handle.has_read_error());
  21559. });
  21560. // A framed body ends where its framing says, with or without the alert
  21561. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21562. "Content-Length: 5\r\n"
  21563. "Connection: close\r\n"
  21564. "\r\n"
  21565. "hello";
  21566. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21567. auto res = cli.Get("/");
  21568. ASSERT_TRUE(res) << to_string(res.error());
  21569. EXPECT_EQ("hello", res->body);
  21570. });
  21571. }
  21572. #endif
  21573. TEST(ResponseHeaderLengthTest, ClientReadsLongerFieldsThanServer) {
  21574. const auto value = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH * 2, 'a');
  21575. const auto response = "HTTP/1.1 200 OK\r\n"
  21576. "X-Long: " +
  21577. value +
  21578. "\r\n"
  21579. "Content-Length: 2\r\n"
  21580. "Connection: close\r\n\r\nok";
  21581. with_single_response(response, [&](Client &cli) {
  21582. auto res = cli.Get("/");
  21583. ASSERT_TRUE(res) << to_string(res.error());
  21584. EXPECT_EQ(value, res->get_header_value("X-Long"));
  21585. });
  21586. with_single_response(response, [&](Client &cli) {
  21587. auto handle = cli.open_stream("GET", "/");
  21588. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21589. EXPECT_EQ(value, handle.response->get_header_value("X-Long"));
  21590. });
  21591. std::string out;
  21592. test_raw_request("GET /hi HTTP/1.1\r\n"
  21593. "Host: localhost\r\n"
  21594. "X-Long: " +
  21595. value + "\r\n\r\n",
  21596. &out);
  21597. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  21598. }
  21599. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21600. const char *responses[] = {
  21601. "HTTP/1.1 103 Early Hints\r\n"
  21602. "Link: </style.css>; rel=preload\r\n"
  21603. "\r\n"
  21604. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21605. "HTTP/1.1 100 Continue\r\n"
  21606. "X-Note: interim\r\n"
  21607. "\r\n"
  21608. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21609. };
  21610. for (auto response : responses) {
  21611. with_single_response(response, [](Client &cli) {
  21612. auto res = cli.Get("/");
  21613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21614. EXPECT_EQ(StatusCode::OK_200, res->status);
  21615. EXPECT_EQ("ok", res->body);
  21616. });
  21617. }
  21618. }
  21619. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21620. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21621. const std::string final_response =
  21622. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21623. std::string interims;
  21624. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21625. interims += interim;
  21626. }
  21627. with_single_response(interims + final_response, [](Client &cli) {
  21628. auto res = cli.Get("/");
  21629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21630. EXPECT_EQ("ok", res->body);
  21631. });
  21632. with_single_response(interims + interim + final_response, [](Client &cli) {
  21633. auto res = cli.Get("/");
  21634. ASSERT_FALSE(res);
  21635. EXPECT_EQ(Error::Read, res.error());
  21636. });
  21637. }
  21638. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21639. #ifndef _WIN32
  21640. signal(SIGPIPE, SIG_IGN);
  21641. #endif
  21642. // The server answers the head without asking for the body. Bytes it then
  21643. // reads on the connection would be taken for the body the request declared.
  21644. auto closed_by_client = false;
  21645. std::promise<int> port_promise;
  21646. auto server_thread = serve_single_response(
  21647. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21648. [&](socket_t sock) {
  21649. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21650. char buf[256];
  21651. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21652. });
  21653. Client cli("127.0.0.1", port_promise.get_future().get());
  21654. cli.set_keep_alive(true);
  21655. cli.set_read_timeout(1, 0);
  21656. // Long enough for the client to send Expect: 100-continue.
  21657. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21659. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21660. cli.Get("/second");
  21661. server_thread.join();
  21662. EXPECT_TRUE(closed_by_client);
  21663. }
  21664. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21665. // Long enough for the client to send Expect: 100-continue
  21666. with_single_response(
  21667. "HTTP/1.1 103 Early Hints\r\n"
  21668. "Link: </style.css>; rel=preload\r\n"
  21669. "\r\n"
  21670. "HTTP/1.1 401 Unauthorized\r\n"
  21671. "Content-Length: 0\r\n\r\n",
  21672. [](Client &cli) {
  21673. cli.set_read_timeout(2, 0);
  21674. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21676. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21677. });
  21678. }
  21679. #ifdef CPPHTTPLIB_SSL_ENABLED
  21680. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21681. #ifndef _WIN32
  21682. signal(SIGPIPE, SIG_IGN);
  21683. #endif
  21684. auto reused = false;
  21685. std::promise<int> port_promise;
  21686. auto server_thread = serve_single_response(
  21687. port_promise,
  21688. "HTTP/1.1 401 Unauthorized\r\n"
  21689. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21690. "Content-Length: 0\r\n\r\n",
  21691. [&](socket_t sock) {
  21692. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21693. char buf[256];
  21694. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21695. });
  21696. Client cli("127.0.0.1", port_promise.get_future().get());
  21697. cli.set_keep_alive(true);
  21698. cli.set_digest_auth("user", "pass");
  21699. cli.set_read_timeout(1, 0);
  21700. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21701. server_thread.join();
  21702. EXPECT_FALSE(reused);
  21703. }
  21704. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21705. // Any other answer to CONNECT would read as the origin's response.
  21706. struct {
  21707. const char *response;
  21708. bool passed_on;
  21709. } cases[] = {
  21710. {"HTTP/1.1 201 Created\r\n"
  21711. "Set-Cookie: session=from-proxy\r\n"
  21712. "Content-Length: 0\r\n\r\n",
  21713. false},
  21714. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21715. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21716. "Content-Length: 0\r\n\r\n",
  21717. true},
  21718. };
  21719. for (const auto &c : cases) {
  21720. std::promise<int> port_promise;
  21721. auto server_thread = serve_single_response(port_promise, c.response);
  21722. SSLClient cli("example.com", 443);
  21723. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21724. auto res = cli.Get("/");
  21725. server_thread.join();
  21726. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21727. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21728. if (res) {
  21729. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21730. }
  21731. }
  21732. }
  21733. #endif
  21734. // Records the client's error logger calls as "error METHOD path", or
  21735. // "error null" for a call without a request
  21736. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21737. return [&log](const Error &err, const Request *req) {
  21738. log.push_back(to_string(err) + " " +
  21739. (req ? req->method + " " + req->path : "null"));
  21740. };
  21741. }
  21742. // A failed request is reported once, with the request the caller made
  21743. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21744. Server svr;
  21745. svr.Get("/big", [](const Request &, Response &res) {
  21746. res.set_content(std::string(100000, 'b'), "text/plain");
  21747. });
  21748. auto port = svr.bind_to_any_port(HOST);
  21749. std::thread t([&]() { svr.listen_after_bind(); });
  21750. auto se = detail::scope_exit([&] {
  21751. svr.stop();
  21752. t.join();
  21753. });
  21754. svr.wait_until_ready();
  21755. Client cli(HOST, port);
  21756. std::vector<std::string> log;
  21757. cli.set_error_logger(record_errors(log));
  21758. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21759. cli.Get("/big", [](const char *, size_t) { return false; });
  21760. EXPECT_EQ(expected, log);
  21761. log.clear();
  21762. cli.Get("/big", [](size_t, size_t) { return false; });
  21763. EXPECT_EQ(expected, log);
  21764. }
  21765. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21766. // Fails while the body is read
  21767. auto broken = [](const Request &, Response &res) {
  21768. res.set_content_provider(10, "text/plain",
  21769. [](size_t, size_t, DataSink &) { return false; });
  21770. };
  21771. Server other;
  21772. other.Get("/broken", broken);
  21773. auto other_port = other.bind_to_any_port(HOST);
  21774. std::thread other_t([&]() { other.listen_after_bind(); });
  21775. auto other_se = detail::scope_exit([&] {
  21776. other.stop();
  21777. other_t.join();
  21778. });
  21779. other.wait_until_ready();
  21780. Server svr;
  21781. svr.Get("/broken", broken);
  21782. svr.Get("/same-origin",
  21783. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21784. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21785. res.set_redirect("http://" + std::string(HOST) + ":" +
  21786. std::to_string(other_port) + "/broken");
  21787. });
  21788. auto port = svr.bind_to_any_port(HOST);
  21789. std::thread t([&]() { svr.listen_after_bind(); });
  21790. auto se = detail::scope_exit([&] {
  21791. svr.stop();
  21792. t.join();
  21793. });
  21794. svr.wait_until_ready();
  21795. Client cli(HOST, port);
  21796. cli.set_follow_location(true);
  21797. std::vector<std::string> log;
  21798. cli.set_error_logger(record_errors(log));
  21799. for (auto path : {"/same-origin", "/cross-origin"}) {
  21800. log.clear();
  21801. auto res = cli.Get(path);
  21802. ASSERT_FALSE(res);
  21803. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21804. log);
  21805. }
  21806. }
  21807. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21808. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21809. std::vector<std::string> log;
  21810. cli.set_error_logger(record_errors(log));
  21811. auto handle = cli.open_stream("GET", "/x");
  21812. EXPECT_FALSE(handle.is_valid());
  21813. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21814. log);
  21815. });
  21816. }
  21817. #ifdef CPPHTTPLIB_SSL_ENABLED
  21818. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21819. // Not a TLS server, so the handshake fails. It waits for a request line in
  21820. // the handshake bytes, so a short read timeout lets it close quickly.
  21821. Server svr;
  21822. svr.set_read_timeout(0, 100000);
  21823. svr.Get("/x", [](const Request &, Response &res) {
  21824. res.set_content("x", "text/plain");
  21825. });
  21826. auto port = svr.bind_to_any_port(HOST);
  21827. std::thread t([&]() { svr.listen_after_bind(); });
  21828. auto se = detail::scope_exit([&] {
  21829. svr.stop();
  21830. t.join();
  21831. });
  21832. svr.wait_until_ready();
  21833. std::vector<std::string> log;
  21834. SSLClient cli(HOST, port);
  21835. cli.enable_server_certificate_verification(false);
  21836. cli.set_error_logger(record_errors(log));
  21837. auto res = cli.Get("/x");
  21838. ASSERT_FALSE(res);
  21839. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21840. log.clear();
  21841. auto handle = cli.open_stream("GET", "/x");
  21842. EXPECT_FALSE(handle.is_valid());
  21843. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21844. log.clear();
  21845. SSLClient no_ca(HOST, port);
  21846. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21847. no_ca.set_error_logger(record_errors(log));
  21848. res = no_ca.Get("/x");
  21849. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21850. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21851. }
  21852. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21853. #ifndef _WIN32
  21854. signal(SIGPIPE, SIG_IGN);
  21855. #endif
  21856. // Refused, answered with a challenge, or closed without an answer
  21857. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21858. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21859. "Content-Length: 0\r\n\r\n",
  21860. ""}) {
  21861. std::promise<int> port_promise;
  21862. auto server_thread = serve_single_response(port_promise, response);
  21863. SSLClient cli("example.com", 443);
  21864. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21865. std::vector<std::string> log;
  21866. cli.set_error_logger(record_errors(log));
  21867. auto res = cli.Get("/");
  21868. server_thread.join();
  21869. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21870. << response;
  21871. }
  21872. }
  21873. #endif
  21874. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21875. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21876. // the chunked coding and drop Content-Length, so a front-end that trusts
  21877. // Content-Length would disagree about where the body ends (response
  21878. // smuggling). The client must reject such a response.
  21879. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21880. for (const char *te : {"chunked", "gzip, chunked"}) {
  21881. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21882. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21883. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21884. "5\r\nhello\r\n0\r\n\r\n";
  21885. with_single_response(response, [&](Client &cli) {
  21886. auto res = cli.Get("/");
  21887. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21888. EXPECT_EQ(Error::Read, res.error()) << te;
  21889. });
  21890. with_single_response(response, [&](Client &cli) {
  21891. auto handle = cli.open_stream("GET", "/");
  21892. EXPECT_FALSE(handle.is_valid()) << te;
  21893. EXPECT_EQ(Error::Read, handle.error) << te;
  21894. });
  21895. }
  21896. }
  21897. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21898. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21899. // closing the connection (unlike a request, which must be rejected).
  21900. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21901. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21902. "Transfer-Encoding: chunked\r\n"
  21903. "Connection: close\r\n"
  21904. "\r\n"
  21905. "5\r\nhello\r\n0\r\n\r\n",
  21906. "HTTP/1.1 200 OK\r\n"
  21907. "Transfer-Encoding: gzip\r\n"
  21908. "Connection: close\r\n"
  21909. "\r\n"
  21910. "hello"}) {
  21911. with_single_response(response, [&](Client &cli) {
  21912. auto res = cli.Get("/");
  21913. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21914. EXPECT_EQ("hello", res->body);
  21915. });
  21916. with_single_response(response, [&](Client &cli) {
  21917. auto handle = cli.open_stream("GET", "/");
  21918. ASSERT_TRUE(handle.is_valid()) << response;
  21919. EXPECT_EQ("hello", read_all(handle));
  21920. });
  21921. }
  21922. }
  21923. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21924. // framing headers describe nothing to read and must not be rejected.
  21925. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21926. const std::string framing = "Content-Length: 5\r\n"
  21927. "Transfer-Encoding: chunked\r\n"
  21928. "Connection: close\r\n"
  21929. "\r\n";
  21930. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21931. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21932. });
  21933. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21934. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21935. });
  21936. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21937. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21938. with_single_response(response, [&](Client &cli) {
  21939. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21940. });
  21941. with_single_response(response, [&](Client &cli) {
  21942. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21943. });
  21944. }
  21945. }
  21946. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21947. // header section, so a stream opened on one has nothing to read, whatever
  21948. // framing or coding headers it carries.
  21949. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21950. struct Case {
  21951. const char *method;
  21952. const char *status;
  21953. };
  21954. // A reader of the declared body reports an early close when nothing
  21955. // follows, and hands back what does.
  21956. struct Framing {
  21957. const char *headers;
  21958. const char *after;
  21959. };
  21960. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21961. Case{"GET", "304 Not Modified"}}) {
  21962. for (const auto &f :
  21963. {Framing{"Content-Length: 5\r\n", ""},
  21964. Framing{"Content-Length: 5\r\n", "hello"},
  21965. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21966. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21967. // Not decoded, so a build without Brotli opens it too
  21968. Framing{"Content-Encoding: br\r\n", ""}}) {
  21969. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21970. "Connection: close\r\n"
  21971. "\r\n" +
  21972. f.after;
  21973. with_single_response(response, [&](Client &cli) {
  21974. auto handle = cli.open_stream(c.method, "/");
  21975. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21976. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21977. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21978. });
  21979. }
  21980. }
  21981. }
  21982. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21983. // response, is faulty framing, so the connection is not reused after it.
  21984. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21985. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21986. "Content-Length: 0\r\n"
  21987. "Transfer-Encoding: chunked\r\n"
  21988. "\r\n"
  21989. "5\r\nhello\r\n0\r\n\r\n",
  21990. "HTTP/1.0 200 Connection established\r\n"
  21991. "Connection: keep-alive\r\n"
  21992. "Transfer-Encoding: chunked\r\n"
  21993. "\r\n"
  21994. "5\r\nhello\r\n0\r\n\r\n"}) {
  21995. with_single_response(response, [&](Client &cli) {
  21996. cli.set_keep_alive(true);
  21997. auto res = cli.Get("/");
  21998. ASSERT_TRUE(res) << response;
  21999. EXPECT_EQ("hello", res->body);
  22000. EXPECT_FALSE(cli.is_socket_open()) << response;
  22001. });
  22002. }
  22003. }
  22004. // A payload max length of 0 means no limit, however the body is framed.
  22005. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  22006. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  22007. "Transfer-Encoding: chunked\r\n"
  22008. "\r\n"
  22009. "5\r\nhello\r\n0\r\n\r\n",
  22010. "HTTP/1.1 200 OK\r\n"
  22011. "Connection: close\r\n"
  22012. "\r\n"
  22013. "hello"}) {
  22014. with_single_response(response, [&](Client &cli) {
  22015. cli.set_payload_max_length(0);
  22016. auto res = cli.Get("/");
  22017. ASSERT_TRUE(res) << response;
  22018. EXPECT_EQ("hello", res->body) << response;
  22019. });
  22020. }
  22021. }
  22022. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  22023. Server svr;
  22024. svr.set_payload_max_length(0);
  22025. svr.Post("/echo", [](const Request &req, Response &res) {
  22026. res.set_content(req.body, "text/plain");
  22027. });
  22028. auto port = svr.bind_to_any_port(HOST);
  22029. thread t = thread([&] { svr.listen_after_bind(); });
  22030. auto se = detail::scope_exit([&] {
  22031. svr.stop();
  22032. t.join();
  22033. ASSERT_FALSE(svr.is_running());
  22034. });
  22035. svr.wait_until_ready();
  22036. Client cli(HOST, port);
  22037. auto res = cli.Post(
  22038. "/echo",
  22039. [](size_t /*offset*/, DataSink &sink) {
  22040. sink.write("hello", 5);
  22041. sink.done();
  22042. return true;
  22043. },
  22044. "text/plain");
  22045. ASSERT_TRUE(res);
  22046. EXPECT_EQ(StatusCode::OK_200, res->status);
  22047. EXPECT_EQ("hello", res->body);
  22048. }
  22049. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22050. TEST_F(OpenStreamTest, Gzip) {
  22051. Client cli("127.0.0.1", port_);
  22052. auto handle = cli.open_stream("GET", "/compressible", {},
  22053. {{"Accept-Encoding", "gzip"}});
  22054. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  22055. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  22056. }
  22057. TEST_F(OpenStreamTest, TrailersWithGzip) {
  22058. Client cli("127.0.0.1", port_);
  22059. auto handle =
  22060. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  22061. {{"Accept-Encoding", "gzip"}});
  22062. ASSERT_TRUE(handle.is_valid());
  22063. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  22064. EXPECT_EQ("123456789", read_all(handle));
  22065. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  22066. }
  22067. #endif
  22068. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  22069. TEST_F(OpenStreamTest, Brotli) {
  22070. Client cli("127.0.0.1", port_);
  22071. auto handle =
  22072. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  22073. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  22074. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  22075. }
  22076. #endif
  22077. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  22078. TEST_F(OpenStreamTest, Zstd) {
  22079. Client cli("127.0.0.1", port_);
  22080. auto handle = cli.open_stream("GET", "/compressible", {},
  22081. {{"Accept-Encoding", "zstd"}});
  22082. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  22083. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  22084. }
  22085. #endif
  22086. #ifdef CPPHTTPLIB_SSL_ENABLED
  22087. class SSLOpenStreamTest : public ::testing::Test {
  22088. protected:
  22089. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  22090. void SetUp() override {
  22091. svr_.Get("/hello", [](const Request &, Response &res) {
  22092. res.set_content("Hello SSL World!", "text/plain");
  22093. });
  22094. svr_.Get("/chunked", [](const Request &, Response &res) {
  22095. res.set_chunked_content_provider("text/plain",
  22096. [](size_t offset, DataSink &sink) {
  22097. if (offset < 15) {
  22098. sink.write("chunk", 5);
  22099. return true;
  22100. }
  22101. sink.done();
  22102. return true;
  22103. });
  22104. });
  22105. svr_.Post("/echo", [](const Request &req, Response &res) {
  22106. res.set_content(req.body, req.get_header_value("Content-Type"));
  22107. });
  22108. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  22109. std::string body = req.body;
  22110. res.set_chunked_content_provider(
  22111. "text/plain", [body](size_t offset, DataSink &sink) {
  22112. if (offset < body.size()) {
  22113. sink.write(body.data() + offset, body.size() - offset);
  22114. }
  22115. sink.done();
  22116. return true;
  22117. });
  22118. });
  22119. port_ = svr_.bind_to_any_port("127.0.0.1");
  22120. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22121. svr_.wait_until_ready();
  22122. }
  22123. void TearDown() override {
  22124. svr_.stop();
  22125. if (thread_.joinable()) thread_.join();
  22126. }
  22127. SSLServer svr_;
  22128. std::thread thread_;
  22129. int port_ = 0;
  22130. };
  22131. TEST_F(SSLOpenStreamTest, Basic) {
  22132. SSLClient cli("127.0.0.1", port_);
  22133. cli.enable_server_certificate_verification(false);
  22134. auto handle = cli.open_stream("GET", "/hello");
  22135. ASSERT_TRUE(handle.is_valid());
  22136. EXPECT_EQ("Hello SSL World!", read_all(handle));
  22137. }
  22138. TEST_F(SSLOpenStreamTest, Chunked) {
  22139. SSLClient cli("127.0.0.1", port_);
  22140. cli.enable_server_certificate_verification(false);
  22141. auto handle = cli.open_stream("GET", "/chunked");
  22142. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  22143. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  22144. "Transfer-Encoding") == "chunked");
  22145. auto body = read_all(handle);
  22146. EXPECT_EQ("chunkchunkchunk", body);
  22147. }
  22148. TEST_F(SSLOpenStreamTest, Post) {
  22149. SSLClient cli("127.0.0.1", port_);
  22150. cli.enable_server_certificate_verification(false);
  22151. auto handle =
  22152. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  22153. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  22154. EXPECT_EQ(200, handle.response->status);
  22155. auto body = read_all(handle);
  22156. EXPECT_EQ("Hello SSL POST", body);
  22157. }
  22158. TEST_F(SSLOpenStreamTest, PostChunked) {
  22159. SSLClient cli("127.0.0.1", port_);
  22160. cli.enable_server_certificate_verification(false);
  22161. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  22162. "Chunked SSL Data", "text/plain");
  22163. ASSERT_TRUE(handle.is_valid());
  22164. EXPECT_EQ(200, handle.response->status);
  22165. auto body = read_all(handle);
  22166. EXPECT_EQ("Chunked SSL Data", body);
  22167. }
  22168. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  22169. // Content-Length is terminated by the server closing the connection. When the
  22170. // SSL peer sends a close_notify after the body, the client must treat it as a
  22171. // clean EOF and return a successful response rather than an error.
  22172. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  22173. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22174. ASSERT_TRUE(svr.is_valid());
  22175. svr.set_keep_alive_max_count(1);
  22176. const std::string expected_body = "Hello from connection-close response!";
  22177. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  22178. res.set_content_provider("text/plain",
  22179. [&](size_t offset, DataSink &sink) -> bool {
  22180. if (offset < expected_body.size()) {
  22181. sink.write(expected_body.data() + offset,
  22182. expected_body.size() - offset);
  22183. }
  22184. sink.done();
  22185. return true;
  22186. });
  22187. });
  22188. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  22189. auto se = detail::scope_exit([&] {
  22190. svr.stop();
  22191. listen_thread.join();
  22192. ASSERT_FALSE(svr.is_running());
  22193. });
  22194. svr.wait_until_ready();
  22195. SSLClient cli(HOST, PORT);
  22196. cli.enable_server_certificate_verification(false);
  22197. auto res = cli.Get("/no-content-length");
  22198. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  22199. EXPECT_EQ(StatusCode::OK_200, res->status);
  22200. EXPECT_EQ(expected_body, res->body);
  22201. }
  22202. // Without Content-Length, the full buffer size reaches tls::read().
  22203. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  22204. if (sizeof(size_t) <= sizeof(int)) {
  22205. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  22206. }
  22207. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22208. ASSERT_TRUE(svr.is_valid());
  22209. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  22210. res.set_content_provider("text/plain",
  22211. [&](size_t offset, DataSink &sink) -> bool {
  22212. if (offset == 0) { sink.write("Hello", 5); }
  22213. sink.done();
  22214. return true;
  22215. });
  22216. });
  22217. auto port = svr.bind_to_any_port(HOST);
  22218. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  22219. auto se = detail::scope_exit([&] {
  22220. svr.stop();
  22221. listen_thread.join();
  22222. });
  22223. svr.wait_until_ready();
  22224. SSLClient cli(HOST, port);
  22225. cli.enable_server_certificate_verification(false);
  22226. auto handle = cli.open_stream("GET", "/no-content-length");
  22227. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  22228. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  22229. std::unique_ptr<char[]> buf(new char[len]);
  22230. std::string body;
  22231. ssize_t n;
  22232. while ((n = handle.read(buf.get(), len)) > 0) {
  22233. body.append(buf.get(), static_cast<size_t>(n));
  22234. }
  22235. EXPECT_EQ(0, n);
  22236. EXPECT_EQ("Hello", body);
  22237. }
  22238. #endif // CPPHTTPLIB_SSL_ENABLED
  22239. //==============================================================================
  22240. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  22241. // results for various scenarios.
  22242. //==============================================================================
  22243. TEST(ParityTest, GetVsOpenStream) {
  22244. Server svr;
  22245. const std::string path = "/parity";
  22246. const std::string content = "Parity test content: hello world";
  22247. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  22248. res.set_content(content, "text/plain");
  22249. });
  22250. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22251. auto se = detail::scope_exit([&] {
  22252. svr.stop();
  22253. t.join();
  22254. ASSERT_FALSE(svr.is_running());
  22255. });
  22256. svr.wait_until_ready();
  22257. Client cli(HOST, PORT);
  22258. // Non-stream path
  22259. auto r1 = cli.Get(path);
  22260. ASSERT_TRUE(r1);
  22261. EXPECT_EQ(StatusCode::OK_200, r1->status);
  22262. // Stream path
  22263. auto h = cli.open_stream("GET", path);
  22264. ASSERT_TRUE(h.is_valid());
  22265. EXPECT_EQ(r1->body, read_all(h));
  22266. }
  22267. // Helper to compress data with provided compressor type T
  22268. template <typename Compressor>
  22269. static std::string compress_payload_for_parity(const std::string &in) {
  22270. std::string out;
  22271. Compressor compressor;
  22272. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  22273. [&](const char *data, size_t n) {
  22274. out.append(data, n);
  22275. return true;
  22276. });
  22277. EXPECT_TRUE(ok);
  22278. return out;
  22279. }
  22280. // Helper function for compression parity tests
  22281. template <typename Compressor>
  22282. static void test_compression_parity(const std::string &original,
  22283. const std::string &path,
  22284. const std::string &encoding) {
  22285. const std::string compressed =
  22286. compress_payload_for_parity<Compressor>(original);
  22287. Server svr;
  22288. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  22289. res.set_content(compressed, "application/octet-stream");
  22290. res.set_header("Content-Encoding", encoding);
  22291. });
  22292. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  22293. auto se = detail::scope_exit([&] {
  22294. svr.stop();
  22295. t.join();
  22296. ASSERT_FALSE(svr.is_running());
  22297. });
  22298. svr.wait_until_ready();
  22299. Client cli(HOST, PORT);
  22300. // Non-streaming
  22301. {
  22302. auto res = cli.Get(path);
  22303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22304. EXPECT_EQ(StatusCode::OK_200, res->status);
  22305. EXPECT_EQ(original, res->body);
  22306. }
  22307. // Streaming
  22308. {
  22309. auto h = cli.open_stream("GET", path);
  22310. ASSERT_TRUE(h.is_valid());
  22311. EXPECT_EQ(original, read_all(h));
  22312. }
  22313. }
  22314. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22315. TEST(ParityTest, Gzip) {
  22316. test_compression_parity<detail::gzip_compressor>(
  22317. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  22318. }
  22319. #endif
  22320. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  22321. TEST(ParityTest, Brotli) {
  22322. test_compression_parity<detail::brotli_compressor>(
  22323. "Hello, brotli parity test payload", "/parity-br", "br");
  22324. }
  22325. #endif
  22326. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  22327. TEST(ParityTest, Zstd) {
  22328. test_compression_parity<detail::zstd_compressor>(
  22329. "Zstandard parity test payload", "/parity-zstd", "zstd");
  22330. }
  22331. #endif
  22332. //==============================================================================
  22333. // New Stream API Tests
  22334. //==============================================================================
  22335. inline std::string read_body(httplib::stream::Result &result) {
  22336. std::string body;
  22337. while (result.next()) {
  22338. body.append(result.data(), result.size());
  22339. }
  22340. return body;
  22341. }
  22342. TEST(ClientConnectionTest, Basic) {
  22343. httplib::ClientConnection conn;
  22344. EXPECT_FALSE(conn.is_open());
  22345. conn.sock = 1;
  22346. EXPECT_TRUE(conn.is_open());
  22347. httplib::ClientConnection conn2(std::move(conn));
  22348. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  22349. conn2.sock = INVALID_SOCKET;
  22350. }
  22351. // Unified test server for all stream::* tests
  22352. class StreamApiTest : public ::testing::Test {
  22353. protected:
  22354. void SetUp() override {
  22355. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22356. res.set_content("Hello World!", "text/plain");
  22357. });
  22358. svr_.Get("/echo-params",
  22359. [](const httplib::Request &req, httplib::Response &res) {
  22360. std::string r;
  22361. for (const auto &p : req.params) {
  22362. if (!r.empty()) r += "&";
  22363. r += p.first + "=" + p.second;
  22364. }
  22365. res.set_content(r, "text/plain");
  22366. });
  22367. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22368. res.set_content(req.body, req.get_header_value("Content-Type"));
  22369. });
  22370. svr_.Post("/echo-headers",
  22371. [](const httplib::Request &req, httplib::Response &res) {
  22372. std::string r;
  22373. for (const auto &h : req.headers)
  22374. r += h.first + ": " + h.second + "\n";
  22375. res.set_content(r, "text/plain");
  22376. });
  22377. svr_.Post("/echo-params",
  22378. [](const httplib::Request &req, httplib::Response &res) {
  22379. std::string r = "params:";
  22380. for (const auto &p : req.params)
  22381. r += p.first + "=" + p.second + ";";
  22382. res.set_content(r + " body:" + req.body, "text/plain");
  22383. });
  22384. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  22385. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  22386. });
  22387. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22388. res.set_content("PUT:" + req.body, "text/plain");
  22389. });
  22390. svr_.Patch("/echo",
  22391. [](const httplib::Request &req, httplib::Response &res) {
  22392. res.set_content("PATCH:" + req.body, "text/plain");
  22393. });
  22394. svr_.Delete(
  22395. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  22396. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  22397. "text/plain");
  22398. });
  22399. svr_.Get("/head-test",
  22400. [](const httplib::Request &, httplib::Response &res) {
  22401. res.set_content("body for HEAD", "text/plain");
  22402. });
  22403. svr_.Options("/options",
  22404. [](const httplib::Request &, httplib::Response &res) {
  22405. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  22406. });
  22407. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  22408. svr_.wait_until_ready();
  22409. }
  22410. void TearDown() override {
  22411. svr_.stop();
  22412. if (thread_.joinable()) thread_.join();
  22413. }
  22414. httplib::Server svr_;
  22415. std::thread thread_;
  22416. };
  22417. // stream::Get tests
  22418. TEST_F(StreamApiTest, GetBasic) {
  22419. httplib::Client cli(HOST, PORT);
  22420. auto result = httplib::stream::Get(cli, "/hello");
  22421. ASSERT_TRUE(result.is_valid());
  22422. EXPECT_EQ(200, result.status());
  22423. EXPECT_EQ("Hello World!", read_body(result));
  22424. }
  22425. TEST_F(StreamApiTest, GetWithParams) {
  22426. httplib::Client cli(HOST, PORT);
  22427. httplib::Params params{{"foo", "bar"}};
  22428. auto result = httplib::stream::Get(cli, "/echo-params", params);
  22429. ASSERT_TRUE(result.is_valid());
  22430. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  22431. }
  22432. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22433. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  22434. httplib::Client cli(HOST, PORT);
  22435. cli.set_payload_max_length(0);
  22436. auto result = httplib::stream::Get(cli, "/hello");
  22437. ASSERT_TRUE(result.is_valid());
  22438. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  22439. EXPECT_EQ("Hello World!", read_body(result));
  22440. }
  22441. #endif
  22442. TEST_F(StreamApiTest, GetConnectionError) {
  22443. httplib::Client cli(HOST, 9999);
  22444. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  22445. }
  22446. TEST_F(StreamApiTest, Get404) {
  22447. httplib::Client cli(HOST, PORT);
  22448. auto result = httplib::stream::Get(cli, "/nonexistent");
  22449. EXPECT_TRUE(result.is_valid());
  22450. EXPECT_EQ(404, result.status());
  22451. }
  22452. // stream::Post tests
  22453. TEST_F(StreamApiTest, PostBasic) {
  22454. httplib::Client cli(HOST, PORT);
  22455. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  22456. "application/json");
  22457. ASSERT_TRUE(result.is_valid());
  22458. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  22459. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  22460. }
  22461. TEST_F(StreamApiTest, PostWithHeaders) {
  22462. httplib::Client cli(HOST, PORT);
  22463. httplib::Headers headers{{"X-Custom", "value"}};
  22464. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  22465. "text/plain");
  22466. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  22467. }
  22468. TEST_F(StreamApiTest, PostWithParams) {
  22469. httplib::Client cli(HOST, PORT);
  22470. httplib::Params params{{"k", "v"}};
  22471. auto result =
  22472. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  22473. auto body = read_body(result);
  22474. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  22475. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  22476. }
  22477. TEST_F(StreamApiTest, PostLarge) {
  22478. httplib::Client cli(HOST, PORT);
  22479. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  22480. size_t total = 0;
  22481. while (result.next()) {
  22482. total += result.size();
  22483. }
  22484. EXPECT_EQ(100u * 1024u, total);
  22485. }
  22486. // stream::Put/Patch tests
  22487. TEST_F(StreamApiTest, PutAndPatch) {
  22488. httplib::Client cli(HOST, PORT);
  22489. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  22490. EXPECT_EQ("PUT:test", read_body(put));
  22491. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  22492. EXPECT_EQ("PATCH:test", read_body(patch));
  22493. }
  22494. // stream::Delete tests
  22495. TEST_F(StreamApiTest, Delete) {
  22496. httplib::Client cli(HOST, PORT);
  22497. auto del1 = httplib::stream::Delete(cli, "/resource");
  22498. EXPECT_EQ("Deleted", read_body(del1));
  22499. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  22500. EXPECT_EQ("Deleted:data", read_body(del2));
  22501. }
  22502. // stream::Head/Options tests
  22503. TEST_F(StreamApiTest, HeadAndOptions) {
  22504. httplib::Client cli(HOST, PORT);
  22505. auto head = httplib::stream::Head(cli, "/head-test");
  22506. EXPECT_TRUE(head.is_valid());
  22507. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  22508. auto opts = httplib::stream::Options(cli, "/options");
  22509. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22510. }
  22511. // SSL stream::* tests
  22512. #ifdef CPPHTTPLIB_SSL_ENABLED
  22513. class SSLStreamApiTest : public ::testing::Test {
  22514. protected:
  22515. void SetUp() override {
  22516. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22517. res.set_content("Hello SSL!", "text/plain");
  22518. });
  22519. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22520. res.set_content(req.body, "text/plain");
  22521. });
  22522. port_ = svr_.bind_to_any_port("127.0.0.1");
  22523. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22524. svr_.wait_until_ready();
  22525. }
  22526. void TearDown() override {
  22527. svr_.stop();
  22528. if (thread_.joinable()) thread_.join();
  22529. }
  22530. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22531. std::thread thread_;
  22532. int port_ = 0;
  22533. };
  22534. TEST_F(SSLStreamApiTest, GetAndPost) {
  22535. httplib::SSLClient cli("127.0.0.1", port_);
  22536. cli.enable_server_certificate_verification(false);
  22537. auto get = httplib::stream::Get(cli, "/hello");
  22538. EXPECT_EQ("Hello SSL!", read_body(get));
  22539. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22540. EXPECT_EQ("test", read_body(post));
  22541. }
  22542. #endif
  22543. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22544. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22545. // BodyReader
  22546. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22547. // Test that read timeout during streaming is detected
  22548. // Use a large content-length response where server delays mid-stream
  22549. Server svr;
  22550. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22551. // Send a large response with delay in the middle
  22552. res.set_content_provider(
  22553. 1000, // content_length
  22554. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22555. if (offset < 100) {
  22556. // Send first 100 bytes immediately
  22557. std::string data(100, 'A');
  22558. sink.write(data.c_str(), data.size());
  22559. return true;
  22560. }
  22561. // Then delay longer than client timeout
  22562. std::this_thread::sleep_for(std::chrono::seconds(3));
  22563. std::string data(900, 'B');
  22564. sink.write(data.c_str(), data.size());
  22565. return true;
  22566. });
  22567. });
  22568. auto port = 8091;
  22569. std::thread t([&]() { svr.listen("localhost", port); });
  22570. svr.wait_until_ready();
  22571. Client cli("localhost", port);
  22572. cli.set_read_timeout(1, 0); // 1 second timeout
  22573. auto handle = cli.open_stream("GET", "/slow-stream");
  22574. ASSERT_TRUE(handle.is_valid());
  22575. char buf[256];
  22576. ssize_t total = 0;
  22577. ssize_t n;
  22578. bool got_error = false;
  22579. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22580. total += n;
  22581. }
  22582. if (n < 0) {
  22583. got_error = true;
  22584. // Should be timeout or read error
  22585. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22586. handle.get_read_error() == Error::Read)
  22587. << "Actual error: " << to_string(handle.get_read_error());
  22588. }
  22589. // Either we got an error, or we got less data than expected
  22590. EXPECT_TRUE(got_error || total < 1000)
  22591. << "Expected timeout but got all " << total << " bytes";
  22592. svr.stop();
  22593. t.join();
  22594. }
  22595. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22596. // Test connection closed detection via BodyReader
  22597. Server svr;
  22598. std::atomic<bool> close_now{false};
  22599. svr.Get("/will-close", [&](const Request &, Response &res) {
  22600. res.set_content_provider(
  22601. 10000, // Large content_length that we won't fully send
  22602. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22603. if (offset < 100) {
  22604. std::string data(100, 'X');
  22605. sink.write(data.c_str(), data.size());
  22606. return true;
  22607. }
  22608. // Wait for signal then abort
  22609. while (!close_now) {
  22610. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22611. }
  22612. return false; // Abort - server will close connection
  22613. });
  22614. });
  22615. auto port = 8092;
  22616. std::thread t([&]() { svr.listen("localhost", port); });
  22617. svr.wait_until_ready();
  22618. Client cli("localhost", port);
  22619. auto handle = cli.open_stream("GET", "/will-close");
  22620. ASSERT_TRUE(handle.is_valid());
  22621. char buf[256];
  22622. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22623. EXPECT_GT(n, 0) << "First read should succeed";
  22624. // Signal server to close
  22625. close_now = true;
  22626. // Keep reading until error or EOF
  22627. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22628. // Keep reading
  22629. }
  22630. // Should get an error since content_length wasn't satisfied
  22631. if (n < 0) {
  22632. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22633. handle.get_read_error() == Error::Read)
  22634. << "Actual error: " << to_string(handle.get_read_error());
  22635. }
  22636. svr.stop();
  22637. t.join();
  22638. }
  22639. #ifdef CPPHTTPLIB_SSL_ENABLED
  22640. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22641. // Test that read timeout during SSL streaming is detected
  22642. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22643. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22644. res.set_content_provider(
  22645. 1000, "text/plain",
  22646. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22647. if (offset < 100) {
  22648. std::string data(100, 'A');
  22649. sink.write(data.c_str(), data.size());
  22650. return true;
  22651. }
  22652. std::this_thread::sleep_for(std::chrono::seconds(3));
  22653. std::string data(900, 'B');
  22654. sink.write(data.c_str(), data.size());
  22655. return true;
  22656. });
  22657. });
  22658. auto port = 8093;
  22659. std::thread t([&]() { svr.listen("localhost", port); });
  22660. svr.wait_until_ready();
  22661. SSLClient cli("localhost", port);
  22662. cli.enable_server_certificate_verification(false);
  22663. cli.set_read_timeout(1, 0); // 1 second timeout
  22664. auto handle = cli.open_stream("GET", "/slow-stream");
  22665. ASSERT_TRUE(handle.is_valid());
  22666. char buf[256];
  22667. ssize_t total = 0;
  22668. ssize_t n;
  22669. bool got_error = false;
  22670. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22671. total += n;
  22672. }
  22673. if (n < 0) {
  22674. got_error = true;
  22675. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22676. handle.get_read_error() == Error::Read)
  22677. << "Actual error: " << to_string(handle.get_read_error());
  22678. }
  22679. EXPECT_TRUE(got_error || total < 1000)
  22680. << "Expected timeout but got all " << total << " bytes";
  22681. svr.stop();
  22682. t.join();
  22683. }
  22684. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22685. // Test SSL connection closed detection
  22686. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22687. std::atomic<bool> close_now{false};
  22688. svr.Get("/will-close", [&](const Request &, Response &res) {
  22689. res.set_content_provider(
  22690. 10000, "text/plain",
  22691. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22692. if (offset < 100) {
  22693. std::string data(100, 'X');
  22694. sink.write(data.c_str(), data.size());
  22695. return true;
  22696. }
  22697. while (!close_now) {
  22698. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22699. }
  22700. return false;
  22701. });
  22702. });
  22703. auto port = 8094;
  22704. std::thread t([&]() { svr.listen("localhost", port); });
  22705. svr.wait_until_ready();
  22706. SSLClient cli("localhost", port);
  22707. cli.enable_server_certificate_verification(false);
  22708. auto handle = cli.open_stream("GET", "/will-close");
  22709. ASSERT_TRUE(handle.is_valid());
  22710. char buf[256];
  22711. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22712. EXPECT_GT(n, 0);
  22713. // Signal server to close
  22714. close_now = true;
  22715. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22716. // Keep reading
  22717. }
  22718. if (n < 0) {
  22719. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22720. handle.get_read_error() == Error::Read)
  22721. << "Actual error: " << to_string(handle.get_read_error());
  22722. }
  22723. svr.stop();
  22724. t.join();
  22725. }
  22726. #endif
  22727. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22728. using namespace httplib;
  22729. // Create a test file
  22730. const char *fname = "etag_testfile.txt";
  22731. const char *content = "etag-content";
  22732. {
  22733. std::ofstream ofs(fname);
  22734. ofs << content;
  22735. ASSERT_TRUE(ofs.good());
  22736. }
  22737. Server svr;
  22738. svr.set_mount_point("/static", ".");
  22739. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22740. svr.wait_until_ready();
  22741. Client cli(HOST, PORT);
  22742. // First request: should get 200 with ETag header
  22743. auto res1 = cli.Get("/static/etag_testfile.txt");
  22744. ASSERT_TRUE(res1);
  22745. ASSERT_EQ(200, res1->status);
  22746. ASSERT_TRUE(res1->has_header("ETag"));
  22747. std::string etag = res1->get_header_value("ETag");
  22748. EXPECT_FALSE(etag.empty());
  22749. // Verify ETag format: W/"hex-hex"
  22750. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22751. EXPECT_EQ('W', etag[0]);
  22752. EXPECT_EQ('/', etag[1]);
  22753. EXPECT_EQ('"', etag[2]);
  22754. EXPECT_EQ('"', etag.back());
  22755. // Exact match: expect 304 Not Modified
  22756. Headers h2 = {{"If-None-Match", etag}};
  22757. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22758. ASSERT_TRUE(res2);
  22759. EXPECT_EQ(304, res2->status);
  22760. // Wildcard match: expect 304 Not Modified
  22761. Headers h3 = {{"If-None-Match", "*"}};
  22762. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22763. ASSERT_TRUE(res3);
  22764. EXPECT_EQ(304, res3->status);
  22765. // Non-matching ETag: expect 200
  22766. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22767. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22768. ASSERT_TRUE(res4);
  22769. EXPECT_EQ(200, res4->status);
  22770. // Multiple ETags with one matching: expect 304
  22771. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22772. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22773. ASSERT_TRUE(res5);
  22774. EXPECT_EQ(304, res5->status);
  22775. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22776. // that equivalent to the single comma-separated list above, so the match on
  22777. // the second line must still be found.
  22778. Headers h6;
  22779. h6.emplace("If-None-Match", "W/\"other\"");
  22780. h6.emplace("If-None-Match", etag);
  22781. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22782. ASSERT_TRUE(res6);
  22783. EXPECT_EQ(304, res6->status);
  22784. svr.stop();
  22785. t.join();
  22786. std::remove(fname);
  22787. }
  22788. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22789. using namespace httplib;
  22790. Server svr;
  22791. svr.set_mount_point("/static", ".");
  22792. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22793. svr.wait_until_ready();
  22794. Client cli(HOST, PORT);
  22795. // Send If-None-Match: * to a non-existent file
  22796. Headers h = {{"If-None-Match", "*"}};
  22797. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22799. EXPECT_EQ(404, res->status);
  22800. svr.stop();
  22801. t.join();
  22802. }
  22803. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22804. using namespace httplib;
  22805. // Create a test file
  22806. const char *fname = "etag_boundary_testfile.txt";
  22807. const char *content = "boundary-test";
  22808. {
  22809. std::ofstream ofs(fname);
  22810. ofs << content;
  22811. ASSERT_TRUE(ofs.good());
  22812. }
  22813. Server svr;
  22814. svr.set_mount_point("/static", ".");
  22815. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22816. svr.wait_until_ready();
  22817. Client cli(HOST, PORT);
  22818. // Get the actual ETag
  22819. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22820. ASSERT_TRUE(res1);
  22821. ASSERT_EQ(200, res1->status);
  22822. ASSERT_TRUE(res1->has_header("ETag"));
  22823. std::string etag = res1->get_header_value("ETag");
  22824. // Test 1: Very long ETag value (longer than actual ETag)
  22825. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22826. Headers h1 = {{"If-None-Match", "W/"
  22827. "\"very-long-etag-value-that-is-much-longer-"
  22828. "than-the-actual-etag-value\""}};
  22829. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22830. ASSERT_TRUE(res2);
  22831. EXPECT_EQ(200, res2->status); // Should not match
  22832. // Test 2: Long string followed by wildcard
  22833. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22834. // string)
  22835. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22836. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22837. ASSERT_TRUE(res3);
  22838. EXPECT_EQ(304, res3->status); // Should match on "*"
  22839. // Test 3: Wildcard followed by long string
  22840. // Should match on "*" immediately and return 304
  22841. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22842. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22843. ASSERT_TRUE(res4);
  22844. EXPECT_EQ(304, res4->status); // Should match on "*"
  22845. // Test 4: Multiple long non-matching values
  22846. // Should NOT match and return 200 (test that all comparisons are safe)
  22847. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22848. "W/\"second-long-non-matching-value\", "
  22849. "W/\"third-long-non-matching-value\""}};
  22850. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22851. ASSERT_TRUE(res5);
  22852. EXPECT_EQ(200, res5->status); // Should not match
  22853. // Test 5: Single character that is not "*" (edge case)
  22854. Headers h5 = {{"If-None-Match", "X"}};
  22855. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22856. ASSERT_TRUE(res6);
  22857. EXPECT_EQ(200, res6->status); // Should not match
  22858. svr.stop();
  22859. t.join();
  22860. std::remove(fname);
  22861. }
  22862. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22863. using namespace httplib;
  22864. // Create a test file
  22865. const char *fname = "ims_testfile.txt";
  22866. const char *content = "if-modified-since-test";
  22867. {
  22868. std::ofstream ofs(fname);
  22869. ofs << content;
  22870. ASSERT_TRUE(ofs.good());
  22871. }
  22872. Server svr;
  22873. svr.set_mount_point("/static", ".");
  22874. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22875. svr.wait_until_ready();
  22876. Client cli(HOST, PORT);
  22877. // First request: should get 200 with Last-Modified header
  22878. auto res1 = cli.Get("/static/ims_testfile.txt");
  22879. ASSERT_TRUE(res1);
  22880. ASSERT_EQ(200, res1->status);
  22881. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22882. std::string last_modified = res1->get_header_value("Last-Modified");
  22883. EXPECT_FALSE(last_modified.empty());
  22884. // If-Modified-Since with same time: expect 304
  22885. Headers h2 = {{"If-Modified-Since", last_modified}};
  22886. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22887. ASSERT_TRUE(res2);
  22888. EXPECT_EQ(304, res2->status);
  22889. // If-Modified-Since with future time: expect 304
  22890. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22891. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22892. ASSERT_TRUE(res3);
  22893. EXPECT_EQ(304, res3->status);
  22894. // If-Modified-Since with past time: expect 200
  22895. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22896. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22897. ASSERT_TRUE(res4);
  22898. EXPECT_EQ(200, res4->status);
  22899. // If-None-Match takes precedence over If-Modified-Since
  22900. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22901. ASSERT_TRUE(res1->has_header("ETag"));
  22902. std::string etag = res1->get_header_value("ETag");
  22903. Headers h5 = {{"If-None-Match", etag},
  22904. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22905. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22906. ASSERT_TRUE(res5);
  22907. EXPECT_EQ(304, res5->status);
  22908. svr.stop();
  22909. t.join();
  22910. std::remove(fname);
  22911. }
  22912. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22913. using namespace httplib;
  22914. Server svr;
  22915. // Endpoint that returns compressible content
  22916. svr.Get("/compressible", [](const Request &, Response &res) {
  22917. // Return a large enough body to trigger compression
  22918. std::string body(1000, 'a');
  22919. res.set_content(body, "text/plain");
  22920. });
  22921. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22922. svr.wait_until_ready();
  22923. Client cli(HOST, PORT);
  22924. // Request with gzip support: should get Vary header when compressed
  22925. cli.set_compress(true);
  22926. auto res1 = cli.Get("/compressible");
  22927. ASSERT_TRUE(res1);
  22928. EXPECT_EQ(200, res1->status);
  22929. // If Content-Encoding is set, Vary should also be set
  22930. if (res1->has_header("Content-Encoding")) {
  22931. EXPECT_TRUE(res1->has_header("Vary"));
  22932. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22933. }
  22934. // Request without Accept-Encoding header: should not have compression
  22935. Headers h_no_compress;
  22936. auto res2 = cli.Get("/compressible", h_no_compress);
  22937. ASSERT_TRUE(res2);
  22938. EXPECT_EQ(200, res2->status);
  22939. // Verify Vary header is present when compression is applied
  22940. // (the exact behavior depends on server configuration)
  22941. svr.stop();
  22942. t.join();
  22943. }
  22944. TEST(ETagTest, IfRangeWithETag) {
  22945. using namespace httplib;
  22946. // Create a test file with known content
  22947. const char *fname = "if_range_testfile.txt";
  22948. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22949. {
  22950. std::ofstream ofs(fname);
  22951. ofs << content;
  22952. ASSERT_TRUE(ofs.good());
  22953. }
  22954. Server svr;
  22955. svr.set_mount_point("/static", ".");
  22956. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22957. svr.wait_until_ready();
  22958. Client cli(HOST, PORT);
  22959. // First request: get ETag
  22960. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22961. ASSERT_TRUE(res1);
  22962. ASSERT_EQ(200, res1->status);
  22963. ASSERT_TRUE(res1->has_header("ETag"));
  22964. std::string etag = res1->get_header_value("ETag");
  22965. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22966. // Since our server generates weak ETags (W/"..."), If-Range with our
  22967. // ETag should NOT result in partial content - it should return full content.
  22968. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22969. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22970. ASSERT_TRUE(res2);
  22971. // Weak ETag in If-Range -> full content (200), not partial (206)
  22972. EXPECT_EQ(200, res2->status);
  22973. EXPECT_EQ(content, res2->body);
  22974. EXPECT_FALSE(res2->has_header("Content-Range"));
  22975. // Range request with non-matching If-Range (ETag): should get 200 (full
  22976. // content)
  22977. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22978. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22979. ASSERT_TRUE(res3);
  22980. EXPECT_EQ(200, res3->status);
  22981. EXPECT_EQ(content, res3->body);
  22982. EXPECT_FALSE(res3->has_header("Content-Range"));
  22983. // Range request with strong ETag (hypothetical - our server doesn't generate
  22984. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22985. // should return full content)
  22986. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22987. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22988. ASSERT_TRUE(res4);
  22989. EXPECT_EQ(200, res4->status);
  22990. EXPECT_EQ(content, res4->body);
  22991. EXPECT_FALSE(res4->has_header("Content-Range"));
  22992. svr.stop();
  22993. t.join();
  22994. std::remove(fname);
  22995. }
  22996. TEST(ETagTest, IfRangeWithDate) {
  22997. using namespace httplib;
  22998. // Create a test file
  22999. const char *fname = "if_range_date_testfile.txt";
  23000. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  23001. {
  23002. std::ofstream ofs(fname);
  23003. ofs << content;
  23004. ASSERT_TRUE(ofs.good());
  23005. }
  23006. Server svr;
  23007. svr.set_mount_point("/static", ".");
  23008. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23009. svr.wait_until_ready();
  23010. Client cli(HOST, PORT);
  23011. // First request: get Last-Modified
  23012. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  23013. ASSERT_TRUE(res1);
  23014. ASSERT_EQ(200, res1->status);
  23015. ASSERT_TRUE(res1->has_header("Last-Modified"));
  23016. std::string last_modified = res1->get_header_value("Last-Modified");
  23017. // Range request with matching If-Range (date): should get 206
  23018. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  23019. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  23020. ASSERT_TRUE(res2);
  23021. EXPECT_EQ(206, res2->status);
  23022. EXPECT_EQ("FGHIJ", res2->body);
  23023. // Range request with old If-Range date: should get 200 (full content)
  23024. Headers h3 = {{"Range", "bytes=5-9"},
  23025. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  23026. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  23027. ASSERT_TRUE(res3);
  23028. EXPECT_EQ(200, res3->status);
  23029. EXPECT_EQ(content, res3->body);
  23030. // Range request with future If-Range date: should get 200 (full content)
  23031. Headers h4 = {{"Range", "bytes=0-4"},
  23032. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  23033. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  23034. ASSERT_TRUE(res4);
  23035. EXPECT_EQ(200, res4->status);
  23036. EXPECT_EQ(content, res4->body);
  23037. #if defined(__APPLE__) || defined(__linux__)
  23038. // File replaced by one with an older mtime: should get 200 (full content)
  23039. const std::string replaced = "abcdefghij9876543210";
  23040. {
  23041. std::ofstream ofs(fname);
  23042. ofs << replaced;
  23043. ASSERT_TRUE(ofs.good());
  23044. }
  23045. struct timeval times[2];
  23046. times[0].tv_sec = time(nullptr);
  23047. times[0].tv_usec = 0;
  23048. times[1].tv_sec = time(nullptr) - 3600;
  23049. times[1].tv_usec = 0;
  23050. ASSERT_EQ(0, utimes(fname, times));
  23051. Headers h5 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  23052. auto res5 = cli.Get("/static/if_range_date_testfile.txt", h5);
  23053. ASSERT_TRUE(res5);
  23054. EXPECT_EQ(200, res5->status);
  23055. EXPECT_EQ(replaced, res5->body);
  23056. #endif
  23057. svr.stop();
  23058. t.join();
  23059. std::remove(fname);
  23060. }
  23061. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  23062. using namespace httplib;
  23063. const char *fname = "etag_malformed.txt";
  23064. const char *content = "malformed-etag";
  23065. {
  23066. std::ofstream ofs(fname);
  23067. ofs << content;
  23068. ASSERT_TRUE(ofs.good());
  23069. }
  23070. Server svr;
  23071. svr.set_mount_point("/static", ".");
  23072. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23073. svr.wait_until_ready();
  23074. Client cli(HOST, PORT);
  23075. // baseline: should get 200 and an ETag
  23076. auto res1 = cli.Get("/static/etag_malformed.txt");
  23077. ASSERT_TRUE(res1);
  23078. ASSERT_EQ(200, res1->status);
  23079. ASSERT_TRUE(res1->has_header("ETag"));
  23080. // Malformed ETag value (missing quotes) should be treated as non-matching
  23081. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  23082. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  23083. ASSERT_TRUE(res_bad);
  23084. EXPECT_EQ(200, res_bad->status);
  23085. // Whitespace-only header value should be considered invalid / non-matching
  23086. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  23087. "Host: localhost\r\n"
  23088. "If-None-Match: \r\n"
  23089. "Connection: close\r\n"
  23090. "\r\n";
  23091. std::string out;
  23092. ASSERT_TRUE(send_request(5, raw_req, &out));
  23093. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  23094. svr.stop();
  23095. t.join();
  23096. std::remove(fname);
  23097. }
  23098. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  23099. using namespace httplib;
  23100. const char *fname = "ims_invalid_format.txt";
  23101. const char *content = "ims-bad-format";
  23102. {
  23103. std::ofstream ofs(fname);
  23104. ofs << content;
  23105. ASSERT_TRUE(ofs.good());
  23106. }
  23107. Server svr;
  23108. svr.set_mount_point("/static", ".");
  23109. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23110. svr.wait_until_ready();
  23111. Client cli(HOST, PORT);
  23112. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  23113. ASSERT_TRUE(res1);
  23114. ASSERT_EQ(200, res1->status);
  23115. ASSERT_TRUE(res1->has_header("Last-Modified"));
  23116. // If-Modified-Since with invalid format should not result in 304
  23117. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  23118. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  23119. ASSERT_TRUE(res_bad);
  23120. EXPECT_EQ(200, res_bad->status);
  23121. // If-Range with invalid date format should be treated as mismatch -> full
  23122. // content (200)
  23123. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  23124. {"If-Range", "invalid-date"}};
  23125. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  23126. ASSERT_TRUE(res_ifrange);
  23127. EXPECT_EQ(200, res_ifrange->status);
  23128. svr.stop();
  23129. t.join();
  23130. std::remove(fname);
  23131. }
  23132. TEST(ETagTest, IfRangeWithMalformedETag) {
  23133. using namespace httplib;
  23134. const char *fname = "ifrange_malformed.txt";
  23135. const std::string content = "0123456789";
  23136. {
  23137. std::ofstream ofs(fname);
  23138. ofs << content;
  23139. ASSERT_TRUE(ofs.good());
  23140. }
  23141. Server svr;
  23142. svr.set_mount_point("/static", ".");
  23143. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23144. svr.wait_until_ready();
  23145. Client cli(HOST, PORT);
  23146. // First request: get ETag
  23147. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  23148. ASSERT_TRUE(res1);
  23149. ASSERT_EQ(200, res1->status);
  23150. ASSERT_TRUE(res1->has_header("ETag"));
  23151. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  23152. // full content (200)
  23153. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  23154. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  23155. ASSERT_TRUE(res2);
  23156. EXPECT_EQ(200, res2->status);
  23157. EXPECT_EQ(content, res2->body);
  23158. svr.stop();
  23159. t.join();
  23160. std::remove(fname);
  23161. }
  23162. TEST(ETagTest, ExtremeLargeDateValues) {
  23163. using namespace httplib;
  23164. const char *fname = "ims_extreme_date.txt";
  23165. const char *content = "ims-extreme-date";
  23166. {
  23167. std::ofstream ofs(fname);
  23168. ofs << content;
  23169. ASSERT_TRUE(ofs.good());
  23170. }
  23171. Server svr;
  23172. svr.set_mount_point("/static", ".");
  23173. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23174. svr.wait_until_ready();
  23175. Client cli(HOST, PORT);
  23176. auto res1 = cli.Get(std::string("/static/") + fname);
  23177. ASSERT_TRUE(res1);
  23178. ASSERT_EQ(200, res1->status);
  23179. ASSERT_TRUE(res1->has_header("Last-Modified"));
  23180. // Extremely large year that may overflow date parsing routines.
  23181. Headers h_large_date = {
  23182. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  23183. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  23184. ASSERT_TRUE(res_bad);
  23185. // Expect server to treat this as invalid/mismatch and return full content
  23186. EXPECT_EQ(200, res_bad->status);
  23187. // If-Range with extremely large date should be treated as mismatch -> full
  23188. // content (200)
  23189. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  23190. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  23191. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  23192. ASSERT_TRUE(res_ifrange);
  23193. EXPECT_EQ(200, res_ifrange->status);
  23194. svr.stop();
  23195. t.join();
  23196. std::remove(fname);
  23197. }
  23198. TEST(ETagTest, NegativeFileModificationTime) {
  23199. using namespace httplib;
  23200. const char *fname = "ims_negative_mtime.txt";
  23201. const std::string content = "negative-mtime";
  23202. {
  23203. std::ofstream ofs(fname);
  23204. ofs << content;
  23205. ASSERT_TRUE(ofs.good());
  23206. }
  23207. // Try to set file mtime to a negative value. This may fail on some
  23208. // platforms/filesystems; if it fails, the test will still verify server
  23209. // behaves safely by performing a regular conditional request.
  23210. #if defined(__APPLE__) || defined(__linux__)
  23211. bool set_negative = false;
  23212. do {
  23213. struct timeval times[2];
  23214. // access time: now
  23215. times[0].tv_sec = time(nullptr);
  23216. times[0].tv_usec = 0;
  23217. // modification time: negative (e.g., -1)
  23218. times[1].tv_sec = -1;
  23219. times[1].tv_usec = 0;
  23220. if (utimes(fname, times) == 0) { set_negative = true; }
  23221. } while (0);
  23222. #else
  23223. bool set_negative = false;
  23224. #endif
  23225. Server svr;
  23226. svr.set_mount_point("/static", ".");
  23227. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23228. svr.wait_until_ready();
  23229. Client cli(HOST, PORT);
  23230. auto res1 = cli.Get(std::string("/static/") + fname);
  23231. ASSERT_TRUE(res1);
  23232. ASSERT_EQ(200, res1->status);
  23233. bool has_last_modified = res1->has_header("Last-Modified");
  23234. std::string last_modified;
  23235. if (has_last_modified) {
  23236. last_modified = res1->get_header_value("Last-Modified");
  23237. }
  23238. if (set_negative) {
  23239. // If we successfully set a negative mtime, ensure server returns a
  23240. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  23241. // with an old date and ensure server handles it without crash.
  23242. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  23243. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  23244. ASSERT_TRUE(res2);
  23245. // Behavior may vary; at minimum ensure server responds (200 or 304).
  23246. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  23247. } else {
  23248. // Could not set negative mtime on this platform; fall back to verifying
  23249. // that normal invalid/malformed dates are treated safely (non-304).
  23250. Headers h_bad_date = {
  23251. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  23252. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  23253. ASSERT_TRUE(res_bad);
  23254. EXPECT_EQ(200, res_bad->status);
  23255. }
  23256. svr.stop();
  23257. t.join();
  23258. std::remove(fname);
  23259. }
  23260. //==============================================================================
  23261. // Integration Tests with Server
  23262. //==============================================================================
  23263. class SSEIntegrationTest : public ::testing::Test {
  23264. protected:
  23265. void SetUp() override {
  23266. stop_server_.store(false);
  23267. events_.clear();
  23268. server_ = httplib::detail::make_unique<Server>();
  23269. setup_server();
  23270. start_server();
  23271. }
  23272. void TearDown() override {
  23273. stop_server_.store(true);
  23274. event_cv_.notify_all();
  23275. server_->stop();
  23276. if (server_thread_.joinable()) { server_thread_.join(); }
  23277. }
  23278. void setup_server() {
  23279. // Simple SSE endpoint
  23280. server_->Get("/events", [this](const Request &req, Response &res) {
  23281. auto last_id = req.get_header_value("Last-Event-ID");
  23282. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  23283. res.set_chunked_content_provider(
  23284. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  23285. std::unique_lock<std::mutex> lock(event_mutex_);
  23286. if (event_cv_.wait_for(
  23287. lock, std::chrono::milliseconds(200), [this] {
  23288. return !events_.empty() || stop_server_.load();
  23289. })) {
  23290. if (stop_server_.load()) { return false; }
  23291. if (!events_.empty()) {
  23292. std::string event = events_.front();
  23293. events_.erase(events_.begin());
  23294. sink.write(event.data(), event.size());
  23295. return true;
  23296. }
  23297. }
  23298. return !stop_server_.load();
  23299. });
  23300. });
  23301. // Endpoint that returns error
  23302. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  23303. res.status = 500;
  23304. res.set_content("Internal Server Error", "text/plain");
  23305. });
  23306. // Endpoint for custom event types
  23307. server_->Get("/custom-events", [](const Request &, Response &res) {
  23308. res.set_chunked_content_provider(
  23309. "text/event-stream", [](size_t offset, DataSink &sink) {
  23310. if (offset == 0) {
  23311. std::string event = "event: update\ndata: updated\n\n"
  23312. "event: delete\ndata: deleted\n\n";
  23313. sink.write(event.data(), event.size());
  23314. }
  23315. return false; // End stream after sending
  23316. });
  23317. });
  23318. }
  23319. void start_server() {
  23320. port_ = server_->bind_to_any_port(HOST);
  23321. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23322. // Wait for server to start
  23323. while (!server_->is_running()) {
  23324. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23325. }
  23326. }
  23327. int get_port() const { return port_; }
  23328. void send_event(const std::string &event) {
  23329. std::lock_guard<std::mutex> lock(event_mutex_);
  23330. events_.push_back(event);
  23331. event_cv_.notify_all();
  23332. }
  23333. std::unique_ptr<Server> server_;
  23334. std::thread server_thread_;
  23335. std::mutex event_mutex_;
  23336. std::condition_variable event_cv_;
  23337. std::vector<std::string> events_;
  23338. std::atomic<bool> stop_server_{false};
  23339. std::string last_received_event_id_;
  23340. int port_ = 0;
  23341. };
  23342. //==============================================================================
  23343. // SSE Parser Tests
  23344. //==============================================================================
  23345. struct SSEParseResult {
  23346. std::vector<sse::SSEMessage> events;
  23347. std::vector<std::string> ids;
  23348. std::vector<int> retries;
  23349. bool ok = true;
  23350. std::string trace; // Every handler call in order
  23351. };
  23352. static SSEParseResult
  23353. sse_parse(const std::vector<std::string> &chunks,
  23354. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  23355. SSEParseResult r;
  23356. detail::SSEParser parser(
  23357. [&](const sse::SSEMessage &msg) {
  23358. r.events.push_back(msg);
  23359. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  23360. },
  23361. [&](const std::string &id) {
  23362. r.ids.push_back(id);
  23363. r.trace += "id[" + id + "]";
  23364. },
  23365. [&](int retry_ms) {
  23366. r.retries.push_back(retry_ms);
  23367. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  23368. },
  23369. max_event_length);
  23370. for (const auto &chunk : chunks) {
  23371. if (!parser.parse(chunk.data(), chunk.size())) {
  23372. r.ok = false;
  23373. break;
  23374. }
  23375. }
  23376. return r;
  23377. }
  23378. static SSEParseResult sse_parse(const std::string &stream) {
  23379. return sse_parse(std::vector<std::string>{stream});
  23380. }
  23381. TEST(SSEParserTest, SingleLineData) {
  23382. auto r = sse_parse("data: hello\n\n");
  23383. ASSERT_EQ(r.events.size(), 1u);
  23384. EXPECT_EQ(r.events[0].data, "hello");
  23385. EXPECT_EQ(r.events[0].event, "message");
  23386. }
  23387. TEST(SSEParserTest, MultiLineData) {
  23388. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  23389. ASSERT_EQ(r.events.size(), 1u);
  23390. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  23391. }
  23392. TEST(SSEParserTest, CustomEventType) {
  23393. auto r = sse_parse("event: update\ndata: payload\n\n");
  23394. ASSERT_EQ(r.events.size(), 1u);
  23395. EXPECT_EQ(r.events[0].event, "update");
  23396. EXPECT_EQ(r.events[0].data, "payload");
  23397. }
  23398. TEST(SSEParserTest, EventIdHandling) {
  23399. auto r = sse_parse("id: 12345\ndata: test\n\n");
  23400. ASSERT_EQ(r.events.size(), 1u);
  23401. EXPECT_EQ(r.events[0].id, "12345");
  23402. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  23403. }
  23404. TEST(SSEParserTest, EmptyEventId) {
  23405. auto r = sse_parse("id:\ndata: test\n\n");
  23406. ASSERT_EQ(r.events.size(), 1u);
  23407. EXPECT_EQ(r.events[0].id, "");
  23408. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  23409. }
  23410. TEST(SSEParserTest, CommentsIgnored) {
  23411. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  23412. ASSERT_EQ(r.events.size(), 1u);
  23413. EXPECT_EQ(r.events[0].data, "hello");
  23414. EXPECT_EQ(r.events[0].event, "message");
  23415. }
  23416. TEST(SSEParserTest, ColonInValue) {
  23417. auto r = sse_parse("data: hello:world:test\n\n");
  23418. ASSERT_EQ(r.events.size(), 1u);
  23419. EXPECT_EQ(r.events[0].data, "hello:world:test");
  23420. }
  23421. TEST(SSEParserTest, FieldNameOnly) {
  23422. // A line without a colon is a field name with an empty value
  23423. auto r = sse_parse("data\n\n");
  23424. ASSERT_EQ(r.events.size(), 1u);
  23425. EXPECT_EQ(r.events[0].data, "");
  23426. }
  23427. TEST(SSEParserTest, TrailingCarriageReturn) {
  23428. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  23429. ASSERT_EQ(r.events.size(), 1u);
  23430. EXPECT_EQ(r.events[0].event, "update");
  23431. EXPECT_EQ(r.events[0].data, "hello");
  23432. }
  23433. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  23434. auto r = sse_parse("data\r\n\r\n");
  23435. ASSERT_EQ(r.events.size(), 1u);
  23436. EXPECT_EQ(r.events[0].data, "");
  23437. }
  23438. TEST(SSEParserTest, CarriageReturnLineEnding) {
  23439. auto r = sse_parse("event: update\rdata: hello\r\r");
  23440. ASSERT_EQ(r.events.size(), 1u);
  23441. EXPECT_EQ(r.events[0].event, "update");
  23442. EXPECT_EQ(r.events[0].data, "hello");
  23443. }
  23444. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  23445. // Chunk boundaries fall inside every \r\n and right before the first one
  23446. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  23447. "\ndata: hello\r", "\n\r", "\n"});
  23448. ASSERT_EQ(r.events.size(), 1u);
  23449. EXPECT_EQ(r.events[0].event, "update");
  23450. EXPECT_EQ(r.events[0].data, "hello");
  23451. }
  23452. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  23453. // Only a BOM at the start of the stream is ignored
  23454. auto r = sse_parse("\xEF\xBB\xBF"
  23455. "data: first\n\n"
  23456. "\xEF\xBB\xBF"
  23457. "data: second\n\n");
  23458. ASSERT_EQ(r.events.size(), 1u);
  23459. EXPECT_EQ(r.events[0].data, "first");
  23460. }
  23461. TEST(SSEParserTest, UnknownFieldsIgnored) {
  23462. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  23463. ASSERT_EQ(r.events.size(), 1u);
  23464. EXPECT_EQ(r.events[0].data, "hello");
  23465. EXPECT_EQ(r.events[0].event, "message");
  23466. }
  23467. TEST(SSEParserTest, SpaceAfterColonOptional) {
  23468. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  23469. ASSERT_EQ(r.events.size(), 2u);
  23470. EXPECT_EQ(r.events[0].data, "hello");
  23471. EXPECT_EQ(r.events[1].data, "hello");
  23472. }
  23473. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  23474. // An event without data is not dispatched, and its type must not leak
  23475. // into the next event
  23476. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  23477. ASSERT_EQ(r.events.size(), 1u);
  23478. EXPECT_EQ(r.events[0].event, "message");
  23479. EXPECT_EQ(r.events[0].data, "hello");
  23480. }
  23481. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  23482. // Also when the empty field replaces an earlier type
  23483. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  23484. ASSERT_EQ(r.events.size(), 2u);
  23485. EXPECT_EQ(r.events[0].event, "message");
  23486. EXPECT_EQ(r.events[1].event, "message");
  23487. }
  23488. TEST(SSEParserTest, EventWithoutDataReportsId) {
  23489. auto r = sse_parse("id: 42\n\n");
  23490. EXPECT_TRUE(r.events.empty());
  23491. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23492. }
  23493. TEST(SSEParserTest, EmptyEventIdClearsId) {
  23494. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  23495. ASSERT_EQ(r.events.size(), 2u);
  23496. EXPECT_EQ(r.events[0].id, "1");
  23497. EXPECT_EQ(r.events[1].id, "");
  23498. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  23499. }
  23500. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  23501. // Ids that cannot be carried in a Last-Event-ID header
  23502. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  23503. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  23504. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23505. }
  23506. TEST(SSEParserTest, RetryDigitsOnly) {
  23507. auto r = sse_parse("retry: 1000\n");
  23508. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23509. // A value that is not all ASCII digits, or does not fit, is ignored
  23510. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  23511. EXPECT_TRUE(r.retries.empty());
  23512. }
  23513. TEST(SSEParserTest, CompleteEventParsing) {
  23514. auto r = sse_parse("event: notification\nid: evt-42\n"
  23515. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  23516. ASSERT_EQ(r.events.size(), 1u);
  23517. EXPECT_EQ(r.events[0].event, "notification");
  23518. EXPECT_EQ(r.events[0].id, "evt-42");
  23519. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  23520. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23521. }
  23522. TEST(SSEParserTest, IncompleteEventNotReported) {
  23523. // An event still waiting for its blank line when the stream ends is
  23524. // discarded per the SSE spec
  23525. auto r = sse_parse("id: 1\ndata: x\n");
  23526. EXPECT_TRUE(r.events.empty());
  23527. EXPECT_TRUE(r.ids.empty());
  23528. }
  23529. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23530. const std::vector<std::string> streams = {
  23531. "\xEF\xBB\xBF"
  23532. "data: bom\r\n\r\n",
  23533. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23534. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23535. };
  23536. for (const auto &stream : streams) {
  23537. auto expected = sse_parse(stream).trace;
  23538. ASSERT_FALSE(expected.empty());
  23539. for (size_t i = 0; i <= stream.size(); i++) {
  23540. auto r = sse_parse(
  23541. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23542. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23543. }
  23544. std::vector<std::string> bytes;
  23545. for (auto c : stream) {
  23546. bytes.emplace_back(1, c);
  23547. }
  23548. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23549. }
  23550. }
  23551. TEST(SSEParserTest, MaxEventLength) {
  23552. // A line still waiting for its end
  23553. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23554. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23555. // Data accumulated over the lines of one event
  23556. EXPECT_TRUE(
  23557. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23558. EXPECT_FALSE(
  23559. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23560. // 0 means no limit
  23561. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23562. // Events completed in the same chunk are still reported
  23563. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23564. EXPECT_FALSE(r.ok);
  23565. ASSERT_EQ(r.events.size(), 1u);
  23566. EXPECT_EQ(r.events[0].data, "a");
  23567. }
  23568. TEST(SSEMessageTest, Clear) {
  23569. sse::SSEMessage msg;
  23570. msg.event = "custom";
  23571. msg.data = "some data";
  23572. msg.id = "123";
  23573. msg.clear();
  23574. EXPECT_EQ(msg.event, "message");
  23575. EXPECT_EQ(msg.data, "");
  23576. EXPECT_EQ(msg.id, "");
  23577. }
  23578. //==============================================================================
  23579. // SSE Integration Tests
  23580. //==============================================================================
  23581. // Test: Successful connection and on_open callback
  23582. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23583. // Add a simple endpoint that sends one event and closes
  23584. server_->Get("/simple-event", [](const Request &, Response &res) {
  23585. res.set_chunked_content_provider(
  23586. "text/event-stream", [](size_t offset, DataSink &sink) {
  23587. if (offset == 0) {
  23588. std::string event = "data: hello\n\n";
  23589. sink.write(event.data(), event.size());
  23590. }
  23591. return false; // Close stream after sending
  23592. });
  23593. });
  23594. Client client("localhost", get_port());
  23595. sse::SSEClient sse(client, "/simple-event");
  23596. std::atomic<bool> open_called{false};
  23597. std::atomic<bool> message_received{false};
  23598. sse.on_open([&open_called]() { open_called.store(true); });
  23599. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23600. if (msg.data == "hello") { message_received.store(true); }
  23601. });
  23602. sse.set_reconnect_interval(100);
  23603. sse.set_max_reconnect_attempts(1);
  23604. // Start async
  23605. sse.start_async();
  23606. // Wait for message to be processed
  23607. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23608. sse.stop();
  23609. EXPECT_TRUE(open_called.load());
  23610. EXPECT_TRUE(message_received.load());
  23611. }
  23612. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23613. // A data line that never ends.
  23614. server_->Get("/endless-line", [](const Request &, Response &res) {
  23615. res.set_chunked_content_provider(
  23616. "text/event-stream", [](size_t offset, DataSink &sink) {
  23617. if (offset == 0) { sink.write("data: ", 6); }
  23618. std::string chunk(64 * 1024, 'A');
  23619. return sink.write(chunk.data(), chunk.size());
  23620. });
  23621. });
  23622. Client client("localhost", get_port());
  23623. sse::SSEClient sse(client, "/endless-line");
  23624. std::atomic<bool> too_long{false};
  23625. sse.on_error([&](Error err) {
  23626. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23627. });
  23628. sse.set_max_reconnect_attempts(1);
  23629. sse.start_async();
  23630. for (int i = 0; i < 500 && !too_long; i++) {
  23631. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23632. }
  23633. sse.stop();
  23634. EXPECT_TRUE(too_long);
  23635. }
  23636. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23637. // Far more in all than the client's payload limit below.
  23638. server_->Get("/many-events", [](const Request &, Response &res) {
  23639. res.set_chunked_content_provider(
  23640. "text/event-stream", [](size_t offset, DataSink &sink) {
  23641. if (offset == 0) {
  23642. std::string events;
  23643. for (int i = 0; i < 1000; i++) {
  23644. events += "data: message\n\n";
  23645. }
  23646. sink.write(events.data(), events.size());
  23647. }
  23648. return false;
  23649. });
  23650. });
  23651. Client client("localhost", get_port());
  23652. client.set_payload_max_length(1024);
  23653. sse::SSEClient sse(client, "/many-events");
  23654. std::atomic<int> messages{0};
  23655. std::atomic<bool> too_large{false};
  23656. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23657. sse.on_error([&](Error err) {
  23658. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23659. });
  23660. sse.set_max_reconnect_attempts(1);
  23661. sse.start_async();
  23662. for (int i = 0; i < 500 && messages < 1000; i++) {
  23663. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23664. }
  23665. sse.stop();
  23666. EXPECT_GE(messages.load(), 1000);
  23667. EXPECT_FALSE(too_large);
  23668. }
  23669. // Test: on_message callback
  23670. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23671. // Endpoint that sends multiple events then closes
  23672. server_->Get("/multi-event", [](const Request &, Response &res) {
  23673. res.set_chunked_content_provider(
  23674. "text/event-stream", [](size_t offset, DataSink &sink) {
  23675. if (offset == 0) {
  23676. std::string events = "data: message1\n\ndata: message2\n\n";
  23677. sink.write(events.data(), events.size());
  23678. }
  23679. return false;
  23680. });
  23681. });
  23682. Client client("localhost", get_port());
  23683. sse::SSEClient sse(client, "/multi-event");
  23684. std::vector<std::string> received_messages;
  23685. std::mutex messages_mutex;
  23686. sse.on_message([&](const sse::SSEMessage &msg) {
  23687. std::lock_guard<std::mutex> lock(messages_mutex);
  23688. received_messages.push_back(msg.data);
  23689. });
  23690. sse.set_reconnect_interval(100);
  23691. sse.set_max_reconnect_attempts(1);
  23692. sse.start_async();
  23693. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23694. sse.stop();
  23695. std::lock_guard<std::mutex> lock(messages_mutex);
  23696. EXPECT_GE(received_messages.size(), 2u);
  23697. if (received_messages.size() >= 2) {
  23698. EXPECT_EQ(received_messages[0], "message1");
  23699. EXPECT_EQ(received_messages[1], "message2");
  23700. }
  23701. }
  23702. // Test: on_event for specific types
  23703. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23704. Client client("localhost", get_port());
  23705. sse::SSEClient sse(client, "/custom-events");
  23706. std::atomic<bool> update_received{false};
  23707. std::atomic<bool> delete_received{false};
  23708. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23709. if (msg.data == "updated") { update_received.store(true); }
  23710. });
  23711. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23712. if (msg.data == "deleted") { delete_received.store(true); }
  23713. });
  23714. sse.set_max_reconnect_attempts(1);
  23715. sse.start_async();
  23716. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23717. sse.stop();
  23718. EXPECT_TRUE(update_received.load());
  23719. EXPECT_TRUE(delete_received.load());
  23720. }
  23721. // Test: on_error callback on connection failure
  23722. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23723. // Connect to a non-existent port
  23724. Client client("localhost", 59999);
  23725. sse::SSEClient sse(client, "/events");
  23726. std::atomic<bool> error_called{false};
  23727. Error received_error = Error::Success;
  23728. sse.on_error([&](Error err) {
  23729. error_called.store(true);
  23730. received_error = err;
  23731. });
  23732. sse.set_reconnect_interval(50);
  23733. sse.set_max_reconnect_attempts(1);
  23734. sse.start_async();
  23735. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23736. sse.stop();
  23737. EXPECT_TRUE(error_called.load());
  23738. EXPECT_NE(received_error, Error::Success);
  23739. }
  23740. // Test: Last-Event-ID header sent on reconnect
  23741. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23742. // Endpoint that sends event with ID
  23743. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23744. res.set_chunked_content_provider(
  23745. "text/event-stream", [](size_t offset, DataSink &sink) {
  23746. if (offset == 0) {
  23747. std::string event = "id: evt-123\ndata: test\n\n";
  23748. sink.write(event.data(), event.size());
  23749. }
  23750. return false;
  23751. });
  23752. });
  23753. Client client("localhost", get_port());
  23754. sse::SSEClient sse(client, "/event-with-id");
  23755. std::atomic<bool> id_received{false};
  23756. sse.on_message([&](const sse::SSEMessage &msg) {
  23757. if (!msg.id.empty()) { id_received.store(true); }
  23758. });
  23759. sse.set_reconnect_interval(100);
  23760. sse.set_max_reconnect_attempts(1);
  23761. sse.start_async();
  23762. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23763. sse.stop();
  23764. EXPECT_TRUE(id_received.load());
  23765. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23766. }
  23767. // Test: last_event_id() read from another thread while start_async() runs
  23768. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23769. // Ids of every length up to 200, so the stored id keeps changing size
  23770. server_->Get("/many-ids", [](const Request &, Response &res) {
  23771. res.set_chunked_content_provider(
  23772. "text/event-stream", [](size_t offset, DataSink &sink) {
  23773. if (offset == 0) {
  23774. std::string events;
  23775. for (size_t i = 0; i < 2000; i++) {
  23776. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23777. events += "data: x\n\n";
  23778. }
  23779. events += "id: end\ndata: x\n\n";
  23780. sink.write(events.data(), events.size());
  23781. }
  23782. return false;
  23783. });
  23784. });
  23785. Client client("localhost", get_port());
  23786. sse::SSEClient sse(client, "/many-ids");
  23787. // Wait out the rest of the test rather than replay the stream
  23788. sse.set_reconnect_interval(10000);
  23789. sse.set_max_reconnect_attempts(1);
  23790. sse.start_async();
  23791. auto well_formed = true;
  23792. std::string id;
  23793. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23794. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23795. id = sse.last_event_id();
  23796. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23797. well_formed = false;
  23798. }
  23799. }
  23800. sse.stop();
  23801. EXPECT_TRUE(well_formed);
  23802. EXPECT_EQ(sse.last_event_id(), "end");
  23803. }
  23804. // Test: Manual stop
  23805. TEST_F(SSEIntegrationTest, ManualStop) {
  23806. // Endpoint that sends one event and stays open briefly. The server outlives
  23807. // this test body, so the provider uses the fixture's flag, not a local.
  23808. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23809. res.set_chunked_content_provider(
  23810. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23811. if (offset == 0) {
  23812. std::string event = "data: connected\n\n";
  23813. sink.write(event.data(), event.size());
  23814. }
  23815. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23816. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23817. }
  23818. return false;
  23819. });
  23820. });
  23821. Client client("localhost", get_port());
  23822. sse::SSEClient sse(client, "/stay-open");
  23823. std::atomic<bool> connected{false};
  23824. sse.on_open([&connected]() { connected.store(true); });
  23825. sse.set_reconnect_interval(100);
  23826. sse.set_max_reconnect_attempts(1);
  23827. sse.start_async();
  23828. // Wait for connection to establish
  23829. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23830. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23831. }
  23832. EXPECT_TRUE(connected.load());
  23833. EXPECT_TRUE(sse.is_connected());
  23834. // Signal handler to stop
  23835. stop_server_.store(true);
  23836. // Stop SSE client
  23837. sse.stop();
  23838. EXPECT_FALSE(sse.is_connected());
  23839. }
  23840. // Sends one event, then nothing until stop is set
  23841. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23842. return [&stop](const Request &, Response &res) {
  23843. res.set_chunked_content_provider(
  23844. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23845. if (offset == 0) {
  23846. std::string event = "data: hello\n\n";
  23847. sink.write(event.data(), event.size());
  23848. }
  23849. while (!stop.load()) {
  23850. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23851. }
  23852. return false;
  23853. });
  23854. };
  23855. }
  23856. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23857. static void check_stop_interrupts_blocked_read(Client &client) {
  23858. client.set_read_timeout(30, 0);
  23859. for (auto by_destructor : {false, true}) {
  23860. std::atomic<bool> received{false};
  23861. std::chrono::steady_clock::time_point start;
  23862. {
  23863. sse::SSEClient sse(client, "/idle-stream");
  23864. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23865. sse.start_async();
  23866. for (int i = 0; i < 500 && !received.load(); ++i) {
  23867. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23868. }
  23869. ASSERT_TRUE(received.load());
  23870. // Let the client block in the next read
  23871. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23872. start = std::chrono::steady_clock::now();
  23873. if (!by_destructor) { sse.stop(); }
  23874. }
  23875. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23876. std::chrono::seconds(2));
  23877. }
  23878. }
  23879. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23880. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23881. Client client("localhost", get_port());
  23882. check_stop_interrupts_blocked_read(client);
  23883. }
  23884. #ifdef CPPHTTPLIB_SSL_ENABLED
  23885. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23886. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23887. std::atomic<bool> done{false};
  23888. svr.Get("/idle-stream", idle_event_stream(done));
  23889. auto port = svr.bind_to_any_port(HOST);
  23890. std::thread t([&] { svr.listen_after_bind(); });
  23891. auto se = detail::scope_exit([&] {
  23892. done.store(true);
  23893. svr.stop();
  23894. t.join();
  23895. });
  23896. svr.wait_until_ready();
  23897. Client client("https://localhost:" + std::to_string(port));
  23898. client.enable_server_certificate_verification(false);
  23899. check_stop_interrupts_blocked_read(client);
  23900. }
  23901. #endif
  23902. // Test: SSEClient with custom headers
  23903. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23904. // Setup a server endpoint that checks for custom header
  23905. std::atomic<bool> header_received{false};
  23906. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23907. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23908. header_received.store(true);
  23909. }
  23910. res.set_chunked_content_provider("text/event-stream",
  23911. [](size_t, DataSink &) { return false; });
  23912. });
  23913. Client client("localhost", get_port());
  23914. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23915. sse::SSEClient sse(client, "/header-check", headers);
  23916. sse.set_max_reconnect_attempts(1);
  23917. sse.start_async();
  23918. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23919. sse.stop();
  23920. EXPECT_TRUE(header_received.load());
  23921. }
  23922. // Test: Reconnect interval configuration
  23923. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23924. Client client("localhost", get_port());
  23925. sse::SSEClient sse(client, "/events");
  23926. auto &result = sse.set_reconnect_interval(500);
  23927. // Builder pattern should return reference to self
  23928. EXPECT_EQ(&result, &sse);
  23929. }
  23930. // Test: Max reconnect attempts
  23931. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23932. // Connect to non-existent port to force reconnects
  23933. Client client("localhost", 59998);
  23934. sse::SSEClient sse(client, "/events");
  23935. std::atomic<int> error_count{0};
  23936. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23937. sse.set_reconnect_interval(50);
  23938. sse.set_max_reconnect_attempts(2);
  23939. auto start = std::chrono::steady_clock::now();
  23940. sse.start(); // Blocking call
  23941. auto end = std::chrono::steady_clock::now();
  23942. // Should have stopped after 2 failed attempts
  23943. EXPECT_GE(error_count.load(), 2);
  23944. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23945. auto duration =
  23946. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23947. #ifdef _WIN32
  23948. // Windows is much slower for socket connection failures
  23949. EXPECT_LT(duration.count(), 7000);
  23950. #else
  23951. EXPECT_LT(duration.count(), 1000);
  23952. #endif
  23953. }
  23954. // Test: Multi-line data in integration
  23955. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23956. // Endpoint with multi-line data
  23957. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23958. res.set_chunked_content_provider(
  23959. "text/event-stream", [](size_t offset, DataSink &sink) {
  23960. if (offset == 0) {
  23961. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23962. sink.write(event.data(), event.size());
  23963. }
  23964. return false;
  23965. });
  23966. });
  23967. Client client("localhost", get_port());
  23968. sse::SSEClient sse(client, "/multiline-data");
  23969. std::string received_data;
  23970. std::mutex data_mutex;
  23971. sse.on_message([&](const sse::SSEMessage &msg) {
  23972. std::lock_guard<std::mutex> lock(data_mutex);
  23973. received_data = msg.data;
  23974. });
  23975. sse.set_reconnect_interval(100);
  23976. sse.set_max_reconnect_attempts(1);
  23977. sse.start_async();
  23978. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23979. sse.stop();
  23980. std::lock_guard<std::mutex> lock(data_mutex);
  23981. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23982. }
  23983. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23984. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23985. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23986. DataSink &sink) {
  23987. if (offset == 0) {
  23988. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23989. sink.write(events.data(), events.size());
  23990. }
  23991. return false;
  23992. });
  23993. });
  23994. Client client("localhost", get_port());
  23995. sse::SSEClient sse(client, "/empty-data-lines");
  23996. std::mutex mutex;
  23997. std::condition_variable cv;
  23998. std::vector<std::string> received;
  23999. sse.on_message([&](const sse::SSEMessage &msg) {
  24000. std::lock_guard<std::mutex> lock(mutex);
  24001. received.push_back(msg.data);
  24002. cv.notify_all();
  24003. });
  24004. sse.set_max_reconnect_attempts(1);
  24005. sse.start_async();
  24006. {
  24007. std::unique_lock<std::mutex> lock(mutex);
  24008. cv.wait_for(lock, std::chrono::seconds(2),
  24009. [&] { return received.size() >= 3; });
  24010. }
  24011. sse.stop();
  24012. ASSERT_GE(received.size(), 3u);
  24013. EXPECT_EQ(received[0], "");
  24014. EXPECT_EQ(received[1], "\nhello");
  24015. EXPECT_EQ(received[2], "");
  24016. }
  24017. // Test: Auto-reconnect after server disconnection
  24018. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  24019. std::atomic<int> connection_count{0};
  24020. std::atomic<int> message_count{0};
  24021. // Endpoint that sends one event and closes, forcing reconnect
  24022. server_->Get("/reconnect-test",
  24023. [&connection_count](const Request &, Response &res) {
  24024. connection_count.fetch_add(1);
  24025. res.set_chunked_content_provider(
  24026. "text/event-stream", [](size_t offset, DataSink &sink) {
  24027. if (offset == 0) {
  24028. std::string event = "data: hello\n\n";
  24029. sink.write(event.data(), event.size());
  24030. }
  24031. return false; // Close connection after sending
  24032. });
  24033. });
  24034. Client client("localhost", get_port());
  24035. sse::SSEClient sse(client, "/reconnect-test");
  24036. sse.on_message([&message_count](const sse::SSEMessage &) {
  24037. message_count.fetch_add(1);
  24038. });
  24039. sse.set_reconnect_interval(100);
  24040. sse.set_max_reconnect_attempts(3);
  24041. sse.start_async();
  24042. // Wait long enough for multiple reconnects
  24043. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  24044. sse.stop();
  24045. // Should have connected multiple times (initial + reconnects)
  24046. EXPECT_GE(connection_count.load(), 2);
  24047. // Should have received messages from multiple connections
  24048. EXPECT_GE(message_count.load(), 2);
  24049. }
  24050. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  24051. std::atomic<int> connection_count{0};
  24052. // Neither Content-Length nor chunked: the close ends the stream
  24053. server_->Get("/close-delimited",
  24054. [&connection_count](const Request &, Response &res) {
  24055. connection_count.fetch_add(1);
  24056. res.set_content_provider(
  24057. "text/event-stream", [](size_t offset, DataSink &sink) {
  24058. if (offset == 0) {
  24059. std::string event = "data: hello\n\n";
  24060. sink.write(event.data(), event.size());
  24061. } else {
  24062. sink.done();
  24063. }
  24064. return true;
  24065. });
  24066. });
  24067. Client client("localhost", get_port());
  24068. sse::SSEClient sse(client, "/close-delimited");
  24069. std::atomic<int> error_count{0};
  24070. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  24071. sse.set_reconnect_interval(100);
  24072. sse.start_async();
  24073. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  24074. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24075. }
  24076. sse.stop();
  24077. // Reconnects as after any end of the stream, but reports no error
  24078. EXPECT_GE(connection_count.load(), 2);
  24079. EXPECT_EQ(0, error_count.load());
  24080. }
  24081. // Test: A retry field of all ASCII digits sets the reconnection time
  24082. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  24083. std::mutex mutex;
  24084. std::condition_variable cv;
  24085. std::vector<std::chrono::steady_clock::time_point> connected_at;
  24086. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  24087. {
  24088. std::lock_guard<std::mutex> lock(mutex);
  24089. connected_at.push_back(std::chrono::steady_clock::now());
  24090. cv.notify_all();
  24091. }
  24092. res.set_chunked_content_provider(
  24093. "text/event-stream", [](size_t offset, DataSink &sink) {
  24094. if (offset == 0) {
  24095. std::string event = "retry: 0\ndata: hello\n\n";
  24096. sink.write(event.data(), event.size());
  24097. }
  24098. return false;
  24099. });
  24100. });
  24101. Client client("localhost", get_port());
  24102. sse::SSEClient sse(client, "/zero-retry");
  24103. sse.set_reconnect_interval(10000);
  24104. sse.start_async();
  24105. {
  24106. std::unique_lock<std::mutex> lock(mutex);
  24107. cv.wait_for(lock, std::chrono::seconds(5),
  24108. [&] { return connected_at.size() >= 2; });
  24109. }
  24110. sse.stop();
  24111. // The server-supplied interval is applied, but never below 100ms, so
  24112. // "retry: 0" does not cause a busy reconnect loop
  24113. std::lock_guard<std::mutex> lock(mutex);
  24114. ASSERT_GE(connected_at.size(), 2u);
  24115. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  24116. connected_at[1] - connected_at[0])
  24117. .count();
  24118. EXPECT_GE(interval_ms, 100);
  24119. }
  24120. // Test: Last-Event-ID sent on reconnect
  24121. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  24122. std::atomic<int> connection_count{0};
  24123. std::vector<std::string> received_last_event_ids;
  24124. std::mutex id_mutex;
  24125. // Endpoint that checks Last-Event-ID header and sends event with ID
  24126. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  24127. int conn = connection_count.fetch_add(1);
  24128. // Capture the Last-Event-ID header from each connection
  24129. {
  24130. std::lock_guard<std::mutex> lock(id_mutex);
  24131. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  24132. }
  24133. res.set_chunked_content_provider(
  24134. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  24135. if (offset == 0) {
  24136. std::string event =
  24137. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  24138. sink.write(event.data(), event.size());
  24139. }
  24140. return false;
  24141. });
  24142. });
  24143. Client client("localhost", get_port());
  24144. sse::SSEClient sse(client, "/reconnect-with-id");
  24145. sse.set_reconnect_interval(100);
  24146. sse.set_max_reconnect_attempts(3);
  24147. sse.start_async();
  24148. // Wait for at least 2 connections
  24149. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  24150. sse.stop();
  24151. // Verify behavior
  24152. std::lock_guard<std::mutex> lock(id_mutex);
  24153. EXPECT_GE(received_last_event_ids.size(), 2u);
  24154. // First connection should have no Last-Event-ID
  24155. if (!received_last_event_ids.empty()) {
  24156. EXPECT_EQ(received_last_event_ids[0], "");
  24157. }
  24158. // Second connection should have Last-Event-ID from first connection
  24159. if (received_last_event_ids.size() >= 2) {
  24160. EXPECT_EQ(received_last_event_ids[1], "event-0");
  24161. }
  24162. }
  24163. // Test: set_headers updates headers used on reconnect
  24164. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  24165. std::vector<std::string> received_tokens;
  24166. std::mutex token_mutex;
  24167. // Endpoint that captures Authorization header
  24168. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  24169. {
  24170. std::lock_guard<std::mutex> lock(token_mutex);
  24171. received_tokens.push_back(req.get_header_value("Authorization"));
  24172. }
  24173. res.set_chunked_content_provider(
  24174. "text/event-stream", [](size_t offset, DataSink &sink) {
  24175. if (offset == 0) {
  24176. std::string event = "data: hello\n\n";
  24177. sink.write(event.data(), event.size());
  24178. }
  24179. return false; // Close connection to trigger reconnect
  24180. });
  24181. });
  24182. Client client("localhost", get_port());
  24183. Headers headers = {{"Authorization", "Bearer old-token"}};
  24184. sse::SSEClient sse(client, "/auth-check", headers);
  24185. // Update headers on each successful connection
  24186. sse.on_open(
  24187. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  24188. sse.set_reconnect_interval(100);
  24189. sse.set_max_reconnect_attempts(3);
  24190. sse.start_async();
  24191. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  24192. sse.stop();
  24193. std::lock_guard<std::mutex> lock(token_mutex);
  24194. ASSERT_GE(received_tokens.size(), 2u);
  24195. // First connection uses original header
  24196. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  24197. // Second connection uses updated header from set_headers
  24198. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  24199. }
  24200. // Test: 401 allows reconnection (so on_error can refresh headers)
  24201. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  24202. std::atomic<int> connection_count{0};
  24203. // Endpoint: returns 401 on first attempt, 200 on second
  24204. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  24205. int conn = connection_count.fetch_add(1);
  24206. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  24207. res.status = StatusCode::Unauthorized_401;
  24208. res.set_content("Unauthorized", "text/plain");
  24209. return;
  24210. }
  24211. res.set_chunked_content_provider(
  24212. "text/event-stream", [](size_t offset, DataSink &sink) {
  24213. if (offset == 0) {
  24214. std::string event = "data: authenticated\n\n";
  24215. sink.write(event.data(), event.size());
  24216. }
  24217. return false;
  24218. });
  24219. });
  24220. Client client("localhost", get_port());
  24221. Headers headers = {{"Authorization", "Bearer expired"}};
  24222. sse::SSEClient sse(client, "/auth-retry", headers);
  24223. std::atomic<bool> message_received{false};
  24224. // Refresh token on error
  24225. sse.on_error(
  24226. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  24227. sse.on_message([&](const sse::SSEMessage &msg) {
  24228. if (msg.data == "authenticated") { message_received.store(true); }
  24229. });
  24230. sse.set_reconnect_interval(100);
  24231. sse.set_max_reconnect_attempts(3);
  24232. sse.start_async();
  24233. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  24234. sse.stop();
  24235. // Should have reconnected after 401 and succeeded with new token
  24236. EXPECT_GE(connection_count.load(), 2);
  24237. EXPECT_TRUE(message_received.load());
  24238. }
  24239. TEST(Issue2318Test, EmptyHostString) {
  24240. {
  24241. httplib::Client cli_empty("", PORT);
  24242. auto res = cli_empty.Get("/");
  24243. ASSERT_FALSE(res);
  24244. EXPECT_EQ(httplib::Error::Connection, res.error());
  24245. }
  24246. {
  24247. httplib::Client cli(" ", PORT);
  24248. auto res = cli.Get("/");
  24249. ASSERT_FALSE(res);
  24250. EXPECT_EQ(httplib::Error::Connection, res.error());
  24251. }
  24252. }
  24253. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  24254. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  24255. Server svr;
  24256. // Set a small payload limit (1KB)
  24257. svr.set_payload_max_length(1024);
  24258. svr.Post("/test", [&](const Request &req, Response &res) {
  24259. res.set_content("Body size: " + std::to_string(req.body.size()),
  24260. "text/plain");
  24261. });
  24262. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  24263. auto se = detail::scope_exit([&] {
  24264. svr.stop();
  24265. listen_thread.join();
  24266. });
  24267. svr.wait_until_ready();
  24268. // Create data that compresses well but exceeds limit when decompressed
  24269. // 8KB of repeated null bytes compresses to a very small size
  24270. std::string original_data(8 * 1024, '\0');
  24271. // Compress the data using gzip
  24272. std::string compressed_data;
  24273. detail::gzip_compressor compressor;
  24274. compressor.compress(original_data.data(), original_data.size(), true,
  24275. [&](const char *data, size_t size) {
  24276. compressed_data.append(data, size);
  24277. return true;
  24278. });
  24279. // Verify compression worked (compressed should be much smaller)
  24280. ASSERT_LT(compressed_data.size(), original_data.size());
  24281. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  24282. // Send compressed data with Content-Encoding: gzip
  24283. Client cli(HOST, PORT);
  24284. Headers headers = {{"Content-Encoding", "gzip"}};
  24285. auto res =
  24286. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  24287. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  24288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24289. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  24290. }
  24291. #endif
  24292. // ============================================================================
  24293. // OpenSSL-Specific Tests
  24294. // ============================================================================
  24295. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24296. X509 *readCertificate(const std::string &strFileName) {
  24297. std::ifstream inStream(strFileName);
  24298. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  24299. std::istreambuf_iterator<char>());
  24300. if (strCertPEM.empty()) return (nullptr);
  24301. BIO *pbCert = BIO_new(BIO_s_mem());
  24302. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  24303. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  24304. BIO_free(pbCert);
  24305. return (pCert);
  24306. }
  24307. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  24308. std::ifstream inStream(strFileName);
  24309. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  24310. std::istreambuf_iterator<char>());
  24311. if (strPrivateKeyPEM.empty()) return (nullptr);
  24312. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  24313. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  24314. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  24315. BIO_free(pbPrivKey);
  24316. return (pPrivateKey);
  24317. }
  24318. TEST(BindServerTest, UpdateCerts) {
  24319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24320. int port = svr.bind_to_any_port("0.0.0.0");
  24321. ASSERT_TRUE(svr.is_valid());
  24322. ASSERT_TRUE(port > 0);
  24323. X509 *cert = readCertificate(SERVER_CERT_FILE);
  24324. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  24325. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  24326. ASSERT_TRUE(cert != nullptr);
  24327. ASSERT_TRUE(ca_cert != nullptr);
  24328. ASSERT_TRUE(key != nullptr);
  24329. X509_STORE *cert_store = X509_STORE_new();
  24330. X509_STORE_add_cert(cert_store, ca_cert);
  24331. // svr.update_certs(cert, key, cert_store); // deprecated
  24332. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  24333. CLIENT_CA_CERT_FILE);
  24334. ASSERT_TRUE(svr.is_valid());
  24335. svr.stop();
  24336. X509_STORE_free(cert_store);
  24337. X509_free(cert);
  24338. X509_free(ca_cert);
  24339. EVP_PKEY_free(key);
  24340. }
  24341. // Test that update_certs() updates client CA list correctly
  24342. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  24343. // Start with file-based constructor
  24344. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24345. ASSERT_TRUE(svr.is_valid());
  24346. // Initially no client CA list should be set
  24347. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24348. ASSERT_TRUE(ssl_ctx != nullptr);
  24349. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  24350. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  24351. // Now update with client CA (PEM string)
  24352. std::string cert_pem, key_pem, ca_pem;
  24353. read_file(SERVER_CERT_FILE, cert_pem);
  24354. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  24355. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  24356. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  24357. ASSERT_TRUE(svr.is_valid());
  24358. // Now client CA list should be set
  24359. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  24360. ASSERT_TRUE(ca_list_after != nullptr);
  24361. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  24362. }
  24363. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  24364. // Test that the file-path SSLServer constructor properly sets the client CA
  24365. // list that is sent to clients during the TLS handshake (CertificateRequest)
  24366. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24367. ASSERT_TRUE(svr.is_valid());
  24368. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24369. ASSERT_TRUE(ssl_ctx != nullptr);
  24370. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  24371. ASSERT_TRUE(ca_list != nullptr);
  24372. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  24373. }
  24374. #endif
  24375. // ============================================================================
  24376. // MbedTLS-Specific Tests
  24377. // ============================================================================
  24378. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  24379. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  24380. using namespace httplib::tls;
  24381. // Track if callback was invoked
  24382. bool callback_invoked = false;
  24383. // The callback receives void* ctx which is actually MbedTlsContext*
  24384. // We can access the mbedtls_ssl_config via the context
  24385. auto setup_callback = [&callback_invoked](void *ctx) {
  24386. callback_invoked = true;
  24387. // Cast to MbedTlsContext* to access the ssl config
  24388. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  24389. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  24390. // Use static variables to hold certificate data (simplified for test)
  24391. static mbedtls_x509_crt own_cert;
  24392. static mbedtls_pk_context own_key;
  24393. static mbedtls_x509_crt ca_chain;
  24394. static bool initialized = false;
  24395. if (!initialized) {
  24396. mbedtls_x509_crt_init(&own_cert);
  24397. mbedtls_pk_init(&own_key);
  24398. mbedtls_x509_crt_init(&ca_chain);
  24399. // Load server certificate
  24400. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  24401. return false;
  24402. }
  24403. // Load server private key.
  24404. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  24405. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  24406. #if MBEDTLS_VERSION_MAJOR == 3
  24407. ,
  24408. mbedtls_ctr_drbg_random, nullptr
  24409. #endif
  24410. ) != 0) {
  24411. return false;
  24412. }
  24413. // Load CA chain for client verification
  24414. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  24415. return false;
  24416. }
  24417. initialized = true;
  24418. }
  24419. // Configure the SSL config
  24420. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  24421. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  24422. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  24423. // Set minimum TLS version using mbedTLS native API
  24424. #if MBEDTLS_VERSION_MAJOR >= 3
  24425. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  24426. #else
  24427. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  24428. MBEDTLS_SSL_MINOR_VERSION_3);
  24429. #endif
  24430. return true;
  24431. };
  24432. SSLServer svr(setup_callback);
  24433. ASSERT_TRUE(svr.is_valid());
  24434. ASSERT_TRUE(callback_invoked);
  24435. svr.Get("/test", [&](const Request &req, Response &res) {
  24436. res.set_content("test", "text/plain");
  24437. auto cert = req.peer_cert();
  24438. ASSERT_TRUE(static_cast<bool>(cert));
  24439. auto common_name = cert.subject_cn();
  24440. EXPECT_EQ("Common Name", common_name);
  24441. });
  24442. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24443. auto se = detail::scope_exit([&] {
  24444. svr.stop();
  24445. t.join();
  24446. ASSERT_FALSE(svr.is_running());
  24447. });
  24448. svr.wait_until_ready();
  24449. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  24450. cli.enable_server_certificate_verification(false);
  24451. cli.set_connection_timeout(30);
  24452. auto res = cli.Get("/test");
  24453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24454. ASSERT_EQ(StatusCode::OK_200, res->status);
  24455. }
  24456. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  24457. // context (owning mbedtls_ssl_config) before shutting down a still-open
  24458. // keep-alive SSL session, which reads through that config in
  24459. // mbedtls_ssl_close_notify.
  24460. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  24461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24462. ASSERT_TRUE(svr.is_valid());
  24463. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  24464. res.set_content("test", "text/plain");
  24465. });
  24466. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24467. auto se = detail::scope_exit([&] {
  24468. svr.stop();
  24469. t.join();
  24470. ASSERT_FALSE(svr.is_running());
  24471. });
  24472. svr.wait_until_ready();
  24473. {
  24474. SSLClient cli(HOST, PORT);
  24475. cli.enable_server_certificate_verification(false);
  24476. cli.set_keep_alive(true);
  24477. auto res = cli.Get("/test");
  24478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24479. ASSERT_EQ(StatusCode::OK_200, res->status);
  24480. // cli is destructed here with the keep-alive SSL session still open.
  24481. }
  24482. }
  24483. #endif
  24484. // WebSocket Tests
  24485. TEST(WebSocketTest, RSVBitsMustBeZero) {
  24486. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  24487. // defining the meaning of these bits has been negotiated.
  24488. auto make_frame = [](uint8_t first_byte) {
  24489. std::string frame;
  24490. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  24491. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  24492. frame += "Hello";
  24493. return frame;
  24494. };
  24495. // RSV1 set (0x40)
  24496. {
  24497. detail::BufferStream strm;
  24498. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  24499. ws::Opcode opcode;
  24500. std::string payload;
  24501. bool fin;
  24502. EXPECT_EQ(
  24503. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24504. ws::impl::FrameRead::ProtocolError);
  24505. }
  24506. // RSV2 set (0x20)
  24507. {
  24508. detail::BufferStream strm;
  24509. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  24510. ws::Opcode opcode;
  24511. std::string payload;
  24512. bool fin;
  24513. EXPECT_EQ(
  24514. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24515. ws::impl::FrameRead::ProtocolError);
  24516. }
  24517. // RSV3 set (0x10)
  24518. {
  24519. detail::BufferStream strm;
  24520. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  24521. ws::Opcode opcode;
  24522. std::string payload;
  24523. bool fin;
  24524. EXPECT_EQ(
  24525. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24526. ws::impl::FrameRead::ProtocolError);
  24527. }
  24528. // No RSV bits set - should succeed
  24529. {
  24530. detail::BufferStream strm;
  24531. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24532. ws::Opcode opcode;
  24533. std::string payload;
  24534. bool fin;
  24535. EXPECT_EQ(
  24536. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24537. ws::impl::FrameRead::Ok);
  24538. EXPECT_EQ(ws::Opcode::Text, opcode);
  24539. EXPECT_EQ("Hello", payload);
  24540. EXPECT_TRUE(fin);
  24541. }
  24542. }
  24543. TEST(WebSocketTest, ControlFrameValidation) {
  24544. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24545. // payload length <= 125.
  24546. // Ping with FIN=0 - must be rejected
  24547. {
  24548. detail::BufferStream strm;
  24549. std::string frame;
  24550. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24551. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24552. strm.write(frame.data(), frame.size());
  24553. ws::Opcode opcode;
  24554. std::string payload;
  24555. bool fin;
  24556. EXPECT_EQ(
  24557. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24558. ws::impl::FrameRead::ProtocolError);
  24559. }
  24560. // Close with FIN=0 - must be rejected
  24561. {
  24562. detail::BufferStream strm;
  24563. std::string frame;
  24564. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24565. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24566. strm.write(frame.data(), frame.size());
  24567. ws::Opcode opcode;
  24568. std::string payload;
  24569. bool fin;
  24570. EXPECT_EQ(
  24571. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24572. ws::impl::FrameRead::ProtocolError);
  24573. }
  24574. // Ping with payload_len=126 (extended length) - must be rejected
  24575. {
  24576. detail::BufferStream strm;
  24577. std::string frame;
  24578. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24579. frame += static_cast<char>(126); // payload_len=126 (>125)
  24580. frame += static_cast<char>(0x00); // extended length high byte
  24581. frame += static_cast<char>(126); // extended length low byte
  24582. frame += std::string(126, 'x');
  24583. strm.write(frame.data(), frame.size());
  24584. ws::Opcode opcode;
  24585. std::string payload;
  24586. bool fin;
  24587. EXPECT_EQ(
  24588. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24589. ws::impl::FrameRead::ProtocolError);
  24590. }
  24591. // Ping with FIN=1 and payload_len=125 - should succeed
  24592. {
  24593. detail::BufferStream strm;
  24594. std::string frame;
  24595. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24596. frame += static_cast<char>(125); // payload_len=125
  24597. frame += std::string(125, 'x');
  24598. strm.write(frame.data(), frame.size());
  24599. ws::Opcode opcode;
  24600. std::string payload;
  24601. bool fin;
  24602. EXPECT_EQ(
  24603. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24604. ws::impl::FrameRead::Ok);
  24605. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24606. EXPECT_EQ(125u, payload.size());
  24607. EXPECT_TRUE(fin);
  24608. }
  24609. }
  24610. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24611. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24612. // length MUST be 0.
  24613. // MSB set - must be rejected
  24614. {
  24615. detail::BufferStream strm;
  24616. std::string frame;
  24617. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24618. frame += static_cast<char>(127); // 64-bit extended length
  24619. frame += static_cast<char>(0x80); // MSB set (invalid)
  24620. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24621. strm.write(frame.data(), frame.size());
  24622. ws::Opcode opcode;
  24623. std::string payload;
  24624. bool fin;
  24625. EXPECT_EQ(
  24626. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24627. ws::impl::FrameRead::ProtocolError);
  24628. }
  24629. // MSB clear - should pass length parsing (will be rejected by max_len,
  24630. // but that's a different check; use a small length to verify)
  24631. {
  24632. detail::BufferStream strm;
  24633. std::string frame;
  24634. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24635. frame += static_cast<char>(127); // 64-bit extended length
  24636. frame += std::string(7, '\0'); // high bytes = 0
  24637. frame += static_cast<char>(0x03); // length = 3
  24638. frame += "abc";
  24639. strm.write(frame.data(), frame.size());
  24640. ws::Opcode opcode;
  24641. std::string payload;
  24642. bool fin;
  24643. EXPECT_EQ(
  24644. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24645. ws::impl::FrameRead::Ok);
  24646. EXPECT_EQ(ws::Opcode::Text, opcode);
  24647. EXPECT_EQ("abc", payload);
  24648. }
  24649. }
  24650. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24651. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24652. // Valid UTF-8
  24653. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24654. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24655. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24656. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24657. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24658. // Invalid UTF-8
  24659. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24660. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24661. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24662. EXPECT_FALSE(
  24663. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24664. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24665. }
  24666. TEST(WebSocketTest, ConnectAndDisconnect) {
  24667. Server svr;
  24668. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24669. std::string msg;
  24670. while (ws.read(msg)) {}
  24671. });
  24672. auto port = svr.bind_to_any_port(HOST);
  24673. std::thread t([&]() { svr.listen_after_bind(); });
  24674. svr.wait_until_ready();
  24675. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24676. auto res = client.connect();
  24677. ASSERT_TRUE(res);
  24678. EXPECT_EQ(Error::Success, res.error());
  24679. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24680. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24681. EXPECT_TRUE(client.is_open());
  24682. client.close();
  24683. EXPECT_FALSE(client.is_open());
  24684. svr.stop();
  24685. t.join();
  24686. }
  24687. TEST(WebSocketTest, ValidURL) {
  24688. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24689. EXPECT_TRUE(ws1.is_valid());
  24690. ws::WebSocketClient ws2("ws://example.com/path");
  24691. EXPECT_TRUE(ws2.is_valid());
  24692. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24693. EXPECT_TRUE(ws3.is_valid());
  24694. #ifdef CPPHTTPLIB_SSL_ENABLED
  24695. ws::WebSocketClient wss1("wss://example.com/path");
  24696. EXPECT_TRUE(wss1.is_valid());
  24697. ws::WebSocketClient wss2("wss://example.com:443/path");
  24698. EXPECT_TRUE(wss2.is_valid());
  24699. #endif
  24700. }
  24701. TEST(WebSocketTest, InvalidURL) {
  24702. // No scheme
  24703. ws::WebSocketClient ws1("localhost:8080/path");
  24704. EXPECT_FALSE(ws1.is_valid());
  24705. // No path
  24706. ws::WebSocketClient ws2("ws://localhost:8080");
  24707. EXPECT_FALSE(ws2.is_valid());
  24708. // Empty string
  24709. ws::WebSocketClient ws3("");
  24710. EXPECT_FALSE(ws3.is_valid());
  24711. // Missing host
  24712. ws::WebSocketClient ws4("ws://:8080/path");
  24713. EXPECT_FALSE(ws4.is_valid());
  24714. // Port number overflow — should not crash
  24715. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24716. EXPECT_FALSE(ws5.is_valid());
  24717. // Port out of range
  24718. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24719. EXPECT_FALSE(ws6.is_valid());
  24720. }
  24721. TEST(WebSocketTest, UnsupportedScheme) {
  24722. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24723. ws::WebSocketClient ws1("http://localhost:8080/path");
  24724. EXPECT_FALSE(ws1.is_valid());
  24725. ws::WebSocketClient ws2("https://localhost:8080/path");
  24726. EXPECT_FALSE(ws2.is_valid());
  24727. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24728. EXPECT_FALSE(ws3.is_valid());
  24729. #else
  24730. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24731. std::invalid_argument);
  24732. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24733. std::invalid_argument);
  24734. #endif
  24735. }
  24736. TEST(WebSocketTest, ConnectWhenInvalid) {
  24737. ws::WebSocketClient ws("not a valid url");
  24738. EXPECT_FALSE(ws.is_valid());
  24739. auto res = ws.connect();
  24740. EXPECT_FALSE(res);
  24741. EXPECT_EQ(Error::Connection, res.error());
  24742. EXPECT_EQ(-1, res.status());
  24743. }
  24744. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24745. // Grab a port that is free, then close it again so nothing listens there
  24746. Server svr;
  24747. auto port = svr.bind_to_any_port(HOST);
  24748. svr.stop();
  24749. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24750. auto res = client.connect();
  24751. ASSERT_FALSE(res);
  24752. EXPECT_EQ(Error::Connection, res.error());
  24753. EXPECT_EQ(-1, res.status());
  24754. }
  24755. TEST(WebSocketTest, DefaultPort) {
  24756. ws::WebSocketClient ws1("ws://example.com/path");
  24757. EXPECT_TRUE(ws1.is_valid());
  24758. // ws:// defaults to port 80 (verified by successful parse)
  24759. #ifdef CPPHTTPLIB_SSL_ENABLED
  24760. ws::WebSocketClient ws2("wss://example.com/path");
  24761. EXPECT_TRUE(ws2.is_valid());
  24762. // wss:// defaults to port 443 (verified by successful parse)
  24763. #endif
  24764. }
  24765. TEST(WebSocketTest, IPv6LiteralAddress) {
  24766. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24767. EXPECT_TRUE(ws1.is_valid());
  24768. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24769. EXPECT_TRUE(ws2.is_valid());
  24770. }
  24771. TEST(WebSocketTest, ComplexPath) {
  24772. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24773. EXPECT_TRUE(ws1.is_valid());
  24774. ws::WebSocketClient ws2("ws://localhost:8080/");
  24775. EXPECT_TRUE(ws2.is_valid());
  24776. }
  24777. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24778. Server svr;
  24779. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24780. std::string msg;
  24781. while (ws.read(msg)) {}
  24782. });
  24783. auto port = svr.bind_to_any_port(HOST);
  24784. std::thread t([&]() { svr.listen_after_bind(); });
  24785. svr.wait_until_ready();
  24786. auto another_host = "example.com";
  24787. auto wrong_ip = "192.0.2.1";
  24788. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24789. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24790. ASSERT_TRUE(client.connect());
  24791. EXPECT_TRUE(client.is_open());
  24792. client.close();
  24793. svr.stop();
  24794. t.join();
  24795. }
  24796. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24797. Server svr;
  24798. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24799. std::string msg;
  24800. while (ws.read(msg)) {}
  24801. });
  24802. auto port = svr.bind_to_any_port(HOST);
  24803. std::thread t([&]() { svr.listen_after_bind(); });
  24804. svr.wait_until_ready();
  24805. auto wrong_ip = "192.0.2.1";
  24806. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24807. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24808. client.set_connection_timeout(1);
  24809. client.set_read_timeout(1);
  24810. client.set_write_timeout(1);
  24811. EXPECT_FALSE(client.connect());
  24812. EXPECT_FALSE(client.is_open());
  24813. svr.stop();
  24814. t.join();
  24815. }
  24816. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24817. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24818. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24819. // (RFC 6761) is only a map key and the Host header value.
  24820. auto host = "target.invalid";
  24821. Server svr;
  24822. std::string received_host;
  24823. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24824. received_host = req.get_header_value("Host");
  24825. std::string msg;
  24826. while (ws.read(msg)) {}
  24827. });
  24828. auto port = svr.bind_to_any_port(HOST);
  24829. std::thread t([&]() { svr.listen_after_bind(); });
  24830. // ASSERT_* below returns from the test body, which would leave t joinable
  24831. // and make ~thread call std::terminate.
  24832. auto se = detail::scope_exit([&] {
  24833. svr.stop();
  24834. if (t.joinable()) { t.join(); }
  24835. });
  24836. svr.wait_until_ready();
  24837. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24838. std::to_string(port) + "/ws");
  24839. client.set_direct_hostname_addr_map({{host, HOST}});
  24840. ASSERT_TRUE(client.connect());
  24841. EXPECT_TRUE(client.is_open());
  24842. client.close();
  24843. svr.stop();
  24844. t.join();
  24845. // The mapping only redirects the connection; the identity stays host_.
  24846. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24847. }
  24848. class WebSocketIntegrationTest : public ::testing::Test {
  24849. protected:
  24850. void SetUp() override {
  24851. server_ = httplib::detail::make_unique<Server>();
  24852. setup_server();
  24853. start_server();
  24854. }
  24855. void TearDown() override {
  24856. server_->stop();
  24857. if (server_thread_.joinable()) { server_thread_.join(); }
  24858. }
  24859. void setup_server() {
  24860. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24861. std::string msg;
  24862. ws::ReadResult ret;
  24863. while ((ret = ws.read(msg))) {
  24864. if (ret == ws::Binary) {
  24865. ws.send(msg.data(), msg.size());
  24866. } else {
  24867. ws.send(msg);
  24868. }
  24869. }
  24870. });
  24871. server_->WebSocket("/ws-echo-string",
  24872. [](const Request &, ws::WebSocket &ws) {
  24873. std::string msg;
  24874. while (ws.read(msg)) {
  24875. ws.send("echo: " + msg);
  24876. }
  24877. });
  24878. server_->WebSocket(
  24879. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24880. // Echo back request metadata
  24881. ws.send("path:" + req.path);
  24882. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24883. std::string msg;
  24884. while (ws.read(msg)) {}
  24885. });
  24886. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24887. std::string msg;
  24888. ws.read(msg); // wait for a message
  24889. ws.close();
  24890. });
  24891. server_->WebSocket("/ws-close-status",
  24892. [](const Request &, ws::WebSocket &ws) {
  24893. std::string msg;
  24894. ws.read(msg); // wait for a message
  24895. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24896. });
  24897. server_->WebSocket(
  24898. "/ws-subprotocol",
  24899. [](const Request &, ws::WebSocket &ws) {
  24900. std::string msg;
  24901. while (ws.read(msg)) {
  24902. ws.send(msg);
  24903. }
  24904. },
  24905. [](const std::vector<std::string> &protocols) -> std::string {
  24906. for (const auto &p : protocols) {
  24907. if (p == "graphql-ws") { return p; }
  24908. }
  24909. return "";
  24910. });
  24911. server_->WebSocket(
  24912. "/ws-subprotocol-unoffered",
  24913. [](const Request &, ws::WebSocket &ws) {
  24914. std::string msg;
  24915. while (ws.read(msg)) {
  24916. ws.send(msg);
  24917. }
  24918. },
  24919. [](const std::vector<std::string> &) -> std::string {
  24920. return "admin";
  24921. });
  24922. }
  24923. void start_server() {
  24924. port_ = server_->bind_to_any_port(HOST);
  24925. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24926. server_->wait_until_ready();
  24927. }
  24928. std::unique_ptr<Server> server_;
  24929. std::thread server_thread_;
  24930. int port_ = 0;
  24931. };
  24932. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24933. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24934. "/ws-echo");
  24935. ASSERT_TRUE(client.connect());
  24936. ASSERT_TRUE(client.is_open());
  24937. ASSERT_TRUE(client.send("Hello WebSocket"));
  24938. std::string msg;
  24939. EXPECT_EQ(ws::Text, client.read(msg));
  24940. EXPECT_EQ("Hello WebSocket", msg);
  24941. client.close();
  24942. }
  24943. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24944. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24945. "/ws-echo");
  24946. ASSERT_TRUE(client.connect());
  24947. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24948. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24949. std::string msg;
  24950. EXPECT_EQ(ws::Binary, client.read(msg));
  24951. EXPECT_EQ(binary_data, msg);
  24952. client.close();
  24953. }
  24954. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24955. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24956. "/ws-echo");
  24957. ASSERT_TRUE(client.connect());
  24958. for (int i = 0; i < 10; i++) {
  24959. auto text = "message " + std::to_string(i);
  24960. ASSERT_TRUE(client.send(text));
  24961. std::string msg;
  24962. ASSERT_TRUE(client.read(msg));
  24963. EXPECT_EQ(text, msg);
  24964. }
  24965. client.close();
  24966. }
  24967. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24968. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24969. "/ws-close");
  24970. ASSERT_TRUE(client.connect());
  24971. // Send a message to trigger the server to close
  24972. ASSERT_TRUE(client.send("trigger close"));
  24973. // The server will close, so read should return false
  24974. std::string msg;
  24975. EXPECT_FALSE(client.read(msg));
  24976. EXPECT_FALSE(client.is_open());
  24977. EXPECT_EQ(ws::CloseStatus::Normal, client.close_status());
  24978. EXPECT_EQ("", client.close_reason());
  24979. }
  24980. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24981. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24982. "/ws-echo");
  24983. ASSERT_TRUE(client.connect());
  24984. // 128KB message
  24985. std::string large_data(128 * 1024, 'X');
  24986. ASSERT_TRUE(client.send(large_data));
  24987. std::string msg;
  24988. ASSERT_TRUE(client.read(msg));
  24989. EXPECT_EQ(large_data, msg);
  24990. client.close();
  24991. }
  24992. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24993. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24994. "/ws-echo");
  24995. ASSERT_TRUE(client.connect());
  24996. const int num_threads = 4;
  24997. std::vector<std::thread> threads;
  24998. std::atomic<int> send_count{0};
  24999. for (int t = 0; t < num_threads; t++) {
  25000. threads.emplace_back([&client, &send_count, t]() {
  25001. for (int i = 0; i < 5; i++) {
  25002. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  25003. if (client.send(text)) { send_count++; }
  25004. }
  25005. });
  25006. }
  25007. for (auto &th : threads) {
  25008. th.join();
  25009. }
  25010. int received = 0;
  25011. std::string msg;
  25012. while (received < send_count.load()) {
  25013. if (!client.read(msg)) { break; }
  25014. received++;
  25015. }
  25016. EXPECT_EQ(send_count.load(), received);
  25017. client.close();
  25018. }
  25019. TEST_F(WebSocketIntegrationTest, ReadString) {
  25020. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25021. "/ws-echo-string");
  25022. ASSERT_TRUE(client.connect());
  25023. ASSERT_TRUE(client.send("hello"));
  25024. std::string msg;
  25025. ASSERT_TRUE(client.read(msg));
  25026. EXPECT_EQ("echo: hello", msg);
  25027. ASSERT_TRUE(client.send("world"));
  25028. ASSERT_TRUE(client.read(msg));
  25029. EXPECT_EQ("echo: world", msg);
  25030. client.close();
  25031. }
  25032. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  25033. Headers headers = {{"X-Test-Header", "test-value"}};
  25034. ws::WebSocketClient client(
  25035. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  25036. ASSERT_TRUE(client.connect());
  25037. std::string msg;
  25038. ASSERT_TRUE(client.read(msg));
  25039. EXPECT_EQ("path:/ws-request-info", msg);
  25040. ASSERT_TRUE(client.read(msg));
  25041. EXPECT_EQ("header:test-value", msg);
  25042. client.close();
  25043. }
  25044. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  25045. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25046. "/ws-echo");
  25047. client.set_read_timeout(1, 0); // 1 second
  25048. ASSERT_TRUE(client.connect());
  25049. // Don't send anything — server echo handler waits for a message, so read()
  25050. // should time out. The connection survives it: nothing was consumed.
  25051. std::string msg;
  25052. EXPECT_EQ(client.read(msg), ws::Timeout);
  25053. EXPECT_TRUE(client.is_open());
  25054. // And it is still usable afterwards.
  25055. EXPECT_TRUE(client.send("after timeout"));
  25056. EXPECT_EQ(client.read(msg), ws::Text);
  25057. EXPECT_EQ(msg, "after timeout");
  25058. }
  25059. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  25060. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25061. "/ws-echo");
  25062. client.set_read_timeout(1, 0);
  25063. ASSERT_TRUE(client.connect());
  25064. ASSERT_TRUE(client.send("first"));
  25065. std::string msg;
  25066. ASSERT_EQ(client.read(msg), ws::Text);
  25067. ASSERT_EQ(msg, "first");
  25068. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  25069. // not be used with a read timeout: it would reprocess the previous message.
  25070. EXPECT_EQ(client.read(msg), ws::Timeout);
  25071. EXPECT_EQ(msg, "first");
  25072. }
  25073. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  25074. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25075. "/ws-echo");
  25076. ASSERT_TRUE(client.connect());
  25077. // Setting it once the connection is open reaches the live stream, not just
  25078. // the seed for the next connect().
  25079. client.set_read_timeout(1, 0);
  25080. std::string msg;
  25081. EXPECT_EQ(client.read(msg), ws::Timeout);
  25082. EXPECT_TRUE(client.is_open());
  25083. }
  25084. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  25085. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25086. "/nonexistent");
  25087. auto res = client.connect();
  25088. EXPECT_FALSE(res);
  25089. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25090. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  25091. EXPECT_FALSE(client.is_open());
  25092. }
  25093. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  25094. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25095. "/ws-echo");
  25096. ASSERT_TRUE(client.connect());
  25097. ASSERT_TRUE(client.send(""));
  25098. std::string msg;
  25099. EXPECT_EQ(ws::Text, client.read(msg));
  25100. EXPECT_EQ("", msg);
  25101. client.close();
  25102. }
  25103. TEST_F(WebSocketIntegrationTest, Reconnect) {
  25104. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25105. "/ws-echo");
  25106. // First connection
  25107. ASSERT_TRUE(client.connect());
  25108. ASSERT_TRUE(client.send("first"));
  25109. std::string msg;
  25110. ASSERT_TRUE(client.read(msg));
  25111. EXPECT_EQ("first", msg);
  25112. client.close();
  25113. EXPECT_FALSE(client.is_open());
  25114. // Reconnect using the same client object
  25115. ASSERT_TRUE(client.connect());
  25116. ASSERT_TRUE(client.is_open());
  25117. ASSERT_TRUE(client.send("second"));
  25118. ASSERT_TRUE(client.read(msg));
  25119. EXPECT_EQ("second", msg);
  25120. client.close();
  25121. }
  25122. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  25123. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25124. "/ws-close-status");
  25125. ASSERT_TRUE(client.connect());
  25126. // Trigger the server to close with GoingAway status
  25127. ASSERT_TRUE(client.send("trigger"));
  25128. // read() should return false after receiving the close frame
  25129. std::string msg;
  25130. EXPECT_FALSE(client.read(msg));
  25131. EXPECT_FALSE(client.is_open());
  25132. EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
  25133. EXPECT_EQ("shutting down", client.close_reason());
  25134. // A copy, so it outlives a reconnect that replaces the connection
  25135. static_assert(
  25136. std::is_same<decltype(client.close_reason()), std::string>::value, "");
  25137. }
  25138. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  25139. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25140. "/ws-echo");
  25141. EXPECT_EQ(ws::CloseStatus::Abnormal, client.close_status());
  25142. ASSERT_TRUE(client.connect());
  25143. client.close(ws::CloseStatus::GoingAway, "client leaving");
  25144. EXPECT_FALSE(client.is_open());
  25145. // The server echoes the Close it receives
  25146. EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
  25147. EXPECT_EQ("client leaving", client.close_reason());
  25148. }
  25149. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  25150. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  25151. ws::WebSocketClient client(
  25152. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  25153. ASSERT_TRUE(client.connect());
  25154. // Server should have selected graphql-ws
  25155. EXPECT_EQ("graphql-ws", client.subprotocol());
  25156. client.close();
  25157. }
  25158. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  25159. Headers headers;
  25160. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  25161. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  25162. ws::WebSocketClient client(
  25163. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  25164. ASSERT_TRUE(client.connect());
  25165. // The offer on the second field line counts too, so graphql-ws is selected
  25166. EXPECT_EQ("graphql-ws", client.subprotocol());
  25167. client.close();
  25168. }
  25169. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  25170. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  25171. ws::WebSocketClient client(
  25172. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  25173. ASSERT_TRUE(client.connect());
  25174. // Server should not have selected any subprotocol
  25175. EXPECT_TRUE(client.subprotocol().empty());
  25176. client.close();
  25177. }
  25178. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  25179. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25180. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25181. "/ws-subprotocol-unoffered",
  25182. headers);
  25183. ASSERT_TRUE(client.connect());
  25184. EXPECT_TRUE(client.subprotocol().empty());
  25185. client.close();
  25186. }
  25187. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  25188. // Connect without requesting any subprotocol
  25189. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25190. "/ws-subprotocol");
  25191. ASSERT_TRUE(client.connect());
  25192. EXPECT_TRUE(client.subprotocol().empty());
  25193. client.close();
  25194. }
  25195. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  25196. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25197. "/ws-echo");
  25198. client.set_tcp_nodelay(true);
  25199. client.set_connection_timeout(3, 0);
  25200. bool socket_options_called = false;
  25201. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  25202. ASSERT_TRUE(client.connect());
  25203. ASSERT_TRUE(client.is_open());
  25204. EXPECT_TRUE(socket_options_called);
  25205. ASSERT_TRUE(client.send("hello"));
  25206. std::string msg;
  25207. auto result = client.read(msg);
  25208. EXPECT_EQ(result, ws::ReadResult::Text);
  25209. EXPECT_EQ(msg, "hello");
  25210. client.close();
  25211. }
  25212. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  25213. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25214. "/ws-echo");
  25215. client.set_connection_timeout(std::chrono::seconds(3));
  25216. client.set_write_timeout(std::chrono::seconds(3));
  25217. // A sub-second remainder exercises the seconds/microseconds split.
  25218. client.set_read_timeout(std::chrono::milliseconds(1500));
  25219. ASSERT_TRUE(client.connect());
  25220. auto start = std::chrono::steady_clock::now();
  25221. std::string msg;
  25222. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  25223. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  25224. std::chrono::steady_clock::now() - start)
  25225. .count();
  25226. // Above 1s so that dropping the microseconds half of the split fails here.
  25227. // Ignoring the setter altogether would not reach this line at all: a client
  25228. // waits forever by default.
  25229. EXPECT_GE(elapsed, 1400);
  25230. EXPECT_LT(elapsed, 30000);
  25231. }
  25232. #ifndef _WIN32
  25233. // A send() that times out after part of the data went out returns the count
  25234. // written so far. Every byte of the frame must still be sent, or the peer reads
  25235. // the next frame's header and payload as the rest of this one.
  25236. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  25237. signal(SIGPIPE, SIG_IGN);
  25238. const std::string large(4 * 1024 * 1024, 'A');
  25239. std::atomic<bool> large_sent{false};
  25240. std::atomic<bool> small_sent{false};
  25241. Server svr;
  25242. svr.set_write_timeout(0, 500000);
  25243. svr.set_socket_options([](socket_t sock) {
  25244. int size = 8192;
  25245. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  25246. reinterpret_cast<const char *>(&size), sizeof(size));
  25247. });
  25248. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25249. large_sent = ws.send(large.data(), large.size());
  25250. small_sent = ws.send("after");
  25251. std::string msg;
  25252. while (ws.read(msg)) {}
  25253. });
  25254. auto port = svr.bind_to_any_port(HOST);
  25255. std::thread t([&]() { svr.listen_after_bind(); });
  25256. auto se = detail::scope_exit([&] {
  25257. svr.stop();
  25258. t.join();
  25259. });
  25260. svr.wait_until_ready();
  25261. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  25262. std::to_string(port) + "/ws");
  25263. client.set_read_timeout(5);
  25264. client.set_socket_options([](socket_t sock) {
  25265. int size = 8192;
  25266. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  25267. reinterpret_cast<const char *>(&size), sizeof(size));
  25268. });
  25269. ASSERT_TRUE(client.connect());
  25270. // Outlast the server's write timeout, then drain.
  25271. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  25272. std::string msg;
  25273. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  25274. EXPECT_TRUE(msg == large);
  25275. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  25276. EXPECT_EQ("after", msg);
  25277. EXPECT_TRUE(large_sent);
  25278. EXPECT_TRUE(small_sent);
  25279. client.close();
  25280. }
  25281. // A send() that fails partway leaves a frame on the wire whose header announces
  25282. // more than was sent. Nothing may follow it, or the peer reads the next frames
  25283. // as the rest of it and a later payload's bytes as a frame of their own.
  25284. TEST(WebSocketPartialWriteTest, FailedWriteClosesConnection) {
  25285. signal(SIGPIPE, SIG_IGN);
  25286. const std::string large(4 * 1024 * 1024, 'A');
  25287. std::atomic<bool> large_sent{true};
  25288. std::atomic<bool> open_after_failure{true};
  25289. std::atomic<bool> handler_done{false};
  25290. Server svr;
  25291. svr.set_write_timeout(0, 200000);
  25292. svr.set_socket_options([](socket_t sock) {
  25293. int size = 8192;
  25294. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  25295. reinterpret_cast<const char *>(&size), sizeof(size));
  25296. });
  25297. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25298. large_sent = ws.send(large.data(), large.size());
  25299. open_after_failure = ws.is_open();
  25300. handler_done = true;
  25301. });
  25302. auto port = svr.bind_to_any_port(HOST);
  25303. std::thread t([&]() { svr.listen_after_bind(); });
  25304. auto se = detail::scope_exit([&] {
  25305. svr.stop();
  25306. t.join();
  25307. });
  25308. svr.wait_until_ready();
  25309. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  25310. std::to_string(port) + "/ws");
  25311. client.set_socket_options([](socket_t sock) {
  25312. int size = 8192;
  25313. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  25314. reinterpret_cast<const char *>(&size), sizeof(size));
  25315. });
  25316. ASSERT_TRUE(client.connect());
  25317. // Read nothing, so the server's write times out partway through the frame.
  25318. for (int i = 0; i < 100 && !handler_done; i++) {
  25319. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  25320. }
  25321. ASSERT_TRUE(handler_done);
  25322. ASSERT_FALSE(large_sent);
  25323. EXPECT_FALSE(open_after_failure);
  25324. client.close();
  25325. }
  25326. #endif
  25327. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  25328. Server svr;
  25329. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25330. if (!req.has_header("Authorization")) {
  25331. res.status = StatusCode::Unauthorized_401;
  25332. res.set_content("Unauthorized", "text/plain");
  25333. return Server::HandlerResponse::Handled;
  25334. }
  25335. return Server::HandlerResponse::Unhandled;
  25336. });
  25337. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25338. std::string msg;
  25339. while (ws.read(msg)) {
  25340. ws.send(msg);
  25341. }
  25342. });
  25343. auto port = svr.bind_to_any_port("localhost");
  25344. std::thread t([&]() { svr.listen_after_bind(); });
  25345. svr.wait_until_ready();
  25346. // Without Authorization header - should be rejected before upgrade
  25347. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  25348. EXPECT_FALSE(client1.connect());
  25349. // The rejection is framed like any other HTTP response
  25350. {
  25351. Client cli("localhost", port);
  25352. Headers headers = {{"Upgrade", "websocket"},
  25353. {"Connection", "Upgrade"},
  25354. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25355. {"Sec-WebSocket-Version", "13"}};
  25356. auto res = cli.Get("/ws", headers);
  25357. ASSERT_TRUE(res);
  25358. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25359. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25360. EXPECT_EQ("Unauthorized", res->body);
  25361. }
  25362. // With Authorization header - should succeed
  25363. Headers headers = {{"Authorization", "Bearer token123"}};
  25364. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  25365. headers);
  25366. ASSERT_TRUE(client2.connect());
  25367. ASSERT_TRUE(client2.send("hello"));
  25368. std::string msg;
  25369. ASSERT_TRUE(client2.read(msg));
  25370. EXPECT_EQ("hello", msg);
  25371. client2.close();
  25372. svr.stop();
  25373. t.join();
  25374. }
  25375. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  25376. Server svr;
  25377. std::atomic<int> pre_routing_calls{0};
  25378. std::atomic<int> pre_request_calls{0};
  25379. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  25380. pre_routing_calls++;
  25381. if (req.path == "/handled") {
  25382. res.set_content("handled", "text/plain");
  25383. return Server::HandlerResponse::Handled;
  25384. }
  25385. return Server::HandlerResponse::Unhandled;
  25386. });
  25387. svr.set_pre_request_handler([&](const Request &, Response &) {
  25388. pre_request_calls++;
  25389. return Server::HandlerResponse::Unhandled;
  25390. });
  25391. svr.Get("/http", [](const Request &, Response &res) {
  25392. res.set_content("http", "text/plain");
  25393. });
  25394. svr.WebSocket("/ws",
  25395. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25396. auto port = svr.bind_to_any_port("localhost");
  25397. std::thread t([&]() { svr.listen_after_bind(); });
  25398. auto se = detail::scope_exit([&] {
  25399. svr.stop();
  25400. t.join();
  25401. });
  25402. svr.wait_until_ready();
  25403. Headers upgrade = {{"Upgrade", "websocket"},
  25404. {"Connection", "Upgrade"},
  25405. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25406. {"Sec-WebSocket-Version", "13"}};
  25407. auto get = [&](const char *path) {
  25408. pre_routing_calls = 0;
  25409. return Client("localhost", port).Get(path, upgrade);
  25410. };
  25411. // No WebSocket route, but an HTTP one
  25412. auto res = get("/http");
  25413. ASSERT_TRUE(res);
  25414. EXPECT_EQ(StatusCode::OK_200, res->status);
  25415. EXPECT_EQ("http", res->body);
  25416. EXPECT_EQ(1, pre_routing_calls);
  25417. EXPECT_EQ(1, pre_request_calls);
  25418. // No route at all
  25419. res = get("/none");
  25420. ASSERT_TRUE(res);
  25421. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25422. EXPECT_EQ(1, pre_routing_calls);
  25423. // Answered by the pre-routing handler
  25424. res = get("/handled");
  25425. ASSERT_TRUE(res);
  25426. EXPECT_EQ(StatusCode::OK_200, res->status);
  25427. EXPECT_EQ("handled", res->body);
  25428. EXPECT_EQ(1, pre_routing_calls);
  25429. // A WebSocket route
  25430. pre_routing_calls = 0;
  25431. pre_request_calls = 0;
  25432. {
  25433. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25434. "/ws");
  25435. ASSERT_TRUE(client.connect());
  25436. std::string msg;
  25437. ASSERT_TRUE(client.read(msg));
  25438. EXPECT_EQ("ws", msg);
  25439. client.close();
  25440. }
  25441. EXPECT_EQ(1, pre_routing_calls);
  25442. EXPECT_EQ(1, pre_request_calls);
  25443. }
  25444. // An upgrade request answered by a hook leaves its body unread, so that body
  25445. // must not be served as the next request on the connection.
  25446. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  25447. Server svr;
  25448. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25449. if (req.path == "/pre-routing") {
  25450. res.set_content("pre-routing", "text/plain");
  25451. return Server::HandlerResponse::Handled;
  25452. }
  25453. return Server::HandlerResponse::Unhandled;
  25454. });
  25455. svr.set_pre_request_handler([](const Request &req, Response &res) {
  25456. if (req.matched_route == "/pre-request") {
  25457. res.set_content("pre-request", "text/plain");
  25458. return Server::HandlerResponse::Handled;
  25459. }
  25460. return Server::HandlerResponse::Unhandled;
  25461. });
  25462. svr.Get("/smuggled", [](const Request &, Response &res) {
  25463. res.set_content("smuggled", "text/plain");
  25464. });
  25465. svr.WebSocket("/pre-request",
  25466. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25467. auto port = svr.bind_to_any_port(HOST);
  25468. std::thread t([&]() { svr.listen_after_bind(); });
  25469. auto se = detail::scope_exit([&] {
  25470. svr.stop();
  25471. t.join();
  25472. });
  25473. svr.wait_until_ready();
  25474. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25475. for (auto path : {"/pre-routing", "/pre-request"}) {
  25476. std::string req = std::string("GET ") + path +
  25477. " HTTP/1.1\r\n"
  25478. "Host: localhost\r\n"
  25479. "Upgrade: websocket\r\n"
  25480. "Connection: Upgrade\r\n"
  25481. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  25482. "Sec-WebSocket-Version: 13\r\n"
  25483. "Content-Length: " +
  25484. std::to_string(body.size()) + "\r\n\r\n" + body;
  25485. std::string res;
  25486. ASSERT_TRUE(send_request(5, req, &res, port));
  25487. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  25488. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  25489. // Only one response, and the body was not served as a request
  25490. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  25491. }
  25492. }
  25493. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  25494. Server svr;
  25495. std::atomic<int> pre_request_calls{0};
  25496. std::atomic<bool> route_matched{false};
  25497. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  25498. pre_request_calls++;
  25499. if (req.matched_route == "/ws/:id") { route_matched = true; }
  25500. if (req.get_header_value("Authorization") != "Bearer token123") {
  25501. res.status = StatusCode::Unauthorized_401;
  25502. res.set_content("Unauthorized", "text/plain");
  25503. return Server::HandlerResponse::Handled;
  25504. }
  25505. return Server::HandlerResponse::Unhandled;
  25506. });
  25507. std::atomic<bool> handler_called{false};
  25508. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  25509. handler_called = true;
  25510. ws.send(req.matched_route + " " + req.path_params.at("id"));
  25511. });
  25512. auto port = svr.bind_to_any_port("localhost");
  25513. std::thread t([&]() { svr.listen_after_bind(); });
  25514. svr.wait_until_ready();
  25515. // Without Authorization header - should be rejected before upgrade
  25516. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  25517. "/ws/1");
  25518. EXPECT_FALSE(client1.connect());
  25519. EXPECT_FALSE(handler_called);
  25520. EXPECT_EQ(1, pre_request_calls);
  25521. EXPECT_TRUE(route_matched);
  25522. // The rejection is an ordinary HTTP response, not a protocol switch
  25523. {
  25524. Client cli("localhost", port);
  25525. Headers headers = {{"Upgrade", "websocket"},
  25526. {"Connection", "Upgrade"},
  25527. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25528. {"Sec-WebSocket-Version", "13"}};
  25529. auto res = cli.Get("/ws/1", headers);
  25530. ASSERT_TRUE(res);
  25531. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25532. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25533. EXPECT_EQ("Unauthorized", res->body);
  25534. }
  25535. EXPECT_FALSE(handler_called);
  25536. // With Authorization header - should succeed
  25537. Headers headers = {{"Authorization", "Bearer token123"}};
  25538. ws::WebSocketClient client2(
  25539. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  25540. ASSERT_TRUE(client2.connect());
  25541. std::string msg;
  25542. ASSERT_TRUE(client2.read(msg));
  25543. EXPECT_EQ("/ws/:id 2", msg);
  25544. EXPECT_TRUE(handler_called);
  25545. client2.close();
  25546. svr.stop();
  25547. t.join();
  25548. }
  25549. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  25550. static Headers websocket_upgrade_headers() {
  25551. return {{"Upgrade", "websocket"},
  25552. {"Connection", "Upgrade"},
  25553. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25554. {"Sec-WebSocket-Version", "13"},
  25555. {"Sec-WebSocket-Protocol", "chat"}};
  25556. }
  25557. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25558. Server svr;
  25559. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25560. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25561. return Server::HandlerResponse::Unhandled;
  25562. });
  25563. svr.set_pre_request_handler([](const Request &req, Response &) {
  25564. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25565. return Server::HandlerResponse::Unhandled;
  25566. });
  25567. svr.set_exception_handler(
  25568. [](const Request &, Response &res, std::exception_ptr ep) {
  25569. try {
  25570. std::rethrow_exception(ep);
  25571. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25572. });
  25573. auto handler = [](const Request &, ws::WebSocket &) {};
  25574. svr.WebSocket("/pre-routing", handler);
  25575. svr.WebSocket("/pre-request", handler);
  25576. svr.WebSocket("/sub-protocol", handler,
  25577. [](const std::vector<std::string> &) -> std::string {
  25578. throw std::runtime_error("/sub-protocol");
  25579. });
  25580. auto port = svr.bind_to_any_port(HOST);
  25581. ASSERT_GT(port, 0);
  25582. thread t = thread([&] { svr.listen_after_bind(); });
  25583. auto se = detail::scope_exit([&] {
  25584. svr.stop();
  25585. t.join();
  25586. ASSERT_FALSE(svr.is_running());
  25587. });
  25588. svr.wait_until_ready();
  25589. Client cli(HOST, port);
  25590. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25591. auto res = cli.Get(path, websocket_upgrade_headers());
  25592. if (!res) {
  25593. ADD_FAILURE() << path << ": " << to_string(res.error());
  25594. continue;
  25595. }
  25596. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25597. EXPECT_EQ(path, res->body);
  25598. }
  25599. }
  25600. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25601. Server svr;
  25602. svr.set_pre_routing_handler(
  25603. [](const Request &, Response &) -> Server::HandlerResponse {
  25604. throw std::runtime_error("pre-routing");
  25605. });
  25606. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25607. auto port = svr.bind_to_any_port(HOST);
  25608. ASSERT_GT(port, 0);
  25609. thread t = thread([&] { svr.listen_after_bind(); });
  25610. auto se = detail::scope_exit([&] {
  25611. svr.stop();
  25612. t.join();
  25613. ASSERT_FALSE(svr.is_running());
  25614. });
  25615. svr.wait_until_ready();
  25616. Client cli(HOST, port);
  25617. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25618. ASSERT_TRUE(res) << to_string(res.error());
  25619. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25620. }
  25621. #endif
  25622. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25623. Server svr;
  25624. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25625. // A read timeout is how a handler gets control back. Without it, a handler
  25626. // parked in read() can never write on the connection it is reading.
  25627. ws.set_read_timeout(std::chrono::milliseconds(100));
  25628. std::string msg;
  25629. while (ws.is_open()) {
  25630. auto r = ws.read(msg);
  25631. if (r == httplib::ws::Timeout) {
  25632. ws.send("tick");
  25633. continue;
  25634. }
  25635. if (r == httplib::ws::Fail) { break; }
  25636. ws.send(msg);
  25637. }
  25638. });
  25639. auto port = svr.bind_to_any_port("localhost");
  25640. std::thread t([&]() { svr.listen_after_bind(); });
  25641. svr.wait_until_ready();
  25642. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25643. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25644. ASSERT_TRUE(client.connect());
  25645. // The client sends nothing, so anything it receives came out of the
  25646. // handler's timeout path.
  25647. std::string msg;
  25648. ASSERT_EQ(client.read(msg), ws::Text);
  25649. EXPECT_EQ("tick", msg);
  25650. client.close();
  25651. svr.stop();
  25652. t.join();
  25653. }
  25654. // Stream::read may return fewer bytes than asked for. This is that contract at
  25655. // its worst -- one byte per call -- which is what a frame header straddling a
  25656. // read buffer's boundary looks like to the frame parser.
  25657. class WsByteAtATimeStream : public Stream {
  25658. public:
  25659. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25660. bool is_readable() const override { return true; }
  25661. bool wait_readable() const override { return true; }
  25662. bool wait_writable() const override { return true; }
  25663. ssize_t read(char *ptr, size_t size) override {
  25664. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25665. *ptr = data_[pos_++];
  25666. return 1;
  25667. }
  25668. ssize_t write(const char *, size_t size) override {
  25669. return static_cast<ssize_t>(size);
  25670. }
  25671. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25672. ip = "127.0.0.1";
  25673. port = 0;
  25674. }
  25675. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25676. ip = "127.0.0.1";
  25677. port = 0;
  25678. }
  25679. socket_t socket() const override { return INVALID_SOCKET; }
  25680. time_t duration() const override { return 0; }
  25681. private:
  25682. std::string data_;
  25683. size_t pos_ = 0;
  25684. };
  25685. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25686. // The payload uses the 16-bit extended length, so the header, the length
  25687. // and the mask key are all multi-byte fields here. Each used to be read
  25688. // with a single read() call, which fails as soon as one is split. The
  25689. // payload is also a little over one read chunk, so it is read in two.
  25690. std::string body;
  25691. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25692. body += static_cast<char>(i % 251);
  25693. }
  25694. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25695. std::string frame;
  25696. frame += static_cast<char>(0x81); // FIN + Text
  25697. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25698. frame += static_cast<char>(body.size() >> 8);
  25699. frame += static_cast<char>(body.size() & 0xff);
  25700. for (size_t i = 0; i < 4; i++) {
  25701. frame += static_cast<char>(mask[i]);
  25702. }
  25703. for (size_t i = 0; i < body.size(); i++) {
  25704. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25705. }
  25706. WsByteAtATimeStream strm(frame);
  25707. ws::Opcode opcode;
  25708. std::string payload;
  25709. bool fin = false;
  25710. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25711. /*expect_masked=*/true, body.size()),
  25712. ws::impl::FrameRead::Ok);
  25713. EXPECT_TRUE(fin);
  25714. EXPECT_EQ(opcode, ws::Opcode::Text);
  25715. EXPECT_EQ(payload, body);
  25716. }
  25717. // Keeps what is written, counting the writes, and reads it back.
  25718. class WsWriteCountingStream : public Stream {
  25719. public:
  25720. bool is_readable() const override { return true; }
  25721. bool wait_readable() const override { return true; }
  25722. bool wait_writable() const override { return true; }
  25723. ssize_t read(char *ptr, size_t size) override {
  25724. auto n = (std::min)(size, data_.size() - pos_);
  25725. if (n == 0) { return 0; }
  25726. memcpy(ptr, data_.data() + pos_, n);
  25727. pos_ += n;
  25728. return static_cast<ssize_t>(n);
  25729. }
  25730. ssize_t write(const char *ptr, size_t size) override {
  25731. writes++;
  25732. data_.append(ptr, size);
  25733. return static_cast<ssize_t>(size);
  25734. }
  25735. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25736. ip = "127.0.0.1";
  25737. port = 0;
  25738. }
  25739. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25740. ip = "127.0.0.1";
  25741. port = 0;
  25742. }
  25743. socket_t socket() const override { return INVALID_SOCKET; }
  25744. time_t duration() const override { return 0; }
  25745. int writes = 0;
  25746. private:
  25747. std::string data_;
  25748. size_t pos_ = 0;
  25749. };
  25750. TEST(WebSocketFrameTest, AFrameGoesOutWithItsHeaderInOneWrite) {
  25751. // Under TCP_NODELAY each write is a segment of its own. Each length form,
  25752. // masked and not, reads back as written; a payload over one chunk follows
  25753. // its first in more writes.
  25754. for (auto len : {size_t(5), size_t(200), size_t(70000)}) {
  25755. for (auto mask : {false, true}) {
  25756. std::string body(len, '\0');
  25757. for (size_t i = 0; i < len; i++) {
  25758. body[i] = static_cast<char>(i % 251);
  25759. }
  25760. WsWriteCountingStream strm;
  25761. ASSERT_TRUE(detail::write_websocket_frame(
  25762. strm, ws::Opcode::Binary, body.data(), body.size(), true, mask));
  25763. if (len <= 4096) { EXPECT_EQ(1, strm.writes) << len << " " << mask; }
  25764. ws::Opcode opcode;
  25765. std::string payload;
  25766. bool fin = false;
  25767. ASSERT_EQ(
  25768. ws::impl::read_websocket_frame(strm, opcode, payload, fin, mask, 0),
  25769. ws::impl::FrameRead::Ok)
  25770. << len << " " << mask;
  25771. EXPECT_TRUE(fin);
  25772. EXPECT_EQ(ws::Opcode::Binary, opcode);
  25773. EXPECT_EQ(body, payload) << len << " " << mask;
  25774. }
  25775. }
  25776. }
  25777. // Hands out its pieces one read at a time, timing out between each two.
  25778. class WsTimeoutBetweenPiecesStream : public Stream {
  25779. public:
  25780. explicit WsTimeoutBetweenPiecesStream(std::vector<std::string> pieces)
  25781. : pieces_(std::move(pieces)) {}
  25782. bool is_readable() const override { return true; }
  25783. bool wait_readable() const override { return true; }
  25784. bool wait_writable() const override { return true; }
  25785. ssize_t read(char *ptr, size_t size) override {
  25786. if (time_out_) {
  25787. time_out_ = false;
  25788. error_ = Error::Timeout;
  25789. return -1;
  25790. }
  25791. if (i_ >= pieces_.size()) {
  25792. error_ = Error::ConnectionClosed;
  25793. return 0;
  25794. }
  25795. auto &piece = pieces_[i_];
  25796. auto n = (std::min)(size, piece.size() - at_);
  25797. memcpy(ptr, piece.data() + at_, n);
  25798. at_ += n;
  25799. if (at_ == piece.size()) {
  25800. i_++;
  25801. at_ = 0;
  25802. time_out_ = true;
  25803. }
  25804. return static_cast<ssize_t>(n);
  25805. }
  25806. ssize_t write(const char *, size_t size) override {
  25807. return static_cast<ssize_t>(size);
  25808. }
  25809. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25810. ip = "127.0.0.1";
  25811. port = 0;
  25812. }
  25813. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25814. ip = "127.0.0.1";
  25815. port = 0;
  25816. }
  25817. socket_t socket() const override { return INVALID_SOCKET; }
  25818. time_t duration() const override { return 0; }
  25819. private:
  25820. std::vector<std::string> pieces_;
  25821. size_t i_ = 0;
  25822. size_t at_ = 0;
  25823. bool time_out_ = false;
  25824. };
  25825. TEST(WebSocketFrameTest, ATimeoutInsideAFrameKeepsWhatWasRead) {
  25826. // FIN + Text, masked with an all-zero key: "Hello" goes out verbatim
  25827. std::string frame = "\x81\x85";
  25828. frame.append(4, '\0');
  25829. frame += "Hello";
  25830. // The header's first byte, then its second with half the mask key, then
  25831. // the rest
  25832. std::vector<std::string> pieces = {frame.substr(0, 1), frame.substr(1, 3),
  25833. frame.substr(4)};
  25834. WsTimeoutBetweenPiecesStream strm(pieces);
  25835. ws::impl::FrameReader reader;
  25836. ws::Opcode opcode;
  25837. std::string payload;
  25838. bool fin = false;
  25839. for (int i = 0; i < 2; i++) {
  25840. EXPECT_EQ(ws::impl::FrameRead::Timeout,
  25841. reader.read(strm, opcode, payload, fin, true, 0));
  25842. EXPECT_TRUE(reader.begun());
  25843. }
  25844. ASSERT_EQ(ws::impl::FrameRead::Ok,
  25845. reader.read(strm, opcode, payload, fin, true, 0));
  25846. EXPECT_FALSE(reader.begun());
  25847. EXPECT_TRUE(fin);
  25848. EXPECT_EQ(ws::Opcode::Text, opcode);
  25849. EXPECT_EQ("Hello", payload);
  25850. // Read in one go, the frame cannot be gone on with after a timeout
  25851. WsTimeoutBetweenPiecesStream again(pieces);
  25852. EXPECT_EQ(
  25853. ws::impl::FrameRead::Fail,
  25854. ws::impl::read_websocket_frame(again, opcode, payload, fin, true, 0));
  25855. }
  25856. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25857. std::string body(2000, 'x');
  25858. std::string frame;
  25859. frame += static_cast<char>(0x82); // FIN + Binary
  25860. frame += static_cast<char>(126); // 16-bit length follows
  25861. frame += static_cast<char>(body.size() >> 8);
  25862. frame += static_cast<char>(body.size() & 0xff);
  25863. frame += body;
  25864. detail::BufferStream strm;
  25865. strm.write(frame.data(), frame.size());
  25866. ws::Opcode opcode;
  25867. std::string payload;
  25868. bool fin;
  25869. EXPECT_EQ(
  25870. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25871. ws::impl::FrameRead::Ok);
  25872. EXPECT_EQ(body, payload);
  25873. }
  25874. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25875. // The header announces the largest payload allowed, and only 3 bytes of it
  25876. // ever arrive.
  25877. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25878. std::string frame;
  25879. frame += static_cast<char>(0x82); // FIN + Binary
  25880. frame += static_cast<char>(127); // 64-bit length follows
  25881. for (int shift = 56; shift >= 0; shift -= 8) {
  25882. frame += static_cast<char>((len >> shift) & 0xff);
  25883. }
  25884. frame += "abc";
  25885. detail::BufferStream strm;
  25886. strm.write(frame.data(), frame.size());
  25887. ws::Opcode opcode;
  25888. std::string payload;
  25889. bool fin;
  25890. EXPECT_EQ(
  25891. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25892. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25893. ws::impl::FrameRead::Fail);
  25894. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25895. }
  25896. TEST(WebSocketTest, QueryStringInHandshake) {
  25897. Server svr;
  25898. std::mutex mtx;
  25899. std::string received_target;
  25900. std::string received_token;
  25901. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25902. {
  25903. std::lock_guard<std::mutex> lock(mtx);
  25904. received_target = req.target;
  25905. if (req.has_param("token")) {
  25906. received_token = req.get_param_value("token");
  25907. }
  25908. }
  25909. std::string msg;
  25910. while (ws.read(msg)) {
  25911. ws.send(msg);
  25912. }
  25913. });
  25914. auto port = svr.bind_to_any_port("localhost");
  25915. std::thread t([&]() { svr.listen_after_bind(); });
  25916. svr.wait_until_ready();
  25917. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25918. "/ws?token=ABC&session=123");
  25919. ASSERT_TRUE(client.connect());
  25920. // Round-trip ensures the handler has run and captured the request.
  25921. ASSERT_TRUE(client.send("hello"));
  25922. std::string msg;
  25923. ASSERT_TRUE(client.read(msg));
  25924. EXPECT_EQ("hello", msg);
  25925. client.close();
  25926. {
  25927. std::lock_guard<std::mutex> lock(mtx);
  25928. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25929. EXPECT_EQ("ABC", received_token);
  25930. }
  25931. svr.stop();
  25932. t.join();
  25933. }
  25934. // Run a handshake against a throwaway server and hand the request the server
  25935. // received back to the caller, so tests can assert on the headers the client
  25936. // actually put on the wire.
  25937. static void capture_websocket_handshake_request(
  25938. const Headers &client_headers,
  25939. std::function<void(const Request &, int port)> verify) {
  25940. Server svr;
  25941. std::mutex mtx;
  25942. Request received;
  25943. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25944. {
  25945. std::lock_guard<std::mutex> lock(mtx);
  25946. received = req;
  25947. }
  25948. std::string msg;
  25949. while (ws.read(msg)) {
  25950. ws.send(msg);
  25951. }
  25952. });
  25953. auto port = svr.bind_to_any_port("localhost");
  25954. std::thread t([&]() { svr.listen_after_bind(); });
  25955. auto se = detail::scope_exit([&] {
  25956. svr.stop();
  25957. t.join();
  25958. });
  25959. svr.wait_until_ready();
  25960. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25961. client_headers);
  25962. ASSERT_TRUE(client.connect());
  25963. ASSERT_TRUE(client.send("hello"));
  25964. std::string msg;
  25965. ASSERT_TRUE(client.read(msg));
  25966. client.close();
  25967. {
  25968. std::lock_guard<std::mutex> lock(mtx);
  25969. verify(received, port);
  25970. }
  25971. }
  25972. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25973. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25974. // Non-default port must be present in the Host header. Default ports
  25975. // (80/443) are omitted; that logic is covered by
  25976. // MakeHostAndPortStringTest.
  25977. EXPECT_EQ("localhost:" + std::to_string(port),
  25978. req.get_header_value("Host"));
  25979. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25980. req.get_header_value("User-Agent"));
  25981. EXPECT_FALSE(req.has_header("Accept"));
  25982. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25983. EXPECT_FALSE(req.has_header("Content-Length"));
  25984. });
  25985. }
  25986. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25987. capture_websocket_handshake_request(
  25988. {{"Host", "example.com"},
  25989. {"User-Agent", "custom-agent"},
  25990. {"X-Custom", "value"}},
  25991. [](const Request &req, int) {
  25992. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25993. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25994. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25995. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25996. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25997. });
  25998. }
  25999. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  26000. capture_websocket_handshake_request(
  26001. {{"Upgrade", "bogus"},
  26002. {"Connection", "close"},
  26003. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  26004. {"Sec-WebSocket-Version", "8"}},
  26005. [](const Request &req, int) {
  26006. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  26007. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  26008. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  26009. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  26010. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  26011. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  26012. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  26013. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  26014. req.get_header_value("Sec-WebSocket-Key"));
  26015. });
  26016. }
  26017. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  26018. // A header the client refuses to send must abort the handshake before any
  26019. // part of it reaches the wire; a lone request line would otherwise sit in
  26020. // the peer's buffer as a truncated request.
  26021. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  26022. ASSERT_NE(INVALID_SOCKET, srv);
  26023. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  26024. sockaddr_in addr{};
  26025. addr.sin_family = AF_INET;
  26026. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  26027. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26028. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  26029. ASSERT_EQ(0, ::listen(srv, 1));
  26030. sockaddr_in bound{};
  26031. socklen_t bound_len = sizeof(bound);
  26032. ASSERT_EQ(
  26033. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  26034. auto port = ntohs(bound.sin_port);
  26035. ssize_t received = -1;
  26036. std::thread t([&] {
  26037. // Bound every blocking call so a regression fails the test with a bad
  26038. // value instead of hanging the suite.
  26039. fd_set rfds;
  26040. FD_ZERO(&rfds);
  26041. FD_SET(srv, &rfds);
  26042. timeval tv{5, 0};
  26043. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  26044. 0) {
  26045. return;
  26046. }
  26047. sockaddr_in cli_addr{};
  26048. socklen_t cli_len = sizeof(cli_addr);
  26049. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  26050. if (cli == INVALID_SOCKET) { return; }
  26051. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  26052. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26053. char buf[4096];
  26054. received = ::recv(cli, buf, sizeof(buf), 0);
  26055. });
  26056. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  26057. // connect() has already shut the socket down by the time it returns false,
  26058. // so the peer sees EOF without waiting for the client to be destroyed.
  26059. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  26060. {{"X-Bad", "a\r\nInjected: 1"}});
  26061. EXPECT_FALSE(client.connect());
  26062. t.join();
  26063. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  26064. EXPECT_EQ(0, received);
  26065. }
  26066. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  26067. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  26068. // contains "upgrade" as a substring is a different token and must not
  26069. // start a WebSocket handshake.
  26070. auto make_request = [](const std::vector<std::string> &connection_values) {
  26071. Request req;
  26072. req.method = "GET";
  26073. req.headers.emplace("Upgrade", "websocket");
  26074. for (const auto &value : connection_values) {
  26075. req.headers.emplace("Connection", value);
  26076. }
  26077. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  26078. req.headers.emplace("Sec-WebSocket-Version", "13");
  26079. return req;
  26080. };
  26081. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  26082. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  26083. EXPECT_TRUE(
  26084. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  26085. EXPECT_TRUE(
  26086. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  26087. EXPECT_TRUE(
  26088. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  26089. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  26090. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  26091. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  26092. EXPECT_FALSE(
  26093. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  26094. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  26095. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  26096. }
  26097. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  26098. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  26099. // asks recipients to match each protocol-name case-insensitively, and RFC
  26100. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  26101. // client naming websocket alongside another protocol, or on a second field
  26102. // line, is offering websocket; a value that merely contains "websocket" as a
  26103. // substring is a different protocol name and is not.
  26104. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  26105. Request req;
  26106. req.method = "GET";
  26107. for (const auto &value : upgrade_values) {
  26108. req.headers.emplace("Upgrade", value);
  26109. }
  26110. req.headers.emplace("Connection", "Upgrade");
  26111. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  26112. req.headers.emplace("Sec-WebSocket-Version", "13");
  26113. return req;
  26114. };
  26115. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  26116. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  26117. EXPECT_TRUE(
  26118. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  26119. EXPECT_TRUE(
  26120. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  26121. EXPECT_TRUE(
  26122. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  26123. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  26124. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  26125. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  26126. EXPECT_FALSE(
  26127. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  26128. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  26129. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  26130. }
  26131. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  26132. Server svr;
  26133. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  26134. auto port = svr.bind_to_any_port("localhost");
  26135. std::thread t([&]() { svr.listen_after_bind(); });
  26136. auto se = detail::scope_exit([&] {
  26137. svr.stop();
  26138. t.join();
  26139. });
  26140. svr.wait_until_ready();
  26141. Headers headers = {{"Upgrade", "websocket"},
  26142. {"Connection", "notupgrade"},
  26143. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  26144. {"Sec-WebSocket-Version", "13"}};
  26145. Client cli("localhost", port);
  26146. auto res = cli.Get("/ws", headers);
  26147. // The route exists only as a WebSocket route, so a request that fails the
  26148. // handshake check falls through to ordinary routing.
  26149. ASSERT_TRUE(res);
  26150. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  26151. }
  26152. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  26153. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  26154. // Connection value is the only thing left for the client to reject.
  26155. Server svr;
  26156. svr.Get("/ws", [](const Request &req, Response &res) {
  26157. res.status = StatusCode::SwitchingProtocol_101;
  26158. res.set_header("Upgrade", "websocket");
  26159. res.set_header("Connection", "notupgrade");
  26160. res.set_header("Sec-WebSocket-Accept",
  26161. detail::websocket_accept_key(
  26162. req.get_header_value("Sec-WebSocket-Key")));
  26163. });
  26164. auto port = svr.bind_to_any_port("localhost");
  26165. std::thread t([&]() { svr.listen_after_bind(); });
  26166. auto se = detail::scope_exit([&] {
  26167. svr.stop();
  26168. t.join();
  26169. });
  26170. svr.wait_until_ready();
  26171. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  26172. auto res = client.connect();
  26173. EXPECT_FALSE(res);
  26174. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  26175. EXPECT_FALSE(client.is_open());
  26176. }
  26177. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  26178. Server svr;
  26179. svr.Get("/ws", [](const Request &req, Response &res) {
  26180. res.status = StatusCode::SwitchingProtocol_101;
  26181. res.set_header("Upgrade", "websocket");
  26182. res.set_header("Connection", "Upgrade");
  26183. res.set_header("Sec-WebSocket-Accept",
  26184. detail::websocket_accept_key(
  26185. req.get_header_value("Sec-WebSocket-Key")));
  26186. res.set_header("Sec-WebSocket-Protocol", "admin");
  26187. });
  26188. auto port = svr.bind_to_any_port("localhost");
  26189. std::thread t([&]() { svr.listen_after_bind(); });
  26190. auto se = detail::scope_exit([&] {
  26191. svr.stop();
  26192. t.join();
  26193. });
  26194. svr.wait_until_ready();
  26195. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  26196. // Server selects a subprotocol the client never offered
  26197. {
  26198. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  26199. ws::WebSocketClient client(url, headers);
  26200. auto res = client.connect();
  26201. EXPECT_FALSE(res);
  26202. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  26203. EXPECT_FALSE(client.is_open());
  26204. EXPECT_TRUE(client.subprotocol().empty());
  26205. }
  26206. // Client offered none but the server named one anyway
  26207. {
  26208. ws::WebSocketClient client(url);
  26209. auto res = client.connect();
  26210. EXPECT_FALSE(res);
  26211. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  26212. EXPECT_FALSE(client.is_open());
  26213. EXPECT_TRUE(client.subprotocol().empty());
  26214. }
  26215. }
  26216. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  26217. // The socket path doubles as the URL host, so it must not contain '/'.
  26218. const char *shard = getenv("GTEST_SHARD_INDEX");
  26219. const std::string sock_path =
  26220. shard ? std::string("httplib-ws-") + shard + ".sock"
  26221. : std::string("httplib-ws.sock");
  26222. std::remove(sock_path.c_str());
  26223. Server svr;
  26224. std::mutex mtx;
  26225. std::string received_host;
  26226. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  26227. {
  26228. std::lock_guard<std::mutex> lock(mtx);
  26229. received_host = req.get_header_value("Host");
  26230. }
  26231. std::string msg;
  26232. while (ws.read(msg)) {
  26233. ws.send(msg);
  26234. }
  26235. });
  26236. svr.set_address_family(AF_UNIX);
  26237. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  26238. auto se = detail::scope_exit([&] {
  26239. svr.stop();
  26240. t.join();
  26241. std::remove(sock_path.c_str());
  26242. });
  26243. svr.wait_until_ready();
  26244. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  26245. client.set_address_family(AF_UNIX);
  26246. ASSERT_TRUE(client.connect());
  26247. ASSERT_TRUE(client.send("hello"));
  26248. std::string msg;
  26249. ASSERT_TRUE(client.read(msg));
  26250. client.close();
  26251. {
  26252. std::lock_guard<std::mutex> lock(mtx);
  26253. // There is no host:port for a Unix socket, so the same "localhost"
  26254. // placeholder the HTTP client uses is expected.
  26255. EXPECT_EQ("localhost", received_host);
  26256. }
  26257. }
  26258. // Two threads must never parse WebSocket frames from the same stream.
  26259. // close() used to read the peer's Close reply with its own frame read, so it
  26260. // raced a reader thread that was in the middle of a payload: the payload loop
  26261. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  26262. // so bytes taken by close() were replaced with bytes from further along the
  26263. // stream. The message kept its length and silently changed content.
  26264. //
  26265. // The raw peer below sends a frame header plus part of the payload, waits for
  26266. // the handler to call close(), and only then sends the rest. Whichever thread
  26267. // would win the race for those bytes, the message must arrive intact, because
  26268. // close() must not touch the stream while read() owns it.
  26269. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  26270. #ifndef _WIN32
  26271. signal(SIGPIPE, SIG_IGN);
  26272. #endif
  26273. const size_t payload_len = 120; // fits the 7-bit length field
  26274. const size_t prefix_len = 8;
  26275. const int attempts = 8;
  26276. std::string expected(payload_len, '\0');
  26277. for (size_t i = 0; i < payload_len; i++) {
  26278. expected[i] = static_cast<char>('a' + i % 26);
  26279. }
  26280. std::atomic<bool> peer_stalled{false};
  26281. std::atomic<bool> handler_done{false};
  26282. std::mutex received_mutex;
  26283. std::vector<std::string> received;
  26284. // Bound every wait, so a regression fails the test instead of hanging the
  26285. // suite.
  26286. auto wait_for = [](const std::atomic<bool> &flag) {
  26287. for (int i = 0; i < 500 && !flag; i++) {
  26288. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26289. }
  26290. };
  26291. Server svr;
  26292. svr.set_websocket_ping_interval(0);
  26293. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26294. std::thread reader([&]() {
  26295. std::string msg;
  26296. while (ws.read(msg)) {
  26297. std::lock_guard<std::mutex> guard(received_mutex);
  26298. received.push_back(msg);
  26299. }
  26300. });
  26301. // Wait until the peer stalls mid-payload, so the reader thread is parked
  26302. // inside a frame when close() runs.
  26303. wait_for(peer_stalled);
  26304. ws.close();
  26305. reader.join();
  26306. handler_done = true;
  26307. });
  26308. auto port = svr.bind_to_any_port("127.0.0.1");
  26309. std::thread t([&]() { svr.listen_after_bind(); });
  26310. auto se = detail::scope_exit([&] {
  26311. svr.stop();
  26312. t.join();
  26313. });
  26314. svr.wait_until_ready();
  26315. auto send_bytes = [](socket_t s, const std::string &data) {
  26316. #ifdef _WIN32
  26317. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  26318. #else
  26319. auto n = ::send(s, data.data(), data.size(), 0);
  26320. #endif
  26321. return n == static_cast<decltype(n)>(data.size());
  26322. };
  26323. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  26324. // Every length used here fits the 7-bit length field.
  26325. auto masked_header = [](uint8_t first_byte, size_t len) {
  26326. std::string h;
  26327. h += static_cast<char>(first_byte);
  26328. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  26329. h.append(4, '\0'); // mask key
  26330. return h;
  26331. };
  26332. for (int attempt = 0; attempt < attempts; attempt++) {
  26333. peer_stalled = false;
  26334. handler_done = false;
  26335. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26336. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  26337. auto se_sock = detail::scope_exit([&] {
  26338. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  26339. });
  26340. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26341. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  26342. sockaddr_in addr{};
  26343. addr.sin_family = AF_INET;
  26344. addr.sin_port = htons(static_cast<uint16_t>(port));
  26345. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26346. ASSERT_EQ(
  26347. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  26348. << "attempt " << attempt;
  26349. ASSERT_TRUE(send_bytes(sock,
  26350. "GET /ws HTTP/1.1\r\n"
  26351. "Host: 127.0.0.1\r\n"
  26352. "Upgrade: websocket\r\n"
  26353. "Connection: Upgrade\r\n"
  26354. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26355. "Sec-WebSocket-Version: 13\r\n"
  26356. "\r\n"))
  26357. << "attempt " << attempt;
  26358. std::string response;
  26359. while (response.find("\r\n\r\n") == std::string::npos) {
  26360. char buf[512];
  26361. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  26362. if (n <= 0) { break; }
  26363. response.append(buf, static_cast<size_t>(n));
  26364. }
  26365. ASSERT_NE(std::string::npos, response.find(" 101 "))
  26366. << "attempt " << attempt;
  26367. // Send the header of a Binary message but only the first prefix_len bytes
  26368. // of its payload, leaving the reader thread stalled inside the payload.
  26369. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  26370. expected.substr(0, prefix_len)))
  26371. << "attempt " << attempt;
  26372. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26373. peer_stalled = true;
  26374. // Let close() send its Close frame and park in its own read before the
  26375. // rest of the payload arrives, so both threads are waiting for it.
  26376. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26377. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  26378. close_frame += static_cast<char>(0x03); // status 1000
  26379. close_frame += static_cast<char>(0xE8);
  26380. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  26381. << "attempt " << attempt;
  26382. // Closing the peer releases the reader thread even on the buggy path,
  26383. // where it waits for bytes another thread already consumed.
  26384. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26385. detail::close_socket(sock);
  26386. sock = INVALID_SOCKET;
  26387. wait_for(handler_done);
  26388. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  26389. }
  26390. std::lock_guard<std::mutex> guard(received_mutex);
  26391. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  26392. << "a message in flight when close() ran was dropped";
  26393. for (size_t i = 0; i < received.size(); i++) {
  26394. EXPECT_EQ(expected, received[i]) << "message " << i;
  26395. }
  26396. }
  26397. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  26398. // returning the socket, or INVALID_SOCKET.
  26399. static socket_t connect_raw_websocket(int port, const std::string &path) {
  26400. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26401. if (sock == INVALID_SOCKET) { return sock; }
  26402. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26403. sockaddr_in addr{};
  26404. addr.sin_family = AF_INET;
  26405. addr.sin_port = htons(static_cast<uint16_t>(port));
  26406. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26407. std::string req = "GET " + path +
  26408. " HTTP/1.1\r\n"
  26409. "Host: 127.0.0.1\r\n"
  26410. "Upgrade: websocket\r\n"
  26411. "Connection: Upgrade\r\n"
  26412. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26413. "Sec-WebSocket-Version: 13\r\n"
  26414. "\r\n";
  26415. std::string res;
  26416. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  26417. detail::send_socket(sock, req.data(), req.size(), 0) ==
  26418. static_cast<ssize_t>(req.size())) {
  26419. char c;
  26420. while (res.find("\r\n\r\n") == std::string::npos &&
  26421. ::recv(sock, &c, 1, 0) == 1) {
  26422. res += c;
  26423. }
  26424. }
  26425. if (res.find(" 101 ") == std::string::npos) {
  26426. detail::close_socket(sock);
  26427. return INVALID_SOCKET;
  26428. }
  26429. return sock;
  26430. }
  26431. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  26432. // The payload must fit the 7-bit length field.
  26433. static std::string masked_frame(uint8_t first_byte,
  26434. const std::string &payload) {
  26435. std::string f;
  26436. f += static_cast<char>(first_byte);
  26437. f += static_cast<char>(0x80 | payload.size());
  26438. f.append(4, '\0');
  26439. return f + payload;
  26440. }
  26441. // Sends frames on a new raw connection to /ws and returns the first n bytes the
  26442. // server sends back, or what came before it closed.
  26443. static std::string raw_websocket_reply(int port, const std::string &frames,
  26444. size_t n) {
  26445. auto sock = connect_raw_websocket(port, "/ws");
  26446. if (sock == INVALID_SOCKET) { return std::string(); }
  26447. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26448. std::string reply;
  26449. char buf[256];
  26450. while (reply.size() < n) {
  26451. auto got = ::recv(sock, buf, sizeof(buf), 0);
  26452. if (got <= 0) { break; }
  26453. reply.append(buf, static_cast<size_t>(got));
  26454. }
  26455. detail::close_socket(sock);
  26456. return reply;
  26457. }
  26458. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  26459. std::atomic<bool> done{false};
  26460. std::string received;
  26461. Server svr;
  26462. svr.set_websocket_ping_interval(0);
  26463. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26464. std::string msg;
  26465. if (ws.read(msg) == ws::Binary) { received = msg; }
  26466. done = true;
  26467. });
  26468. auto port = svr.bind_to_any_port("127.0.0.1");
  26469. std::thread t([&]() { svr.listen_after_bind(); });
  26470. auto se = detail::scope_exit([&] {
  26471. svr.stop();
  26472. t.join();
  26473. });
  26474. svr.wait_until_ready();
  26475. auto sock = connect_raw_websocket(port, "/ws");
  26476. ASSERT_NE(INVALID_SOCKET, sock);
  26477. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26478. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  26479. masked_frame(0x89, "p") + // FIN + Ping
  26480. masked_frame(0x80, "lo"); // FIN + Continuation
  26481. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26482. for (int i = 0; i < 500 && !done; i++) {
  26483. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26484. }
  26485. ASSERT_TRUE(done);
  26486. EXPECT_EQ("Hello", received);
  26487. // The Ping between the fragments is answered with a Pong.
  26488. char pong[3];
  26489. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  26490. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  26491. }
  26492. TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
  26493. #ifndef _WIN32
  26494. signal(SIGPIPE, SIG_IGN);
  26495. #endif
  26496. std::atomic<bool> read_ended{false};
  26497. std::atomic<bool> sending{true};
  26498. Server svr;
  26499. svr.set_websocket_ping_interval(0);
  26500. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26501. std::thread reader([&]() {
  26502. std::string msg;
  26503. while (ws.read(msg)) {}
  26504. read_ended = true;
  26505. });
  26506. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26507. ws.close();
  26508. reader.join();
  26509. });
  26510. auto port = svr.bind_to_any_port("127.0.0.1");
  26511. std::thread t([&]() { svr.listen_after_bind(); });
  26512. auto se = detail::scope_exit([&] {
  26513. svr.stop();
  26514. t.join();
  26515. });
  26516. svr.wait_until_ready();
  26517. auto sock = connect_raw_websocket(port, "/ws");
  26518. ASSERT_NE(INVALID_SOCKET, sock);
  26519. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26520. // A Text message whose empty continuation frames never end
  26521. std::thread sender([&]() {
  26522. auto data = masked_frame(0x01, "");
  26523. while (sending) {
  26524. data += masked_frame(0x00, "");
  26525. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  26526. return;
  26527. }
  26528. data.clear();
  26529. }
  26530. });
  26531. for (int i = 0; i < 300 && !read_ended; i++) {
  26532. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26533. }
  26534. sending = false;
  26535. sender.join();
  26536. EXPECT_TRUE(read_ended);
  26537. }
  26538. TEST(WebSocketTest, ServerMaxMessageLength) {
  26539. Server svr;
  26540. svr.set_websocket_ping_interval(0);
  26541. svr.set_websocket_max_message_length(100);
  26542. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26543. std::string msg;
  26544. while (ws.read(msg)) {
  26545. ws.send(msg);
  26546. }
  26547. });
  26548. auto port = svr.bind_to_any_port("127.0.0.1");
  26549. std::thread t([&]() { svr.listen_after_bind(); });
  26550. auto se = detail::scope_exit([&] {
  26551. svr.stop();
  26552. t.join();
  26553. });
  26554. svr.wait_until_ready();
  26555. const std::string ping(110, 'p');
  26556. const std::string half(50, 'a');
  26557. const std::string over(60, 'b');
  26558. const std::string too_big("\x88\x02\x03\xf1"); // Close 1009
  26559. // A Ping longer than the limit is answered, since the limit is for
  26560. // messages. A message at the limit is echoed, and one over it is refused
  26561. // although each of its frames is within it.
  26562. EXPECT_EQ(std::string("\x8a\x6e") + ping + "\x81\x64" + half + half + too_big,
  26563. raw_websocket_reply(
  26564. port,
  26565. masked_frame(0x89, ping) + masked_frame(0x01, half) +
  26566. masked_frame(0x80, half) + masked_frame(0x01, over) +
  26567. masked_frame(0x80, over),
  26568. 2 + ping.size() + 2 + 2 * half.size() + too_big.size()));
  26569. // A header that announces more than the limit is refused before its payload
  26570. EXPECT_EQ(too_big, raw_websocket_reply(port,
  26571. std::string("\x82\xfe\x03\xe8", 4) +
  26572. std::string(4, '\0'),
  26573. too_big.size()));
  26574. }
  26575. TEST(WebSocketTest, ClientMaxMessageLength) {
  26576. Server svr;
  26577. svr.set_websocket_ping_interval(0);
  26578. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26579. ws.send(std::string(1024, 'a'));
  26580. ws.send(std::string(2048, 'b'));
  26581. std::string msg;
  26582. while (ws.read(msg)) {}
  26583. });
  26584. auto port = svr.bind_to_any_port(HOST);
  26585. std::thread t([&]() { svr.listen_after_bind(); });
  26586. auto se = detail::scope_exit([&] {
  26587. svr.stop();
  26588. t.join();
  26589. });
  26590. svr.wait_until_ready();
  26591. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  26592. client.set_read_timeout(5, 0);
  26593. client.set_websocket_max_message_length(1024);
  26594. ASSERT_TRUE(client.connect());
  26595. std::string msg;
  26596. ASSERT_EQ(ws::Text, client.read(msg));
  26597. EXPECT_EQ(1024u, msg.size());
  26598. EXPECT_EQ(ws::Fail, client.read(msg));
  26599. EXPECT_FALSE(client.is_open());
  26600. // 0 lifts the limit
  26601. client.set_websocket_max_message_length(0);
  26602. ASSERT_TRUE(client.connect());
  26603. EXPECT_EQ(ws::Text, client.read(msg));
  26604. EXPECT_EQ(ws::Text, client.read(msg));
  26605. EXPECT_EQ(2048u, msg.size());
  26606. }
  26607. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  26608. Server svr;
  26609. svr.set_websocket_ping_interval(-1);
  26610. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26611. std::string msg;
  26612. while (ws.read(msg)) {}
  26613. });
  26614. auto port = svr.bind_to_any_port("127.0.0.1");
  26615. std::thread t([&]() { svr.listen_after_bind(); });
  26616. auto se = detail::scope_exit([&] {
  26617. svr.stop();
  26618. t.join();
  26619. });
  26620. svr.wait_until_ready();
  26621. auto sock = connect_raw_websocket(port, "/ws");
  26622. ASSERT_NE(INVALID_SOCKET, sock);
  26623. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26624. // Nothing comes while the client stays quiet.
  26625. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  26626. char c;
  26627. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  26628. }
  26629. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  26630. // and that has to end a read() already waiting on the peer, on every platform.
  26631. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  26632. // The peer sends no pings, and its handler never calls read(), which is
  26633. // where pongs are written.
  26634. std::mutex mutex;
  26635. std::condition_variable cv;
  26636. auto release = false;
  26637. svr.set_websocket_ping_interval(0);
  26638. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  26639. std::unique_lock<std::mutex> lock(mutex);
  26640. cv.wait(lock, [&] { return release; });
  26641. });
  26642. auto port = svr.bind_to_any_port(HOST);
  26643. std::thread t([&]() { svr.listen_after_bind(); });
  26644. auto se = detail::scope_exit([&] {
  26645. {
  26646. std::lock_guard<std::mutex> lock(mutex);
  26647. release = true;
  26648. }
  26649. cv.notify_all();
  26650. svr.stop();
  26651. t.join();
  26652. });
  26653. svr.wait_until_ready();
  26654. ws::WebSocketClient client(std::string(scheme) +
  26655. "://localhost:" + std::to_string(port) + "/ws");
  26656. #ifdef CPPHTTPLIB_SSL_ENABLED
  26657. client.enable_server_certificate_verification(false);
  26658. #endif
  26659. // A ping a second, given up on after two go unanswered: about 3s
  26660. client.set_websocket_ping_interval(1);
  26661. client.set_websocket_max_missed_pongs(2);
  26662. // Well past that, so that a read the timeout ends instead stands out
  26663. client.set_read_timeout(10);
  26664. ASSERT_TRUE(client.connect());
  26665. auto start = std::chrono::steady_clock::now();
  26666. std::string msg;
  26667. EXPECT_EQ(ws::Fail, client.read(msg));
  26668. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  26669. std::chrono::steady_clock::now() - start)
  26670. .count(),
  26671. 6000);
  26672. EXPECT_FALSE(client.is_open());
  26673. }
  26674. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  26675. Server svr;
  26676. check_pong_timeout_ends_read(svr, "ws");
  26677. }
  26678. #ifdef CPPHTTPLIB_SSL_ENABLED
  26679. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  26680. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26681. ASSERT_TRUE(svr.is_valid());
  26682. check_pong_timeout_ends_read(svr, "wss");
  26683. }
  26684. #endif
  26685. // listen() returns only after every handler has, so Server::stop() has to end
  26686. // a WebSocket handler's read() waiting on a client that stays connected and
  26687. // quiet, whether or not the handler bounded its reads, and the client's
  26688. // connection ends with it.
  26689. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  26690. bool bounded) {
  26691. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26692. if (bounded) { ws.set_read_timeout(0, 50000); }
  26693. std::string msg;
  26694. while (ws.read(msg) != ws::Fail) {}
  26695. });
  26696. auto port = svr.bind_to_any_port(HOST);
  26697. std::thread t([&]() { svr.listen_after_bind(); });
  26698. auto se = detail::scope_exit([&] {
  26699. if (t.joinable()) {
  26700. svr.stop();
  26701. t.join();
  26702. }
  26703. });
  26704. svr.wait_until_ready();
  26705. ws::WebSocketClient client(std::string(scheme) +
  26706. "://localhost:" + std::to_string(port) + "/ws");
  26707. #ifdef CPPHTTPLIB_SSL_ENABLED
  26708. client.enable_server_certificate_verification(false);
  26709. #endif
  26710. client.set_read_timeout(2);
  26711. ASSERT_TRUE(client.connect());
  26712. auto stopped = std::async(std::launch::async, [&] {
  26713. svr.stop();
  26714. t.join();
  26715. });
  26716. std::string msg;
  26717. EXPECT_EQ(ws::Fail, client.read(msg));
  26718. EXPECT_FALSE(client.is_open());
  26719. auto in_time =
  26720. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  26721. // A handler the stop did not reach ends when the client leaves
  26722. if (!in_time) { client.close(); }
  26723. stopped.wait();
  26724. EXPECT_TRUE(in_time);
  26725. }
  26726. TEST(WebSocketTest, StopEndsAWaitingRead) {
  26727. Server svr;
  26728. check_stop_ends_websocket_read(svr, "ws", false);
  26729. }
  26730. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  26731. Server svr;
  26732. check_stop_ends_websocket_read(svr, "ws", true);
  26733. }
  26734. #ifdef CPPHTTPLIB_SSL_ENABLED
  26735. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  26736. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26737. ASSERT_TRUE(svr.is_valid());
  26738. check_stop_ends_websocket_read(svr, "wss", false);
  26739. }
  26740. #endif
  26741. // The stop reaches the client as a Close with 1001 Going Away, not as a
  26742. // dropped connection, whether the handler waits for a message or for the rest
  26743. // of one: `sent` is what the client sends first. A `bounded` handler's reads
  26744. // time out inside the message as well, and the stop ends them too.
  26745. static void check_stop_closes_with_going_away(const std::string &sent,
  26746. bool bounded = false) {
  26747. Server svr;
  26748. svr.set_websocket_ping_interval(0);
  26749. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26750. if (bounded) { ws.set_read_timeout(0, 10000); }
  26751. std::string msg;
  26752. while (ws.read(msg) != ws::Fail) {}
  26753. });
  26754. auto port = svr.bind_to_any_port("127.0.0.1");
  26755. std::thread t([&]() { svr.listen_after_bind(); });
  26756. auto se = detail::scope_exit([&] {
  26757. svr.stop();
  26758. t.join();
  26759. });
  26760. svr.wait_until_ready();
  26761. // Closed before the join above, which a handler the stop did not reach
  26762. // would otherwise hold up.
  26763. auto sock = connect_raw_websocket(port, "/ws");
  26764. ASSERT_NE(INVALID_SOCKET, sock);
  26765. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26766. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  26767. detail::send_socket(sock, sent.data(), sent.size(), 0));
  26768. // Let the handler take what was sent and wait for more
  26769. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  26770. svr.stop();
  26771. // FIN + Close, its length, then the code: unmasked, from a server
  26772. std::string head;
  26773. char c;
  26774. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  26775. head += c;
  26776. }
  26777. const std::string reason = "server stopping";
  26778. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  26779. "\x03\xe9",
  26780. head);
  26781. }
  26782. TEST(WebSocketTest, StopClosesWithGoingAway) {
  26783. check_stop_closes_with_going_away("");
  26784. }
  26785. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26786. // A Text frame without FIN: the first fragment of a message
  26787. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26788. }
  26789. TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
  26790. check_stop_closes_with_going_away(masked_frame(0x01, "half"),
  26791. /*bounded=*/true);
  26792. }
  26793. // A handler that bounds its reads gets control back within its timeout even
  26794. // while a message arrives in pieces, and the message whole once the last has
  26795. // come: what was read of it is kept across the timeouts. Each of `pieces` is
  26796. // sent once read() has timed out twice since the one before was sent, so the
  26797. // second timeout came from a read() that had that piece to take.
  26798. static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
  26799. const std::string &expected) {
  26800. std::atomic<bool> done{false};
  26801. std::atomic<int> timeouts{0};
  26802. std::string received;
  26803. Server svr;
  26804. svr.set_websocket_ping_interval(0);
  26805. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26806. ws.set_read_timeout(0, 10000);
  26807. std::string msg;
  26808. ws::ReadResult r;
  26809. while ((r = ws.read(msg)) == ws::Timeout) {
  26810. timeouts++;
  26811. }
  26812. if (r == ws::Text) { received = msg; }
  26813. done = true;
  26814. });
  26815. auto port = svr.bind_to_any_port("127.0.0.1");
  26816. std::thread t([&]() { svr.listen_after_bind(); });
  26817. auto se = detail::scope_exit([&] {
  26818. svr.stop();
  26819. t.join();
  26820. });
  26821. svr.wait_until_ready();
  26822. auto sock = connect_raw_websocket(port, "/ws");
  26823. ASSERT_NE(INVALID_SOCKET, sock);
  26824. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26825. // Each piece goes out at once, not held back by Nagle's algorithm
  26826. ASSERT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  26827. for (size_t i = 0; i < pieces.size(); i++) {
  26828. ASSERT_EQ(static_cast<ssize_t>(pieces[i].size()),
  26829. detail::send_socket(sock, pieces[i].data(), pieces[i].size(), 0));
  26830. if (i + 1 == pieces.size()) { break; }
  26831. auto before = timeouts.load();
  26832. for (int j = 0; j < 5000 && timeouts < before + 2; j++) {
  26833. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  26834. }
  26835. ASSERT_GE(timeouts.load(), before + 2) << "piece " << i;
  26836. }
  26837. for (int i = 0; i < 5000 && !done; i++) {
  26838. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  26839. }
  26840. ASSERT_TRUE(done);
  26841. EXPECT_EQ(expected, received);
  26842. }
  26843. TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
  26844. // The header's first byte, then its second with half the mask key, then
  26845. // the rest: what a frame written in several writes may look like when
  26846. // Nagle's algorithm holds the later ones back for an ACK.
  26847. auto frame = masked_frame(0x81, "Hello"); // FIN + Text
  26848. check_bounded_read_resumes(
  26849. {frame.substr(0, 1), frame.substr(1, 3), frame.substr(4)}, "Hello");
  26850. }
  26851. TEST(WebSocketTest, BoundedReadResumesBetweenFragments) {
  26852. check_bounded_read_resumes(
  26853. {masked_frame(0x01, "Hel"), masked_frame(0x80, "lo")}, "Hello");
  26854. }
  26855. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26856. Server svr;
  26857. svr.set_websocket_ping_interval(0);
  26858. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26859. std::string msg;
  26860. while (ws.read(msg)) {}
  26861. });
  26862. auto port = svr.bind_to_any_port("127.0.0.1");
  26863. std::thread t([&]() { svr.listen_after_bind(); });
  26864. auto se = detail::scope_exit([&] {
  26865. svr.stop();
  26866. t.join();
  26867. });
  26868. svr.wait_until_ready();
  26869. // Each Close payload and the reply it should get: an echo when valid, 1002
  26870. // otherwise.
  26871. std::vector<std::pair<std::string, std::string>> cases = {
  26872. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26873. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26874. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26875. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26876. };
  26877. // Also between the fragments of a message.
  26878. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26879. for (const auto &c : cases) {
  26880. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26881. c.second,
  26882. raw_websocket_reply(port, prefix + masked_frame(0x88, c.first),
  26883. 2 + c.second.size()));
  26884. }
  26885. }
  26886. }
  26887. TEST(WebSocketTest, FailsABadFrameWithACloseStatus) {
  26888. Server svr;
  26889. svr.set_websocket_ping_interval(0);
  26890. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26891. std::string msg;
  26892. while (ws.read(msg)) {}
  26893. });
  26894. auto port = svr.bind_to_any_port("127.0.0.1");
  26895. std::thread t([&]() { svr.listen_after_bind(); });
  26896. auto se = detail::scope_exit([&] {
  26897. svr.stop();
  26898. t.join();
  26899. });
  26900. svr.wait_until_ready();
  26901. // A header that announces one byte over the limit, and none of its payload
  26902. std::string too_big = "\x82\xff";
  26903. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1;
  26904. for (int shift = 56; shift >= 0; shift -= 8) {
  26905. too_big += static_cast<char>((len >> shift) & 0xff);
  26906. }
  26907. too_big.append(4, '\0');
  26908. const std::string protocol_error("\x03\xea"); // 1002
  26909. const std::string too_big_error("\x03\xf1"); // 1009
  26910. // What the client sends and the status the server closes with
  26911. std::vector<std::pair<std::string, std::string>> cases = {
  26912. {masked_frame(0xc1, "a"), protocol_error}, // RSV1
  26913. {std::string("\x81\x01") + "a", protocol_error}, // not masked
  26914. {masked_frame(0x09, ""), protocol_error}, // fragmented Ping
  26915. {masked_frame(0x83, ""), protocol_error}, // reserved opcode
  26916. {masked_frame(0x8b, ""), protocol_error}, // reserved control opcode
  26917. {masked_frame(0x80, "a"), protocol_error}, // continuation, no start
  26918. {masked_frame(0x01, "a") + masked_frame(0x81, "b"),
  26919. protocol_error}, // a new message inside a fragmented one
  26920. {std::string("\x81\xff\x80", 3) + std::string(11, '\0'),
  26921. protocol_error}, // 64-bit length with its top bit set
  26922. {too_big, too_big_error},
  26923. };
  26924. for (const auto &c : cases) {
  26925. EXPECT_EQ(std::string("\x88\x02") + c.second,
  26926. raw_websocket_reply(port, c.first, 4));
  26927. }
  26928. }
  26929. TEST(WebSocketTest, ClientFailsAMaskedFrameWithProtocolError) {
  26930. SilentListener listener;
  26931. ASSERT_NE(INVALID_SOCKET, listener.sock);
  26932. // A peer that completes the handshake, then sends a masked frame, which a
  26933. // server must never do, and keeps what the client sends back.
  26934. std::string reply;
  26935. std::thread peer([&]() {
  26936. auto sock = listener.accept();
  26937. if (sock == INVALID_SOCKET) { return; }
  26938. std::string req;
  26939. char c;
  26940. while (req.find("\r\n\r\n") == std::string::npos &&
  26941. ::recv(sock, &c, 1, 0) == 1) {
  26942. req += c;
  26943. }
  26944. const std::string field = "Sec-WebSocket-Key: ";
  26945. auto pos = req.find(field);
  26946. if (pos != std::string::npos) {
  26947. pos += field.size();
  26948. auto key = req.substr(pos, req.find("\r\n", pos) - pos);
  26949. auto res = "HTTP/1.1 101 Switching Protocols\r\n"
  26950. "Upgrade: websocket\r\n"
  26951. "Connection: Upgrade\r\n"
  26952. "Sec-WebSocket-Accept: " +
  26953. detail::websocket_accept_key(key) + "\r\n\r\n" +
  26954. masked_frame(0x81, "a");
  26955. detail::send_socket(sock, res.data(), res.size(), 0);
  26956. // FIN + Close, masked with a length of 2, the mask key, the code
  26957. char buf[256];
  26958. while (reply.size() < 8) {
  26959. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26960. if (n <= 0) { break; }
  26961. reply.append(buf, static_cast<size_t>(n));
  26962. }
  26963. }
  26964. detail::close_socket(sock);
  26965. });
  26966. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(listener.port) +
  26967. "/ws");
  26968. auto connected = static_cast<bool>(client.connect());
  26969. std::string msg;
  26970. auto r = connected ? client.read(msg) : ws::Fail;
  26971. peer.join();
  26972. ASSERT_TRUE(connected);
  26973. EXPECT_EQ(ws::Fail, r);
  26974. detail::BufferStream strm;
  26975. strm.write(reply.data(), reply.size());
  26976. ws::Opcode opcode;
  26977. std::string payload;
  26978. bool fin;
  26979. ASSERT_EQ(
  26980. ws::impl::FrameRead::Ok,
  26981. ws::impl::read_websocket_frame(strm, opcode, payload, fin, true, 125));
  26982. EXPECT_EQ(ws::Opcode::Close, opcode);
  26983. EXPECT_EQ(std::string("\x03\xea"), payload);
  26984. }
  26985. // What a handler sees of the peer's close once read() has failed
  26986. TEST(WebSocketTest, HandlerSeesThePeersClose) {
  26987. std::mutex m;
  26988. std::condition_variable cv;
  26989. size_t handled = 0;
  26990. uint16_t seen_status = 0;
  26991. std::string seen_reason;
  26992. Server svr;
  26993. svr.set_websocket_ping_interval(0);
  26994. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26995. std::string msg;
  26996. while (ws.read(msg)) {}
  26997. std::lock_guard<std::mutex> lock(m);
  26998. seen_status = static_cast<uint16_t>(ws.close_status());
  26999. seen_reason = ws.close_reason();
  27000. handled++;
  27001. cv.notify_one();
  27002. });
  27003. auto port = svr.bind_to_any_port("127.0.0.1");
  27004. std::thread t([&]() { svr.listen_after_bind(); });
  27005. auto se = detail::scope_exit([&] {
  27006. svr.stop();
  27007. t.join();
  27008. });
  27009. svr.wait_until_ready();
  27010. auto expect_seen = [&](size_t n, uint16_t status, const std::string &reason,
  27011. const char *label) {
  27012. std::unique_lock<std::mutex> lock(m);
  27013. ASSERT_TRUE(cv.wait_for(lock, std::chrono::seconds(5), [&] {
  27014. return handled == n;
  27015. })) << label;
  27016. EXPECT_EQ(status, seen_status) << label;
  27017. EXPECT_EQ(reason, seen_reason) << label;
  27018. };
  27019. // What a raw client sends before it drops the connection
  27020. struct Case {
  27021. const char *label;
  27022. std::string sent;
  27023. uint16_t status;
  27024. std::string reason;
  27025. };
  27026. std::vector<Case> cases = {
  27027. {"application code", masked_frame(0x88, "\x0f\xa1logout"), 4001,
  27028. "logout"},
  27029. {"normal", masked_frame(0x88, "\x03\xe8"), 1000, ""},
  27030. {"no status", masked_frame(0x88, ""), 1005, ""},
  27031. {"malformed", masked_frame(0x88, "\x03"), 1002, ""},
  27032. {"no Close", masked_frame(0x81, "hi"), 1006, ""},
  27033. };
  27034. for (size_t i = 0; i < cases.size(); i++) {
  27035. auto sock = connect_raw_websocket(port, "/ws");
  27036. ASSERT_NE(INVALID_SOCKET, sock);
  27037. detail::send_socket(sock, cases[i].sent.data(), cases[i].sent.size(), 0);
  27038. detail::close_socket(sock);
  27039. expect_seen(i + 1, cases[i].status, cases[i].reason, cases[i].label);
  27040. }
  27041. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws");
  27042. ASSERT_TRUE(client.connect());
  27043. client.close(static_cast<ws::CloseStatus>(4001), "logout");
  27044. expect_seen(cases.size() + 1, 4001, "logout", "WebSocketClient");
  27045. }
  27046. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  27047. class WebSocketSSLIntegrationTest : public ::testing::Test {
  27048. protected:
  27049. void SetUp() override {
  27050. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  27051. SERVER_PRIVATE_KEY_FILE);
  27052. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  27053. std::string msg;
  27054. ws::ReadResult ret;
  27055. while ((ret = ws.read(msg))) {
  27056. if (ret == ws::Binary) {
  27057. ws.send(msg.data(), msg.size());
  27058. } else {
  27059. ws.send(msg);
  27060. }
  27061. }
  27062. });
  27063. port_ = server_->bind_to_any_port(HOST);
  27064. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27065. server_->wait_until_ready();
  27066. }
  27067. void TearDown() override {
  27068. server_->stop();
  27069. if (server_thread_.joinable()) { server_thread_.join(); }
  27070. }
  27071. std::unique_ptr<SSLServer> server_;
  27072. std::thread server_thread_;
  27073. int port_ = 0;
  27074. };
  27075. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  27076. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  27077. {
  27078. ws::WebSocketClient client(url);
  27079. client.enable_server_certificate_verification(false);
  27080. auto calls = 0;
  27081. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  27082. calls++;
  27083. return false;
  27084. });
  27085. EXPECT_FALSE(client.connect());
  27086. EXPECT_GT(calls, 0);
  27087. }
  27088. {
  27089. ws::WebSocketClient client(url);
  27090. client.enable_server_certificate_verification(false);
  27091. client.set_session_verifier([](tls::session_t) {
  27092. return SSLVerifierResponse::CertificateRejected;
  27093. });
  27094. EXPECT_FALSE(client.connect());
  27095. }
  27096. {
  27097. ws::WebSocketClient client(url);
  27098. client.enable_server_certificate_verification(false);
  27099. client.set_session_verifier([](tls::session_t) {
  27100. return SSLVerifierResponse::CertificateAccepted;
  27101. });
  27102. EXPECT_TRUE(client.connect());
  27103. }
  27104. }
  27105. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  27106. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  27107. "/ws-echo");
  27108. client.enable_server_certificate_verification(false);
  27109. ASSERT_TRUE(client.connect());
  27110. ASSERT_TRUE(client.is_open());
  27111. ASSERT_TRUE(client.send("Hello WSS"));
  27112. std::string msg;
  27113. EXPECT_EQ(ws::Text, client.read(msg));
  27114. EXPECT_EQ("Hello WSS", msg);
  27115. client.close();
  27116. }
  27117. TEST_F(WebSocketSSLIntegrationTest, UppercaseScheme) {
  27118. ws::WebSocketClient client("WSS://localhost:" + std::to_string(port_) +
  27119. "/ws-echo");
  27120. client.enable_server_certificate_verification(false);
  27121. EXPECT_TRUE(client.connect());
  27122. }
  27123. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  27124. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  27125. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  27126. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  27127. // client (without calling close() first) is the only path that runs
  27128. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  27129. // bug exactly.
  27130. //
  27131. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  27132. // when linked against an instrumented libssl; run under Valgrind to catch it
  27133. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  27134. // suite (the freed session otherwise stalls on the close handshake) — this test
  27135. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  27136. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  27137. {
  27138. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  27139. "/ws-echo");
  27140. client.enable_server_certificate_verification(false);
  27141. client.set_read_timeout(2, 0);
  27142. client.set_write_timeout(2, 0);
  27143. ASSERT_TRUE(client.connect());
  27144. ASSERT_TRUE(client.is_open());
  27145. ASSERT_TRUE(client.send("still open"));
  27146. // Intentionally do NOT call client.close(): leaving scope runs
  27147. // shutdown_and_close() with the WebSocket still open, which must send the
  27148. // close frame while the TLS session is still alive.
  27149. }
  27150. }
  27151. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  27152. // shutdown_and_close() at the start of connect(), reproducing the same
  27153. // use-after-free within the test body rather than at scope exit. The second
  27154. // connect must succeed and echo, proving the close handshake ran over a live
  27155. // session. See the note above about memory-tool requirements.
  27156. TEST_F(WebSocketSSLIntegrationTest,
  27157. ReconnectWhileOpenSendsCloseOverLiveSession) {
  27158. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  27159. "/ws-echo");
  27160. client.enable_server_certificate_verification(false);
  27161. client.set_read_timeout(2, 0);
  27162. client.set_write_timeout(2, 0);
  27163. ASSERT_TRUE(client.connect());
  27164. ASSERT_TRUE(client.is_open());
  27165. ASSERT_TRUE(client.send("still open"));
  27166. // Reconnect without closing first: connect() calls shutdown_and_close() on
  27167. // the still-open connection, which must not touch a freed TLS session.
  27168. ASSERT_TRUE(client.connect());
  27169. ASSERT_TRUE(client.is_open());
  27170. ASSERT_TRUE(client.send("after reconnect"));
  27171. std::string msg;
  27172. EXPECT_EQ(ws::Text, client.read(msg));
  27173. EXPECT_EQ("after reconnect", msg);
  27174. client.close();
  27175. }
  27176. #endif
  27177. #ifdef CPPHTTPLIB_SSL_ENABLED
  27178. class WebSocketSSLCATest : public ::testing::Test {
  27179. protected:
  27180. void SetUp() override {
  27181. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  27182. SERVER_PRIVATE_KEY_FILE);
  27183. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  27184. std::string msg;
  27185. while (ws.read(msg)) {
  27186. ws.send(msg);
  27187. }
  27188. });
  27189. port_ = server_->bind_to_any_port("127.0.0.1");
  27190. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27191. server_->wait_until_ready();
  27192. }
  27193. void TearDown() override {
  27194. server_->stop();
  27195. if (server_thread_.joinable()) { server_thread_.join(); }
  27196. }
  27197. std::string url() const {
  27198. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  27199. }
  27200. std::unique_ptr<SSLServer> server_;
  27201. std::thread server_thread_;
  27202. int port_ = 0;
  27203. };
  27204. // A custom CA loaded as PEM verifies the server with full certificate
  27205. // verification enabled
  27206. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  27207. ws::WebSocketClient client(url());
  27208. std::string cert;
  27209. read_file(SERVER_CERT2_FILE, cert);
  27210. client.load_ca_cert_store(cert.c_str(), cert.size());
  27211. ASSERT_TRUE(client.connect());
  27212. ASSERT_TRUE(client.send("hello"));
  27213. std::string msg;
  27214. EXPECT_EQ(ws::Text, client.read(msg));
  27215. EXPECT_EQ("hello", msg);
  27216. client.close();
  27217. }
  27218. // A custom CA that does not cover the server must fail verification (the
  27219. // custom CA is exclusive; system certs are not loaded alongside it)
  27220. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  27221. ws::WebSocketClient client(url());
  27222. std::string cert;
  27223. read_file(CLIENT_CA_CERT_FILE, cert);
  27224. client.load_ca_cert_store(cert.c_str(), cert.size());
  27225. auto res = client.connect();
  27226. ASSERT_FALSE(res);
  27227. EXPECT_EQ(Error::SSLServerVerification, res.error());
  27228. EXPECT_EQ(-1, res.status());
  27229. EXPECT_NE(0u, res.ssl_backend_error());
  27230. }
  27231. // The same CA as a file path rather than PEM in memory
  27232. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  27233. ws::WebSocketClient client(url());
  27234. client.set_ca_cert_path(SERVER_CERT2_FILE);
  27235. ASSERT_TRUE(client.connect());
  27236. ASSERT_TRUE(client.send("hello"));
  27237. std::string msg;
  27238. EXPECT_EQ(ws::Text, client.read(msg));
  27239. EXPECT_EQ("hello", msg);
  27240. client.close();
  27241. }
  27242. // ...and a CA file that does not cover the server still fails, so it is the
  27243. // path above that decides the outcome
  27244. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  27245. ws::WebSocketClient client(url());
  27246. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  27247. ASSERT_FALSE(client.connect());
  27248. }
  27249. // Regression test: reconnecting with a native custom CA store used to reuse
  27250. // a store handle the previous TLS context had already freed (use-after-free
  27251. // under the OpenSSL backend). The context now lives as long as the client.
  27252. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  27253. ws::WebSocketClient client(url());
  27254. std::string cert;
  27255. read_file(SERVER_CERT2_FILE, cert);
  27256. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  27257. ASSERT_TRUE(client.connect());
  27258. client.close();
  27259. ASSERT_TRUE(client.connect());
  27260. ASSERT_TRUE(client.send("again"));
  27261. std::string msg;
  27262. EXPECT_EQ(ws::Text, client.read(msg));
  27263. EXPECT_EQ("again", msg);
  27264. client.close();
  27265. }
  27266. // Regression test: a certificate with a trusted chain but no identity match
  27267. // for the server IP must be rejected. The Mbed TLS backend used to skip
  27268. // verification entirely for IP hosts, so this connection succeeded there.
  27269. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  27270. // chain verification while the identity check must still fail.
  27271. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  27272. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  27273. ASSERT_TRUE(svr.is_valid());
  27274. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  27275. std::string msg;
  27276. while (ws.read(msg)) {
  27277. ws.send(msg);
  27278. }
  27279. });
  27280. auto port = svr.bind_to_any_port("127.0.0.1");
  27281. auto t = std::thread([&]() { svr.listen_after_bind(); });
  27282. auto se = detail::scope_exit([&] {
  27283. svr.stop();
  27284. t.join();
  27285. });
  27286. svr.wait_until_ready();
  27287. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  27288. "/echo");
  27289. std::string cert;
  27290. read_file(SERVER_CERT_FILE, cert);
  27291. client.load_ca_cert_store(cert.c_str(), cert.size());
  27292. ASSERT_FALSE(client.connect());
  27293. }
  27294. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  27295. // SNI, so nothing binds the host name to the TLS session. These bind the
  27296. // server to "localhost" instead, the only shape that exercises the SNI and
  27297. // hostname-verification path with certificate verification left enabled.
  27298. class WebSocketSSLDnsHostTest : public ::testing::Test {
  27299. protected:
  27300. void Start(const char *cert_file) {
  27301. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  27302. SERVER_PRIVATE_KEY_FILE);
  27303. ASSERT_TRUE(server_->is_valid());
  27304. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  27305. std::string msg;
  27306. while (ws.read(msg)) {
  27307. ws.send(msg);
  27308. }
  27309. });
  27310. port_ = server_->bind_to_any_port("localhost");
  27311. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27312. server_->wait_until_ready();
  27313. }
  27314. void TearDown() override {
  27315. if (server_) { server_->stop(); }
  27316. if (server_thread_.joinable()) { server_thread_.join(); }
  27317. }
  27318. std::string url() const {
  27319. return "wss://localhost:" + std::to_string(port_) + "/echo";
  27320. }
  27321. std::unique_ptr<SSLServer> server_;
  27322. std::thread server_thread_;
  27323. int port_ = 0;
  27324. };
  27325. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  27326. // out and the connection is usable
  27327. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  27328. Start(SERVER_CERT2_FILE);
  27329. ws::WebSocketClient client(url());
  27330. client.set_ca_cert_path(SERVER_CERT2_FILE);
  27331. ASSERT_TRUE(client.connect());
  27332. ASSERT_TRUE(client.send("hello"));
  27333. std::string msg;
  27334. EXPECT_EQ(ws::Text, client.read(msg));
  27335. EXPECT_EQ("hello", msg);
  27336. client.close();
  27337. }
  27338. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  27339. // while the identity check must still reject "localhost"
  27340. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  27341. Start(SERVER_CERT_FILE);
  27342. ws::WebSocketClient client(url());
  27343. client.set_ca_cert_path(SERVER_CERT_FILE);
  27344. auto res = client.connect();
  27345. ASSERT_FALSE(res);
  27346. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  27347. EXPECT_EQ(-1, res.status());
  27348. }
  27349. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  27350. // disabled: the chain is still checked, only the identity check is skipped
  27351. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  27352. Start(SERVER_CERT_FILE);
  27353. ws::WebSocketClient client(url());
  27354. client.set_ca_cert_path(SERVER_CERT_FILE);
  27355. client.enable_server_hostname_verification(false);
  27356. ASSERT_TRUE(client.connect());
  27357. ASSERT_TRUE(client.send("hello"));
  27358. std::string msg;
  27359. EXPECT_EQ(ws::Text, client.read(msg));
  27360. EXPECT_EQ("hello", msg);
  27361. client.close();
  27362. }
  27363. // A CA that did not sign the server certificate fails the chain, even though
  27364. // the name would match
  27365. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  27366. Start(SERVER_CERT2_FILE);
  27367. ws::WebSocketClient client(url());
  27368. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  27369. ASSERT_FALSE(client.connect());
  27370. }
  27371. // With verification disabled, neither the chain nor the name is checked
  27372. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  27373. Start(SERVER_CERT_FILE);
  27374. ws::WebSocketClient client(url());
  27375. client.enable_server_certificate_verification(false);
  27376. ASSERT_TRUE(client.connect());
  27377. ASSERT_TRUE(client.send("hello"));
  27378. std::string msg;
  27379. EXPECT_EQ(ws::Text, client.read(msg));
  27380. EXPECT_EQ("hello", msg);
  27381. client.close();
  27382. }
  27383. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  27384. protected:
  27385. void SetUp() override {
  27386. server_ = httplib::detail::make_unique<SSLServer>(
  27387. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  27388. ASSERT_TRUE(server_->is_valid());
  27389. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  27390. std::string msg;
  27391. while (ws.read(msg)) {
  27392. ws.send(msg);
  27393. }
  27394. });
  27395. port_ = server_->bind_to_any_port("localhost");
  27396. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27397. server_->wait_until_ready();
  27398. }
  27399. void TearDown() override {
  27400. server_->stop();
  27401. if (server_thread_.joinable()) { server_thread_.join(); }
  27402. }
  27403. std::string url() const {
  27404. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  27405. }
  27406. void ConnectWithClientCert(const std::string &client_cert_file,
  27407. const std::string &client_private_key_file,
  27408. const char *private_key_password) {
  27409. std::string cert_pem, key_pem;
  27410. read_file(client_cert_file, cert_pem);
  27411. read_file(client_private_key_file, key_pem);
  27412. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  27413. key_pem.c_str(), key_pem.size(),
  27414. private_key_password};
  27415. ConnectWithPem(pem);
  27416. }
  27417. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  27418. ws::WebSocketClient client(url(), pem);
  27419. ASSERT_TRUE(client.is_valid());
  27420. client.enable_server_certificate_verification(false);
  27421. ASSERT_TRUE(client.connect());
  27422. ASSERT_TRUE(client.send("hello"));
  27423. std::string msg;
  27424. EXPECT_EQ(ws::Text, client.read(msg));
  27425. EXPECT_EQ("hello", msg);
  27426. client.close();
  27427. }
  27428. std::unique_ptr<SSLServer> server_;
  27429. std::thread server_thread_;
  27430. int port_ = 0;
  27431. };
  27432. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  27433. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  27434. }
  27435. // Control for the tests above: the fixture's server really does require a
  27436. // client certificate, so it is the PEM the constructor installed that decides
  27437. // the outcome.
  27438. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  27439. ws::WebSocketClient client(url());
  27440. ASSERT_TRUE(client.is_valid());
  27441. client.enable_server_certificate_verification(false);
  27442. EXPECT_FALSE(client.connect());
  27443. }
  27444. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  27445. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  27446. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  27447. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  27448. }
  27449. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  27450. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  27451. std::string cert_pem, key_pem;
  27452. read_file(CLIENT_CERT_FILE, cert_pem);
  27453. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  27454. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  27455. std::vector<char> key(key_pem.begin(), key_pem.end());
  27456. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  27457. key.size(), nullptr};
  27458. ConnectWithPem(pem);
  27459. }
  27460. #endif
  27461. #if !defined(_WIN32)
  27462. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  27463. auto secret_dir = std::string("./symlink_test_secret");
  27464. auto served_dir = std::string("./symlink_test_served");
  27465. auto secret_file = secret_dir + "/secret.txt";
  27466. auto symlink_path = served_dir + "/escape";
  27467. // Setup: create directories and files
  27468. mkdir(secret_dir.c_str(), 0755);
  27469. mkdir(served_dir.c_str(), 0755);
  27470. {
  27471. std::ofstream ofs(secret_file);
  27472. ofs << "SECRET_DATA";
  27473. }
  27474. // Create symlink using absolute path so it resolves correctly
  27475. #ifdef PATH_MAX
  27476. char abs_secret[PATH_MAX];
  27477. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  27478. #else
  27479. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  27480. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  27481. ASSERT_NE(nullptr, abs_secret);
  27482. #endif
  27483. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  27484. auto se = detail::scope_exit([&] {
  27485. unlink(symlink_path.c_str());
  27486. unlink(secret_file.c_str());
  27487. rmdir(served_dir.c_str());
  27488. rmdir(secret_dir.c_str());
  27489. });
  27490. Server svr;
  27491. svr.set_mount_point("/", served_dir);
  27492. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27493. auto se2 = detail::scope_exit([&] {
  27494. svr.stop();
  27495. listen_thread.join();
  27496. });
  27497. svr.wait_until_ready();
  27498. Client cli("localhost", PORT);
  27499. // Symlink pointing outside base dir should be blocked
  27500. auto res = cli.Get("/escape/secret.txt");
  27501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27502. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27503. }
  27504. #else
  27505. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  27506. auto secret_dir = std::string("junction_test_secret");
  27507. auto served_dir = std::string("junction_test_served");
  27508. auto secret_file = secret_dir + "\\secret.txt";
  27509. auto junction_path = served_dir + "\\escape";
  27510. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  27511. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  27512. {
  27513. std::ofstream ofs(secret_file);
  27514. ofs << "SECRET_DATA";
  27515. }
  27516. // A junction needs no privilege to create, unlike a symlink
  27517. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  27518. ASSERT_EQ(0, std::system(cmd.c_str()));
  27519. auto se = detail::scope_exit([&] {
  27520. ::RemoveDirectoryA(junction_path.c_str());
  27521. std::remove(secret_file.c_str());
  27522. ::RemoveDirectoryA(served_dir.c_str());
  27523. ::RemoveDirectoryA(secret_dir.c_str());
  27524. });
  27525. Server svr;
  27526. svr.set_mount_point("/", served_dir);
  27527. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27528. auto se2 = detail::scope_exit([&] {
  27529. svr.stop();
  27530. listen_thread.join();
  27531. });
  27532. svr.wait_until_ready();
  27533. Client cli("localhost", PORT);
  27534. // Junction pointing outside base dir should be blocked
  27535. auto res = cli.Get("/escape/secret.txt");
  27536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27537. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27538. }
  27539. #endif
  27540. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  27541. // "GET /smuggled" request), reads the first response, and only then sends the
  27542. // embedded request as the body. Returns how many times /smuggled ran.
  27543. //
  27544. // The body is sent AFTER receiving the first response (as in the original
  27545. // PoC) so that the stream_line_reader cannot buffer it together with the
  27546. // headers of the first request.
  27547. static int count_smuggled_requests(const std::string &outer_head,
  27548. std::string &first_response) {
  27549. Server svr;
  27550. svr.set_mount_point("/", "./www");
  27551. std::atomic<int> smuggled_count(0);
  27552. svr.Get("/smuggled", [&](const Request &, Response &res) {
  27553. smuggled_count++;
  27554. res.set_content("oops", "text/plain");
  27555. });
  27556. svr.Post("/post", [&](const Request &req, Response &res) {
  27557. res.set_content(req.body, "text/plain");
  27558. });
  27559. auto port = svr.bind_to_any_port("localhost");
  27560. thread t = thread([&] { svr.listen_after_bind(); });
  27561. auto se = detail::scope_exit([&] {
  27562. svr.stop();
  27563. t.join();
  27564. });
  27565. svr.wait_until_ready();
  27566. auto error = Error::Success;
  27567. auto sock = detail::create_client_socket(
  27568. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  27569. /*connection_timeout_sec=*/2, 0,
  27570. /*read_timeout_sec=*/2, 0,
  27571. /*write_timeout_sec=*/2, 0, std::string(), error);
  27572. EXPECT_NE(INVALID_SOCKET, sock);
  27573. if (sock == INVALID_SOCKET) { return -1; }
  27574. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27575. // The "smuggled" request will be sent as the body of the outer request
  27576. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  27577. "Host: localhost\r\n"
  27578. "Connection: close\r\n"
  27579. "\r\n";
  27580. auto head = outer_head;
  27581. auto len = std::to_string(smuggled.size());
  27582. for (auto pos = head.find("{len}"); pos != std::string::npos;
  27583. pos = head.find("{len}", pos + len.size())) {
  27584. head.replace(pos, 5, len);
  27585. }
  27586. // Step 1: Send only the outer request headers (no body yet)
  27587. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  27588. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  27589. // Step 2: Read the first response
  27590. char buf[4096];
  27591. for (;;) {
  27592. auto n = recv(sock, buf, sizeof(buf), 0);
  27593. if (n <= 0) break;
  27594. first_response.append(buf, static_cast<size_t>(n));
  27595. // Stop once we have a complete response (headers + body)
  27596. auto hdr_end = first_response.find("\r\n\r\n");
  27597. if (hdr_end != std::string::npos) {
  27598. // Check for Content-Length to know when the body is complete
  27599. auto cl_pos = first_response.find("Content-Length:");
  27600. if (cl_pos != std::string::npos) {
  27601. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  27602. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  27603. auto cl = std::stoul(
  27604. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  27605. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  27606. } else {
  27607. break; // No Content-Length, assume headers-only response
  27608. }
  27609. }
  27610. }
  27611. // Step 3: Now send the body, which looks like a new HTTP request. On a
  27612. // vulnerable server the keep-alive loop reads this as a second request. The
  27613. // server may already have closed the connection, so the result is ignored.
  27614. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  27615. // Half-close so that a server which drained the body sees EOF and closes,
  27616. // instead of the read below waiting for the read timeout.
  27617. #ifdef _WIN32
  27618. ::shutdown(sock, SD_SEND);
  27619. #else
  27620. ::shutdown(sock, SHUT_WR);
  27621. #endif
  27622. // Step 4: Read until the server closes the connection
  27623. for (;;) {
  27624. auto n = recv(sock, buf, sizeof(buf), 0);
  27625. if (n <= 0) break;
  27626. }
  27627. return smuggled_count.load();
  27628. }
  27629. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  27630. // A GET request with Content-Length to a static file handler must have its
  27631. // body drained before the keep-alive connection is reused. Otherwise the
  27632. // unread body bytes are interpreted as the next HTTP request.
  27633. std::string first_response;
  27634. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27635. "Host: localhost\r\n"
  27636. "Content-Length: {len}\r\n"
  27637. "\r\n",
  27638. first_response));
  27639. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  27640. }
  27641. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  27642. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  27643. // be answered with 400 and the connection closed. Treating it as "no body"
  27644. // leaves the body to be parsed as the next request.
  27645. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  27646. const char *targets[] = {
  27647. "GET /file", // handler that never reads the body
  27648. "GET /not-found", // no handler matches (404)
  27649. "POST /post", // handler that reads the body
  27650. };
  27651. for (auto target : targets) {
  27652. for (auto value : values) {
  27653. std::string first_response;
  27654. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  27655. " HTTP/1.1\r\n"
  27656. "Host: localhost\r\n"
  27657. "Content-Length: " +
  27658. value + "\r\n\r\n",
  27659. first_response))
  27660. << target << " with Content-Length: " << value;
  27661. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  27662. << target << " with Content-Length: " << value;
  27663. }
  27664. }
  27665. }
  27666. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  27667. // A 400 for an unparseable request line leaves the rest of the message
  27668. // unread, so the connection must be closed rather than reused.
  27669. std::string first_response;
  27670. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  27671. "Host: localhost\r\n"
  27672. "Content-Length: {len}\r\n"
  27673. "\r\n",
  27674. first_response));
  27675. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27676. }
  27677. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  27678. // Same as above for a header block that fails to parse.
  27679. std::string first_response;
  27680. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27681. "Host: localhost\r\n"
  27682. "Bad Header\r\n"
  27683. "Content-Length: {len}\r\n"
  27684. "\r\n",
  27685. first_response));
  27686. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27687. }
  27688. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  27689. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  27690. // server must not read another request on that connection, even when the
  27691. // request had no body to drain.
  27692. std::string first_response;
  27693. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  27694. "Host: localhost\r\n"
  27695. "\r\n",
  27696. first_response));
  27697. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  27698. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  27699. }
  27700. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  27701. // A content reader that stops early leaves the stream inside the body.
  27702. // Draining the whole Content-Length from there, or reading the body again,
  27703. // reads into the next request, and whatever follows is parsed as a request
  27704. // of its own.
  27705. Server svr;
  27706. std::atomic<int> smuggled_count(0);
  27707. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  27708. svr.Post("/upload", [](const Request &req, Response &res,
  27709. const ContentReader &content_reader) {
  27710. // Stop at the last chunk, so the whole body has been read however it
  27711. // arrives.
  27712. auto length = req.get_header_value_u64("Content-Length");
  27713. size_t total = 0;
  27714. auto consumed = content_reader([&](const char *, size_t n) {
  27715. total += n;
  27716. return total < length;
  27717. });
  27718. EXPECT_FALSE(consumed);
  27719. if (req.has_param("retry")) {
  27720. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  27721. }
  27722. // Replace the 400 the aborted read set, which would close the connection.
  27723. res.set_redirect("/done");
  27724. });
  27725. auto port = svr.bind_to_any_port(HOST);
  27726. thread t = thread([&] { svr.listen_after_bind(); });
  27727. auto se = detail::scope_exit([&] {
  27728. svr.stop();
  27729. t.join();
  27730. });
  27731. svr.wait_until_ready();
  27732. // A front end sees the second request as a POST whose body is the GET. The
  27733. // first body is as long as the POST's headers, so draining it again reads
  27734. // exactly those and leaves the GET to be parsed next.
  27735. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  27736. "Host: localhost\r\n"
  27737. "\r\n";
  27738. std::string second_head = "POST /post HTTP/1.1\r\n"
  27739. "Host: localhost\r\n"
  27740. "Content-Length: " +
  27741. std::to_string(inner.size()) +
  27742. "\r\n"
  27743. "\r\n";
  27744. for (auto target : {"/upload", "/upload?retry"}) {
  27745. smuggled_count = 0;
  27746. std::string request = "POST " + std::string(target) +
  27747. " HTTP/1.1\r\n"
  27748. "Host: localhost\r\n"
  27749. "Content-Length: " +
  27750. std::to_string(second_head.size()) +
  27751. "\r\n"
  27752. "\r\n" +
  27753. std::string(second_head.size(), 'A') + second_head +
  27754. inner;
  27755. std::string response;
  27756. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  27757. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  27758. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  27759. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  27760. EXPECT_EQ(0, smuggled_count.load()) << target;
  27761. }
  27762. }
  27763. // An error response closes the connection anyway, so the body is left unread
  27764. // with a redirect, such as one to a login page.
  27765. static void serve_redirects(Server &svr,
  27766. const std::function<void(int)> &client) {
  27767. svr.set_pre_routing_handler([](const Request &, Response &res) {
  27768. res.set_redirect("/login");
  27769. return Server::HandlerResponse::Handled;
  27770. });
  27771. auto port = svr.bind_to_any_port(HOST);
  27772. ASSERT_GT(port, 0);
  27773. thread t = thread([&] { svr.listen_after_bind(); });
  27774. auto se = detail::scope_exit([&] {
  27775. svr.stop();
  27776. t.join();
  27777. ASSERT_FALSE(svr.is_running());
  27778. });
  27779. svr.wait_until_ready();
  27780. client(port);
  27781. }
  27782. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  27783. Server svr;
  27784. serve_redirects(svr, [](int port) {
  27785. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  27786. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  27787. std::to_string(body.size()) + "\r\n\r\n" + body +
  27788. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  27789. std::string resp;
  27790. ASSERT_TRUE(send_request(1, req, &resp, port));
  27791. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  27792. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  27793. });
  27794. }
  27795. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  27796. Server svr;
  27797. svr.set_read_timeout(0, 200000);
  27798. serve_redirects(svr, [](int port) {
  27799. // A byte every 100 ms keeps each read within the read timeout, but not the
  27800. // body as a whole, so the server closes and the bytes sent after that fail.
  27801. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  27802. "Content-Length: 10\r\n\r\n"};
  27803. parts.resize(11, "x");
  27804. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  27805. });
  27806. }
  27807. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  27808. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  27809. // must be rejected with 400 Bad Request.
  27810. Server svr;
  27811. svr.Post("/test", [&](const Request &, Response &res) {
  27812. res.set_content("ok", "text/plain");
  27813. });
  27814. thread t = thread([&] { svr.listen(HOST, PORT); });
  27815. auto se = detail::scope_exit([&] {
  27816. svr.stop();
  27817. t.join();
  27818. ASSERT_FALSE(svr.is_running());
  27819. });
  27820. svr.wait_until_ready();
  27821. // Exact "chunked"
  27822. {
  27823. auto req = "POST /test HTTP/1.1\r\n"
  27824. "Host: localhost\r\n"
  27825. "Content-Length: 5\r\n"
  27826. "Transfer-Encoding: chunked\r\n"
  27827. "Connection: close\r\n"
  27828. "\r\n"
  27829. "hello";
  27830. std::string response;
  27831. ASSERT_TRUE(send_request(1, req, &response));
  27832. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27833. response.substr(0, response.find("\r\n")));
  27834. }
  27835. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  27836. {
  27837. auto req = "POST /test HTTP/1.1\r\n"
  27838. "Host: localhost\r\n"
  27839. "Content-Length: 5\r\n"
  27840. "Transfer-Encoding: gzip, chunked\r\n"
  27841. "Connection: close\r\n"
  27842. "\r\n"
  27843. "hello";
  27844. std::string response;
  27845. ASSERT_TRUE(send_request(1, req, &response));
  27846. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27847. response.substr(0, response.find("\r\n")));
  27848. }
  27849. }
  27850. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  27851. Server svr;
  27852. svr.Post("/test", [&](const Request &, Response &res) {
  27853. res.set_content("ok", "text/plain");
  27854. });
  27855. thread t = thread([&] { svr.listen(HOST, PORT); });
  27856. auto se = detail::scope_exit([&] {
  27857. svr.stop();
  27858. t.join();
  27859. ASSERT_FALSE(svr.is_running());
  27860. });
  27861. svr.wait_until_ready();
  27862. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  27863. // length cannot be determined, so the server must answer 400 and close
  27864. // rather than treat the request as bodyless and leave the body in the
  27865. // socket for the next request to pick up.
  27866. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  27867. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  27868. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  27869. std::string response;
  27870. ASSERT_TRUE(send_request(1, req, &response));
  27871. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27872. response.substr(0, response.find("\r\n")))
  27873. << transfer_encoding;
  27874. }
  27875. // RFC 9110 5.3: the codings may also be split across several
  27876. // Transfer-Encoding lines, which combine in the order they were received.
  27877. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  27878. // just like the single-line "chunked, gzip" above.
  27879. {
  27880. auto req = "POST /test HTTP/1.1\r\n"
  27881. "Host: localhost\r\n"
  27882. "Transfer-Encoding: chunked\r\n"
  27883. "Transfer-Encoding: gzip\r\n"
  27884. "\r\n"
  27885. "0\r\n\r\n";
  27886. std::string response;
  27887. ASSERT_TRUE(send_request(1, req, &response));
  27888. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27889. response.substr(0, response.find("\r\n")));
  27890. }
  27891. }
  27892. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  27893. Server svr;
  27894. svr.Post("/test", [&](const Request &, Response &res) {
  27895. res.set_content("ok", "text/plain");
  27896. });
  27897. auto port = svr.bind_to_any_port(HOST);
  27898. ASSERT_GT(port, 0);
  27899. thread t = thread([&] { svr.listen_after_bind(); });
  27900. auto se = detail::scope_exit([&] {
  27901. svr.stop();
  27902. t.join();
  27903. ASSERT_FALSE(svr.is_running());
  27904. });
  27905. svr.wait_until_ready();
  27906. for (auto transfer_encoding :
  27907. {"Transfer-Encoding: gzip, chunked\r\n",
  27908. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  27909. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  27910. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  27911. transfer_encoding + "\r\n0\r\n\r\n";
  27912. std::string response;
  27913. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  27914. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  27915. response.substr(0, response.find("\r\n")))
  27916. << transfer_encoding;
  27917. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  27918. << transfer_encoding;
  27919. }
  27920. }
  27921. // Regression for issue #2450: a DELETE without Content-Length on a
  27922. // keep-alive connection must not let the post-response drain consume the
  27923. // next request's bytes.
  27924. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  27925. Server svr;
  27926. std::atomic<int> delete_count(0);
  27927. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  27928. delete_count++;
  27929. res.status = StatusCode::NoContent_204;
  27930. });
  27931. auto port = svr.bind_to_any_port(HOST);
  27932. thread t = thread([&] { svr.listen_after_bind(); });
  27933. auto se = detail::scope_exit([&] {
  27934. svr.stop();
  27935. t.join();
  27936. });
  27937. svr.wait_until_ready();
  27938. auto error = Error::Success;
  27939. auto sock = detail::create_client_socket(
  27940. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27941. /*connection_timeout_sec=*/2, 0,
  27942. /*read_timeout_sec=*/2, 0,
  27943. /*write_timeout_sec=*/2, 0, std::string(), error);
  27944. ASSERT_NE(INVALID_SOCKET, sock);
  27945. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27946. auto send_request_and_read_response = [&](const std::string &req,
  27947. std::string &out) -> bool {
  27948. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  27949. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  27950. char buf[4096];
  27951. for (;;) {
  27952. auto n = recv(sock, buf, sizeof(buf), 0);
  27953. if (n <= 0) { return !out.empty(); }
  27954. out.append(buf, static_cast<size_t>(n));
  27955. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  27956. }
  27957. };
  27958. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  27959. "Host: localhost\r\n"
  27960. "\r\n";
  27961. std::string resp1;
  27962. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  27963. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  27964. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  27965. "Host: localhost\r\n"
  27966. "Connection: close\r\n"
  27967. "\r\n";
  27968. std::string resp2;
  27969. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  27970. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  27971. EXPECT_EQ(2, delete_count.load());
  27972. }
  27973. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  27974. Server svr;
  27975. svr.Post("/ingest", [&](const Request &, Response &res,
  27976. const ContentReader &content_reader) {
  27977. auto consumed = content_reader([](const char *, size_t) { return false; });
  27978. EXPECT_FALSE(consumed);
  27979. res.status = StatusCode::Conflict_409;
  27980. res.set_header("Connection", "close");
  27981. });
  27982. auto port = svr.bind_to_any_port(HOST);
  27983. thread t = thread([&] { svr.listen_after_bind(); });
  27984. auto se = detail::scope_exit([&] {
  27985. svr.stop();
  27986. t.join();
  27987. });
  27988. svr.wait_until_ready();
  27989. auto error = Error::Success;
  27990. auto sock = detail::create_client_socket(
  27991. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27992. /*connection_timeout_sec=*/2, 0,
  27993. /*read_timeout_sec=*/1, 0,
  27994. /*write_timeout_sec=*/2, 0, std::string(), error);
  27995. ASSERT_NE(INVALID_SOCKET, sock);
  27996. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27997. std::string request = "POST /ingest HTTP/1.1\r\n"
  27998. "Host: localhost\r\n"
  27999. "Transfer-Encoding: chunked\r\n"
  28000. "\r\n"
  28001. "4\r\n"
  28002. "data\r\n";
  28003. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  28004. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  28005. std::string response;
  28006. ssize_t received = 0;
  28007. do {
  28008. char buf[4096];
  28009. received = recv(sock, buf, sizeof(buf), 0);
  28010. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  28011. } while (received > 0);
  28012. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  28013. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  28014. EXPECT_EQ(0, received);
  28015. }
  28016. namespace no_proxy_test {
  28017. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  28018. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  28019. // calling listen().
  28020. class ScopedServer {
  28021. public:
  28022. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  28023. ~ScopedServer() {
  28024. svr_.stop();
  28025. if (th_.joinable()) { th_.join(); }
  28026. }
  28027. Server &svr() { return svr_; }
  28028. int port() const { return port_; }
  28029. void listen() {
  28030. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28031. svr_.wait_until_ready();
  28032. }
  28033. private:
  28034. Server svr_;
  28035. std::thread th_;
  28036. int port_ = 0;
  28037. };
  28038. class ProxyAndTargetServers {
  28039. public:
  28040. ProxyAndTargetServers() {
  28041. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  28042. proxy_hits_++;
  28043. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  28044. res.set_content("via-proxy", "text/plain");
  28045. });
  28046. target_.Get(".*", [this](const Request &req, Response &res) {
  28047. target_hits_++;
  28048. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  28049. res.set_content("direct", "text/plain");
  28050. });
  28051. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  28052. target_port_ = target_.bind_to_any_port("127.0.0.1");
  28053. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  28054. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  28055. proxy_mock_.wait_until_ready();
  28056. target_.wait_until_ready();
  28057. }
  28058. ~ProxyAndTargetServers() {
  28059. proxy_mock_.stop();
  28060. target_.stop();
  28061. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  28062. if (target_thread_.joinable()) { target_thread_.join(); }
  28063. }
  28064. Server &proxy_mock() { return proxy_mock_; }
  28065. Server &target() { return target_; }
  28066. int proxy_port() const { return proxy_port_; }
  28067. int target_port() const { return target_port_; }
  28068. int proxy_hits() const { return proxy_hits_.load(); }
  28069. int target_hits() const { return target_hits_.load(); }
  28070. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  28071. void reset_counters() {
  28072. proxy_hits_ = 0;
  28073. target_hits_ = 0;
  28074. last_had_proxy_authz_ = false;
  28075. }
  28076. private:
  28077. Server proxy_mock_;
  28078. Server target_;
  28079. std::thread proxy_thread_;
  28080. std::thread target_thread_;
  28081. int proxy_port_ = 0;
  28082. int target_port_ = 0;
  28083. std::atomic<int> proxy_hits_{0};
  28084. std::atomic<int> target_hits_{0};
  28085. std::atomic<bool> last_had_proxy_authz_{false};
  28086. };
  28087. inline std::unique_ptr<Client> make_client(const std::string &host,
  28088. ProxyAndTargetServers &s) {
  28089. auto cli = detail::make_unique<Client>(host, s.target_port());
  28090. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  28091. cli->set_proxy("127.0.0.1", s.proxy_port());
  28092. return cli;
  28093. }
  28094. } // namespace no_proxy_test
  28095. using no_proxy_test::make_client;
  28096. using no_proxy_test::ProxyAndTargetServers;
  28097. // A stream request carries the credentials a buffered request does
  28098. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  28099. no_proxy_test::ScopedServer origin;
  28100. origin.svr().Get("/x", [](const Request &req, Response &res) {
  28101. res.set_content(req.get_header_value("Authorization"), "text/plain");
  28102. });
  28103. origin.listen();
  28104. Client cli("127.0.0.1", origin.port());
  28105. cli.set_basic_auth("user", "pass");
  28106. auto handle = cli.open_stream("GET", "/x");
  28107. ASSERT_TRUE(handle.is_valid());
  28108. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  28109. Client bearer("127.0.0.1", origin.port());
  28110. bearer.set_bearer_token_auth("tok");
  28111. auto handle2 = bearer.open_stream("GET", "/x");
  28112. ASSERT_TRUE(handle2.is_valid());
  28113. EXPECT_EQ("Bearer tok", read_all(handle2));
  28114. }
  28115. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  28116. // takes its own credentials, as for a buffered request
  28117. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  28118. std::string target, authz, proxy_authz;
  28119. no_proxy_test::ScopedServer proxy;
  28120. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  28121. target = req.target;
  28122. authz = req.get_header_value("Authorization");
  28123. proxy_authz = req.get_header_value("Proxy-Authorization");
  28124. res.set_content("ok", "text/plain");
  28125. });
  28126. proxy.listen();
  28127. Client cli("origin.example", 8080);
  28128. cli.set_proxy("127.0.0.1", proxy.port());
  28129. cli.set_proxy_basic_auth("puser", "ppass");
  28130. cli.set_basic_auth("user", "pass");
  28131. auto handle = cli.open_stream("GET", "/x");
  28132. ASSERT_TRUE(handle.is_valid());
  28133. EXPECT_EQ("ok", read_all(handle));
  28134. EXPECT_EQ("http://origin.example:8080/x", target);
  28135. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  28136. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  28137. }
  28138. // In absolute-form the path follows the authority, so a path that does not
  28139. // begin with '/' would make the proxy connect to another host
  28140. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  28141. std::vector<std::string> targets;
  28142. no_proxy_test::ScopedServer proxy;
  28143. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  28144. targets.push_back(req.target);
  28145. res.set_content("ok", "text/plain");
  28146. });
  28147. proxy.listen();
  28148. Client cli("origin.example", 8080);
  28149. cli.set_proxy("127.0.0.1", proxy.port());
  28150. cli.set_basic_auth("user", "pass");
  28151. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  28152. auto res = cli.Get(path);
  28153. EXPECT_FALSE(res) << path;
  28154. auto handle = cli.open_stream("GET", path);
  28155. EXPECT_FALSE(handle.is_valid()) << path;
  28156. }
  28157. EXPECT_TRUE(targets.empty());
  28158. auto res = cli.Get("/x");
  28159. ASSERT_TRUE(res);
  28160. ASSERT_EQ(1u, targets.size());
  28161. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  28162. }
  28163. TEST(NoProxyTest, ExactHostnameBypasses) {
  28164. ProxyAndTargetServers s;
  28165. auto cli = make_client("example.com", s);
  28166. cli->set_no_proxy({"example.com"});
  28167. auto res = cli->Get("/");
  28168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28169. EXPECT_EQ(0, s.proxy_hits());
  28170. EXPECT_EQ(1, s.target_hits());
  28171. }
  28172. TEST(NoProxyTest, SubdomainBypasses) {
  28173. ProxyAndTargetServers s;
  28174. auto cli = make_client("foo.example.com", s);
  28175. cli->set_no_proxy({"example.com"});
  28176. auto res = cli->Get("/");
  28177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28178. EXPECT_EQ(0, s.proxy_hits());
  28179. EXPECT_EQ(1, s.target_hits());
  28180. }
  28181. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  28182. // Regression guard: "evilexample.com" must not be considered a subdomain
  28183. // of "example.com". Without the dot-boundary rule, a naive endsWith
  28184. // check would let traffic bypass the proxy and leak credentials direct
  28185. // to the attacker host.
  28186. ProxyAndTargetServers s;
  28187. auto cli = make_client("evilexample.com", s);
  28188. cli->set_no_proxy({"example.com"});
  28189. auto res = cli->Get("/");
  28190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28191. EXPECT_GE(s.proxy_hits(), 1);
  28192. EXPECT_EQ(0, s.target_hits());
  28193. }
  28194. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  28195. ProxyAndTargetServers s;
  28196. auto cli = make_client("example.com.evil.com", s);
  28197. cli->set_no_proxy({"example.com"});
  28198. auto res = cli->Get("/");
  28199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28200. EXPECT_GE(s.proxy_hits(), 1);
  28201. EXPECT_EQ(0, s.target_hits());
  28202. }
  28203. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  28204. ProxyAndTargetServers s;
  28205. auto cli = make_client("example.com", s);
  28206. cli->set_no_proxy({".example.com"});
  28207. auto res = cli->Get("/");
  28208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28209. EXPECT_EQ(0, s.proxy_hits());
  28210. EXPECT_EQ(1, s.target_hits());
  28211. }
  28212. TEST(NoProxyTest, CaseInsensitiveHostname) {
  28213. ProxyAndTargetServers s;
  28214. auto cli = make_client("Example.COM", s);
  28215. cli->set_no_proxy({"EXAMPLE.com"});
  28216. auto res = cli->Get("/");
  28217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28218. EXPECT_EQ(0, s.proxy_hits());
  28219. EXPECT_EQ(1, s.target_hits());
  28220. }
  28221. TEST(NoProxyTest, TrailingDotIsNormalized) {
  28222. ProxyAndTargetServers s;
  28223. auto cli = make_client("example.com.", s);
  28224. cli->set_no_proxy({"example.com"});
  28225. auto res = cli->Get("/");
  28226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28227. EXPECT_EQ(0, s.proxy_hits());
  28228. EXPECT_EQ(1, s.target_hits());
  28229. }
  28230. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  28231. // Trailing dots must be normalized on BOTH sides — host and entry.
  28232. // An implementation that only strips the host-side trailing dot would
  28233. // fail to match host "example.com" against entry "example.com." because
  28234. // a literal substring search would compare 11 chars against 12.
  28235. ProxyAndTargetServers s;
  28236. auto cli = make_client("example.com", s);
  28237. cli->set_no_proxy({"example.com."});
  28238. auto res = cli->Get("/");
  28239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28240. EXPECT_EQ(0, s.proxy_hits());
  28241. EXPECT_EQ(1, s.target_hits());
  28242. }
  28243. TEST(NoProxyTest, WildcardBypassesEverything) {
  28244. ProxyAndTargetServers s;
  28245. auto cli = make_client("anything.invalid.test", s);
  28246. cli->set_no_proxy({"*"});
  28247. auto res = cli->Get("/");
  28248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28249. EXPECT_EQ(0, s.proxy_hits());
  28250. EXPECT_EQ(1, s.target_hits());
  28251. }
  28252. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  28253. ProxyAndTargetServers s;
  28254. Client cli("127.0.0.1", s.target_port());
  28255. cli.set_proxy("127.0.0.1", s.proxy_port());
  28256. cli.set_no_proxy({"127.0.0.1"});
  28257. auto res = cli.Get("/");
  28258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28259. EXPECT_EQ(0, s.proxy_hits());
  28260. EXPECT_EQ(1, s.target_hits());
  28261. }
  28262. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  28263. ProxyAndTargetServers s;
  28264. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  28265. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  28266. cli.set_proxy("127.0.0.1", s.proxy_port());
  28267. cli.set_no_proxy({"::1"});
  28268. auto res = cli.Get("/");
  28269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28270. EXPECT_EQ(0, s.proxy_hits());
  28271. EXPECT_EQ(1, s.target_hits());
  28272. }
  28273. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  28274. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  28275. // must still be recognized as IPv6 for CIDR matching. Implementations
  28276. // that detect IPv6 only when the host begins with '[' would parse the
  28277. // host as a hostname and miss the match.
  28278. ProxyAndTargetServers s;
  28279. Client cli("fe80::1", s.target_port());
  28280. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  28281. cli.set_proxy("127.0.0.1", s.proxy_port());
  28282. cli.set_no_proxy({"fe80::/10"});
  28283. auto res = cli.Get("/");
  28284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28285. EXPECT_EQ(0, s.proxy_hits());
  28286. EXPECT_EQ(1, s.target_hits());
  28287. }
  28288. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  28289. ProxyAndTargetServers s;
  28290. Client cli("::1", s.target_port());
  28291. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  28292. cli.set_proxy("127.0.0.1", s.proxy_port());
  28293. cli.set_no_proxy({"[::1]"});
  28294. auto res = cli.Get("/");
  28295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28296. EXPECT_EQ(0, s.proxy_hits());
  28297. EXPECT_EQ(1, s.target_hits());
  28298. }
  28299. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  28300. ProxyAndTargetServers s;
  28301. Client cli("fe80::1", s.target_port());
  28302. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  28303. cli.set_proxy("127.0.0.1", s.proxy_port());
  28304. cli.set_no_proxy({"[fe80::]/10"});
  28305. auto res = cli.Get("/");
  28306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28307. EXPECT_EQ(0, s.proxy_hits());
  28308. EXPECT_EQ(1, s.target_hits());
  28309. }
  28310. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  28311. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  28312. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  28313. // tricks via address-family conversion.
  28314. ProxyAndTargetServers s;
  28315. Client cli("::ffff:127.0.0.1", s.target_port());
  28316. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  28317. cli.set_proxy("127.0.0.1", s.proxy_port());
  28318. cli.set_no_proxy({"127.0.0.1"});
  28319. auto res = cli.Get("/");
  28320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28321. EXPECT_GE(s.proxy_hits(), 1);
  28322. EXPECT_EQ(0, s.target_hits());
  28323. }
  28324. TEST(NoProxyTest, IPv4CidrMatch) {
  28325. ProxyAndTargetServers s;
  28326. Client cli("127.0.0.1", s.target_port());
  28327. cli.set_proxy("127.0.0.1", s.proxy_port());
  28328. cli.set_no_proxy({"127.0.0.0/8"});
  28329. auto res = cli.Get("/");
  28330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28331. EXPECT_EQ(0, s.proxy_hits());
  28332. EXPECT_EQ(1, s.target_hits());
  28333. }
  28334. TEST(NoProxyTest, IPv4CidrNonMatch) {
  28335. ProxyAndTargetServers s;
  28336. Client cli("127.0.0.1", s.target_port());
  28337. cli.set_proxy("127.0.0.1", s.proxy_port());
  28338. cli.set_no_proxy({"10.0.0.0/8"});
  28339. auto res = cli.Get("/");
  28340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28341. EXPECT_GE(s.proxy_hits(), 1);
  28342. EXPECT_EQ(0, s.target_hits());
  28343. }
  28344. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  28345. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  28346. // IPv4 target matches.
  28347. ProxyAndTargetServers s;
  28348. Client cli("127.0.0.1", s.target_port());
  28349. cli.set_proxy("127.0.0.1", s.proxy_port());
  28350. cli.set_no_proxy({"0.0.0.0/0"});
  28351. auto res = cli.Get("/");
  28352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28353. EXPECT_EQ(0, s.proxy_hits());
  28354. EXPECT_EQ(1, s.target_hits());
  28355. }
  28356. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  28357. ProxyAndTargetServers s;
  28358. Client cli("127.0.0.1", s.target_port());
  28359. cli.set_proxy("127.0.0.1", s.proxy_port());
  28360. cli.set_no_proxy({"127.0.0.1"});
  28361. auto res = cli.Get("/");
  28362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28363. EXPECT_EQ(0, s.proxy_hits());
  28364. EXPECT_EQ(1, s.target_hits());
  28365. }
  28366. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  28367. ProxyAndTargetServers s;
  28368. Client cli("127.0.0.1", s.target_port());
  28369. cli.set_proxy("127.0.0.1", s.proxy_port());
  28370. cli.set_no_proxy({"127.0.0.0/33"});
  28371. auto res = cli.Get("/");
  28372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28373. EXPECT_GE(s.proxy_hits(), 1);
  28374. EXPECT_EQ(0, s.target_hits());
  28375. }
  28376. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  28377. // Empty prefix after the slash must be rejected, not silently treated as /32.
  28378. ProxyAndTargetServers s;
  28379. Client cli("127.0.0.1", s.target_port());
  28380. cli.set_proxy("127.0.0.1", s.proxy_port());
  28381. cli.set_no_proxy({"127.0.0.1/"});
  28382. auto res = cli.Get("/");
  28383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28384. EXPECT_GE(s.proxy_hits(), 1);
  28385. EXPECT_EQ(0, s.target_hits());
  28386. }
  28387. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  28388. ProxyAndTargetServers s;
  28389. auto cli = make_client("internal.corp", s);
  28390. cli->set_proxy_basic_auth("u", "p");
  28391. cli->set_no_proxy({"internal.corp"});
  28392. auto res = cli->Get("/");
  28393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28394. EXPECT_EQ(1, s.target_hits());
  28395. EXPECT_EQ(0, s.proxy_hits());
  28396. EXPECT_FALSE(s.last_had_proxy_authz())
  28397. << "Proxy-Authorization must not be sent direct to the target";
  28398. }
  28399. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  28400. ProxyAndTargetServers s;
  28401. auto cli = make_client("public.example", s);
  28402. cli->set_proxy_basic_auth("u", "p");
  28403. cli->set_no_proxy({"internal.corp"}); // does not match
  28404. auto res = cli->Get("/");
  28405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28406. EXPECT_GE(s.proxy_hits(), 1);
  28407. EXPECT_TRUE(s.last_had_proxy_authz());
  28408. }
  28409. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  28410. std::atomic<int> hits{0};
  28411. std::atomic<int> hits_with_authz{0};
  28412. no_proxy_test::ScopedServer proxy_mock;
  28413. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28414. hits++;
  28415. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  28416. if (req.target.find("/redir") != std::string::npos) {
  28417. res.set_redirect("http://other.example/landed");
  28418. } else {
  28419. res.set_content("via-proxy", "text/plain");
  28420. }
  28421. });
  28422. proxy_mock.listen();
  28423. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  28424. hits = 0;
  28425. hits_with_authz = 0;
  28426. Client cli("public.example", 80);
  28427. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28428. cli.set_proxy_basic_auth(c.first, c.second);
  28429. cli.set_follow_location(true);
  28430. // The redirect to another host goes through the proxy as well
  28431. auto res = cli.Get("/redir");
  28432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28433. EXPECT_EQ(2, hits.load());
  28434. EXPECT_EQ(2, hits_with_authz.load());
  28435. }
  28436. }
  28437. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  28438. ProxyAndTargetServers s;
  28439. auto cli = make_client("anything.test", s);
  28440. auto res = cli->Get("/");
  28441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28442. EXPECT_GE(s.proxy_hits(), 1);
  28443. EXPECT_EQ(0, s.target_hits());
  28444. }
  28445. TEST(NoProxyTest, PortSpecificEntryRejected) {
  28446. ProxyAndTargetServers s;
  28447. auto cli = make_client("example.com", s);
  28448. cli->set_no_proxy({"example.com:8080"});
  28449. auto res = cli->Get("/");
  28450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28451. EXPECT_GE(s.proxy_hits(), 1);
  28452. EXPECT_EQ(0, s.target_hits());
  28453. }
  28454. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  28455. ProxyAndTargetServers s;
  28456. auto cli = make_client("anything.test", s);
  28457. cli->set_no_proxy({"", " ", "\t"});
  28458. auto res = cli->Get("/");
  28459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28460. EXPECT_GE(s.proxy_hits(), 1);
  28461. EXPECT_EQ(0, s.target_hits());
  28462. }
  28463. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  28464. // An entry with leading/trailing whitespace must still match — env-style
  28465. // values are commonly pasted with stray spaces and an implementation
  28466. // that feeds the raw token directly to inet_pton would fail to match
  28467. // valid CIDRs because of the spaces.
  28468. ProxyAndTargetServers s;
  28469. Client cli("127.0.0.1", s.target_port());
  28470. cli.set_proxy("127.0.0.1", s.proxy_port());
  28471. cli.set_no_proxy({" 127.0.0.0/8 "});
  28472. auto res = cli.Get("/");
  28473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28474. EXPECT_EQ(0, s.proxy_hits());
  28475. EXPECT_EQ(1, s.target_hits());
  28476. }
  28477. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  28478. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  28479. // go direct and must NOT carry Proxy-Authorization.
  28480. std::atomic<int> proxy_hits{0};
  28481. std::atomic<int> target_hits{0};
  28482. std::atomic<bool> target_saw_authz{false};
  28483. no_proxy_test::ScopedServer proxy_mock, target;
  28484. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28485. proxy_hits++;
  28486. res.status = 302;
  28487. res.set_header("Location", "http://127.0.0.1:" +
  28488. std::to_string(target.port()) + "/landed");
  28489. });
  28490. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28491. target_hits++;
  28492. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  28493. res.set_content("direct", "text/plain");
  28494. });
  28495. proxy_mock.listen();
  28496. target.listen();
  28497. Client cli("public.example", target.port());
  28498. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28499. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28500. cli.set_proxy_basic_auth("u", "p");
  28501. cli.set_no_proxy({"127.0.0.1"});
  28502. cli.set_follow_location(true);
  28503. auto res = cli.Get("/redir");
  28504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28505. EXPECT_GE(proxy_hits.load(), 1);
  28506. EXPECT_GE(target_hits.load(), 1);
  28507. EXPECT_FALSE(target_saw_authz.load());
  28508. }
  28509. #ifdef CPPHTTPLIB_SSL_ENABLED
  28510. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  28511. // Direct origin replying 407 must not trigger the digest retry; otherwise
  28512. // proxy creds would be sent to the (possibly hostile) origin.
  28513. std::atomic<int> target_hits{0};
  28514. std::atomic<bool> target_saw_proxy_authz{false};
  28515. no_proxy_test::ScopedServer target;
  28516. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28517. target_hits++;
  28518. if (req.has_header("Proxy-Authorization")) {
  28519. target_saw_proxy_authz = true;
  28520. }
  28521. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28522. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  28523. "nonce=\"abc\", algorithm=MD5");
  28524. });
  28525. target.listen();
  28526. // The proxy address is set to the target's port: the bypass MUST kick in;
  28527. // if it doesn't, the test still routes "via proxy" to the same server and
  28528. // the Proxy-Authorization assertion below catches the leak.
  28529. Client cli("evil.example", target.port());
  28530. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  28531. cli.set_proxy("127.0.0.1", target.port());
  28532. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28533. cli.set_no_proxy({"evil.example"});
  28534. auto res = cli.Get("/x");
  28535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28536. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28537. EXPECT_EQ(1, target_hits.load());
  28538. EXPECT_FALSE(target_saw_proxy_authz.load());
  28539. }
  28540. #endif
  28541. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  28542. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  28543. std::atomic<int> proxy_hits{0};
  28544. std::atomic<int> bypass_hits{0};
  28545. std::atomic<bool> proxy_saw_c_url{false};
  28546. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  28547. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28548. proxy_hits++;
  28549. if (req.path.find("/start") != std::string::npos) {
  28550. res.status = 302;
  28551. res.set_header("Location", "http://127.0.0.1:" +
  28552. std::to_string(bypass_server.port()) +
  28553. "/middle");
  28554. return;
  28555. }
  28556. if (req.path.find("/end") != std::string::npos) {
  28557. proxy_saw_c_url = true;
  28558. res.set_content("c-via-proxy", "text/plain");
  28559. return;
  28560. }
  28561. res.set_content("unexpected", "text/plain");
  28562. });
  28563. // public.example's "advertised" port is arbitrary (the request never lands
  28564. // there — it goes through the proxy), but use a dynamic value to stay
  28565. // friendly with sharded parallel runs.
  28566. int public_port = bypass_server.port();
  28567. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  28568. bypass_hits++;
  28569. res.status = 302;
  28570. res.set_header("Location", "http://public.example:" +
  28571. std::to_string(public_port) + "/end");
  28572. });
  28573. proxy_mock.listen();
  28574. bypass_server.listen();
  28575. Client cli("public.example", public_port);
  28576. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28577. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28578. cli.set_no_proxy({"127.0.0.1"});
  28579. cli.set_follow_location(true);
  28580. auto res = cli.Get("/start");
  28581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28582. EXPECT_EQ(StatusCode::OK_200, res->status);
  28583. EXPECT_EQ("c-via-proxy", res->body);
  28584. EXPECT_GE(proxy_hits.load(), 2);
  28585. EXPECT_GE(bypass_hits.load(), 1);
  28586. EXPECT_TRUE(proxy_saw_c_url.load());
  28587. }
  28588. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  28589. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  28590. // request reconnects to the correct endpoint.
  28591. std::atomic<int> proxy_hits{0};
  28592. std::atomic<int> target_hits{0};
  28593. no_proxy_test::ScopedServer proxy_mock, target;
  28594. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28595. proxy_hits++;
  28596. res.set_content("via-proxy", "text/plain");
  28597. });
  28598. target.svr().Get(".*", [&](const Request &, Response &res) {
  28599. target_hits++;
  28600. res.set_content("direct", "text/plain");
  28601. });
  28602. proxy_mock.listen();
  28603. target.listen();
  28604. Client cli("public.example", target.port());
  28605. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28606. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28607. cli.set_keep_alive(true);
  28608. auto res1 = cli.Get("/a");
  28609. ASSERT_TRUE(res1);
  28610. EXPECT_EQ("via-proxy", res1->body);
  28611. EXPECT_EQ(1, proxy_hits.load());
  28612. EXPECT_EQ(0, target_hits.load());
  28613. cli.set_no_proxy({"public.example"});
  28614. auto res2 = cli.Get("/b");
  28615. ASSERT_TRUE(res2);
  28616. EXPECT_EQ("direct", res2->body);
  28617. EXPECT_EQ(1, proxy_hits.load());
  28618. EXPECT_EQ(1, target_hits.load());
  28619. }
  28620. // Forward declarations (see the base64_encode note).
  28621. namespace httplib {
  28622. namespace detail {
  28623. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  28624. int shutdown_socket(socket_t sock) noexcept;
  28625. } // namespace detail
  28626. } // namespace httplib
  28627. namespace proxy_tunnel_test {
  28628. const char *const kTunnelEstablished =
  28629. "HTTP/1.1 200 Connection established\r\n\r\n";
  28630. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  28631. using ConnectReply = std::function<std::string(const std::string &head)>;
  28632. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  28633. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  28634. class ScopedConnectProxy {
  28635. public:
  28636. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  28637. : forward_port_(forward_port), reply_(std::move(reply)) {
  28638. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  28639. if (listen_sock_ == INVALID_SOCKET) { return; }
  28640. auto a = loopback(0);
  28641. auto addr = reinterpret_cast<sockaddr *>(&a);
  28642. socklen_t alen = sizeof(a);
  28643. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  28644. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  28645. ::listen(listen_sock_, 4) != 0) {
  28646. return;
  28647. }
  28648. port_ = ntohs(a.sin_port);
  28649. th_ = std::thread([this] { run(); });
  28650. }
  28651. ~ScopedConnectProxy() {
  28652. if (th_.joinable()) {
  28653. stop_ = true;
  28654. auto wake = connect_to(port_);
  28655. th_.join();
  28656. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  28657. }
  28658. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  28659. }
  28660. int port() const { return port_; }
  28661. int connect_hits() const { return connect_hits_.load(); }
  28662. // Head of the last CONNECT request, as the proxy saw it on the wire.
  28663. std::string connect_request() const {
  28664. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28665. return connect_request_;
  28666. }
  28667. private:
  28668. static sockaddr_in loopback(int port) {
  28669. sockaddr_in a{};
  28670. a.sin_family = AF_INET;
  28671. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  28672. a.sin_port = htons(static_cast<unsigned short>(port));
  28673. return a;
  28674. }
  28675. static socket_t connect_to(int port) {
  28676. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  28677. if (sock == INVALID_SOCKET) { return sock; }
  28678. auto a = loopback(port);
  28679. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  28680. detail::close_socket(sock);
  28681. return INVALID_SOCKET;
  28682. }
  28683. return sock;
  28684. }
  28685. static bool send_all(socket_t sock, const char *data, size_t size) {
  28686. while (size > 0) {
  28687. auto n = detail::send_socket(sock, data, size, 0);
  28688. if (n <= 0) { return false; }
  28689. data += n;
  28690. size -= static_cast<size_t>(n);
  28691. }
  28692. return true;
  28693. }
  28694. void run() {
  28695. for (;;) {
  28696. auto client = ::accept(listen_sock_, nullptr, nullptr);
  28697. if (stop_) {
  28698. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  28699. return;
  28700. }
  28701. if (client == INVALID_SOCKET) { continue; }
  28702. serve(client);
  28703. detail::close_socket(client);
  28704. }
  28705. }
  28706. void serve(socket_t client) {
  28707. std::string head;
  28708. char buf[2048];
  28709. while (head.find("\r\n\r\n") == std::string::npos) {
  28710. if (detail::select_read(client, 5, 0) <= 0) { return; }
  28711. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  28712. if (n <= 0) { return; }
  28713. head.append(buf, static_cast<size_t>(n));
  28714. }
  28715. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  28716. connect_hits_++;
  28717. {
  28718. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28719. connect_request_ = head;
  28720. }
  28721. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  28722. if (!send_all(client, res.data(), res.size()) ||
  28723. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  28724. return;
  28725. }
  28726. auto origin = connect_to(forward_port_);
  28727. if (origin == INVALID_SOCKET) { return; }
  28728. // When either side stops, shut both down so the other pump returns too.
  28729. auto pump = [&](socket_t from, socket_t to) {
  28730. char b[8192];
  28731. for (;;) {
  28732. auto n = detail::read_socket(from, b, sizeof(b), 0);
  28733. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  28734. }
  28735. detail::shutdown_socket(client);
  28736. detail::shutdown_socket(origin);
  28737. };
  28738. std::thread up([&] { pump(client, origin); });
  28739. pump(origin, client);
  28740. up.join();
  28741. detail::close_socket(origin);
  28742. }
  28743. int forward_port_;
  28744. ConnectReply reply_;
  28745. socket_t listen_sock_ = INVALID_SOCKET;
  28746. int port_ = 0;
  28747. std::thread th_;
  28748. std::atomic<bool> stop_{false};
  28749. std::atomic<int> connect_hits_{0};
  28750. mutable std::mutex connect_request_mutex_;
  28751. std::string connect_request_;
  28752. };
  28753. } // namespace proxy_tunnel_test
  28754. #ifdef CPPHTTPLIB_SSL_ENABLED
  28755. namespace proxy_tunnel_test {
  28756. // SSLServer counterpart to no_proxy_test::ScopedServer.
  28757. class ScopedSSLServer {
  28758. public:
  28759. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  28760. port_ = svr_.bind_to_any_port("127.0.0.1");
  28761. }
  28762. ~ScopedSSLServer() {
  28763. svr_.stop();
  28764. if (th_.joinable()) { th_.join(); }
  28765. }
  28766. SSLServer &svr() { return svr_; }
  28767. int port() const { return port_; }
  28768. void listen() {
  28769. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28770. svr_.wait_until_ready();
  28771. }
  28772. private:
  28773. SSLServer svr_;
  28774. std::thread th_;
  28775. int port_ = 0;
  28776. };
  28777. // Sends one request through the CONNECT proxy to the TLS origin with a
  28778. // credential configured for each hop, and checks that each credential reaches
  28779. // only the hop it was configured for: the proxy's on the CONNECT request, the
  28780. // origin's (every header in origin_headers) on the tunnelled request.
  28781. void CredentialsStayWithTheirHop(
  28782. const std::function<void(SSLClient &)> &set_credentials,
  28783. const std::string &scheme,
  28784. const std::vector<std::string> &origin_headers = {"Authorization"},
  28785. bool stream = false) {
  28786. std::atomic<int> origin_hits{0};
  28787. std::atomic<bool> origin_saw_proxy_authz{false};
  28788. std::atomic<bool> origin_saw_headers{false};
  28789. ScopedSSLServer origin;
  28790. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28791. origin_hits++;
  28792. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  28793. origin_saw_headers =
  28794. std::all_of(origin_headers.begin(), origin_headers.end(),
  28795. [&](const std::string &h) { return req.has_header(h); });
  28796. res.set_content("ok", "text/plain");
  28797. });
  28798. origin.listen();
  28799. ScopedConnectProxy proxy(origin.port());
  28800. ASSERT_NE(0, proxy.port());
  28801. // Pinned to 127.0.0.1 for the same reason as the test below.
  28802. SSLClient cli("127.0.0.1", origin.port());
  28803. cli.enable_server_certificate_verification(false);
  28804. cli.set_proxy("127.0.0.1", proxy.port());
  28805. set_credentials(cli);
  28806. if (stream) {
  28807. auto handle = cli.open_stream("GET", "/x");
  28808. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  28809. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  28810. } else {
  28811. auto res = cli.Get("/x");
  28812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28813. EXPECT_EQ(StatusCode::OK_200, res->status);
  28814. }
  28815. EXPECT_EQ(1, origin_hits.load());
  28816. EXPECT_EQ(1, proxy.connect_hits());
  28817. EXPECT_TRUE(origin_saw_headers.load());
  28818. EXPECT_FALSE(origin_saw_proxy_authz.load())
  28819. << "Proxy-Authorization must not be sent inside the tunnel";
  28820. auto connect_req = proxy.connect_request();
  28821. EXPECT_NE(std::string::npos,
  28822. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  28823. for (const auto &h : origin_headers) {
  28824. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  28825. << h << " must not be sent to the proxy on CONNECT";
  28826. }
  28827. }
  28828. } // namespace proxy_tunnel_test
  28829. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  28830. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28831. [](SSLClient &cli) {
  28832. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28833. cli.set_basic_auth("origin-user", "origin-pass");
  28834. },
  28835. "Basic");
  28836. }
  28837. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  28838. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28839. [](SSLClient &cli) {
  28840. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28841. cli.set_basic_auth("origin-user", "origin-pass");
  28842. },
  28843. "Basic", {"Authorization"}, true);
  28844. }
  28845. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  28846. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28847. [](SSLClient &cli) {
  28848. cli.set_proxy_bearer_token_auth("proxy-token");
  28849. cli.set_bearer_token_auth("origin-token");
  28850. },
  28851. "Bearer");
  28852. }
  28853. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  28854. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28855. [](SSLClient &cli) {
  28856. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28857. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  28858. {"Cookie", "sid=origin-session"},
  28859. {"X-Api-Key", "origin-key"}});
  28860. },
  28861. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  28862. }
  28863. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  28864. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  28865. // retry; otherwise proxy creds would be sent to the origin.
  28866. std::atomic<int> origin_hits{0};
  28867. std::atomic<bool> origin_saw_proxy_authz{false};
  28868. proxy_tunnel_test::ScopedSSLServer origin;
  28869. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28870. origin_hits++;
  28871. if (req.has_header("Proxy-Authorization")) {
  28872. origin_saw_proxy_authz = true;
  28873. }
  28874. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28875. res.set_header("Proxy-Authenticate",
  28876. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  28877. "algorithm=MD5");
  28878. });
  28879. origin.listen();
  28880. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28881. ASSERT_NE(0, proxy.port());
  28882. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  28883. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  28884. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  28885. // and answer with its own status, making this test flaky.
  28886. SSLClient cli("127.0.0.1", origin.port());
  28887. cli.enable_server_certificate_verification(false);
  28888. cli.set_proxy("127.0.0.1", proxy.port());
  28889. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28890. auto res = cli.Get("/x");
  28891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28892. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28893. EXPECT_EQ(1, origin_hits.load());
  28894. EXPECT_FALSE(origin_saw_proxy_authz.load());
  28895. EXPECT_EQ(1, proxy.connect_hits());
  28896. }
  28897. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28898. std::string origin_sni;
  28899. std::string origin_host;
  28900. proxy_tunnel_test::ScopedSSLServer origin;
  28901. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28902. origin_sni = req.sni();
  28903. origin_host = req.get_header_value("Host");
  28904. res.set_content("ok", "text/plain");
  28905. });
  28906. origin.listen();
  28907. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28908. ASSERT_NE(0, proxy.port());
  28909. SSLClient cli("origin.example", origin.port());
  28910. cli.enable_server_certificate_verification(false);
  28911. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28912. cli.set_proxy("127.0.0.1", proxy.port());
  28913. auto res = cli.Get("/x");
  28914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28915. EXPECT_EQ(StatusCode::OK_200, res->status);
  28916. auto port = std::to_string(origin.port());
  28917. auto target = "127.0.0.1:" + port;
  28918. auto connect_req = proxy.connect_request();
  28919. EXPECT_EQ(1, proxy.connect_hits());
  28920. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28921. EXPECT_NE(std::string::npos,
  28922. connect_req.find("\r\nHost: " + target + "\r\n"));
  28923. EXPECT_EQ("origin.example", origin_sni);
  28924. EXPECT_EQ("origin.example:" + port, origin_host);
  28925. }
  28926. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  28927. proxy_tunnel_test::ScopedSSLServer origin;
  28928. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28929. res.set_content("ok", "text/plain");
  28930. });
  28931. origin.listen();
  28932. proxy_tunnel_test::ScopedConnectProxy proxy(
  28933. origin.port(), [](const std::string &head) -> std::string {
  28934. if (head.find(
  28935. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28936. std::string::npos) {
  28937. return proxy_tunnel_test::kTunnelEstablished;
  28938. }
  28939. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28940. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28941. "nonce=\"abc\", algorithm=MD5\r\n"
  28942. "Content-Length: 0\r\n\r\n";
  28943. });
  28944. ASSERT_NE(0, proxy.port());
  28945. SSLClient cli("origin.example", origin.port());
  28946. cli.enable_server_certificate_verification(false);
  28947. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28948. cli.set_proxy("127.0.0.1", proxy.port());
  28949. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28950. auto res = cli.Get("/x");
  28951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28952. EXPECT_EQ(StatusCode::OK_200, res->status);
  28953. // The retried CONNECT is the one the proxy saw last.
  28954. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28955. auto connect_req = proxy.connect_request();
  28956. EXPECT_EQ(2, proxy.connect_hits());
  28957. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28958. EXPECT_NE(std::string::npos,
  28959. connect_req.find("\r\nHost: " + target + "\r\n"));
  28960. }
  28961. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28962. proxy_tunnel_test::ScopedSSLServer origin;
  28963. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28964. res.set_content("ok", "text/plain");
  28965. });
  28966. origin.listen();
  28967. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28968. ASSERT_NE(0, proxy.port());
  28969. SSLClient cli("origin.example", origin.port());
  28970. cli.enable_server_certificate_verification(false);
  28971. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28972. cli.set_proxy("127.0.0.1", proxy.port());
  28973. auto res = cli.Get("/x");
  28974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28975. EXPECT_EQ(StatusCode::OK_200, res->status);
  28976. auto target = "origin.example:" + std::to_string(origin.port());
  28977. auto connect_req = proxy.connect_request();
  28978. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28979. EXPECT_NE(std::string::npos,
  28980. connect_req.find("\r\nHost: " + target + "\r\n"));
  28981. }
  28982. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  28983. proxy_tunnel_test::ScopedSSLServer origin;
  28984. auto port = std::to_string(origin.port());
  28985. origin.svr().Get("/x", [&](const Request &, Response &res) {
  28986. res.set_redirect("https://next.example:" + port + "/y");
  28987. });
  28988. origin.svr().Get("/y", [](const Request &, Response &res) {
  28989. res.set_content("ok", "text/plain");
  28990. });
  28991. origin.listen();
  28992. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28993. ASSERT_NE(0, proxy.port());
  28994. SSLClient cli("origin.example", origin.port());
  28995. cli.enable_server_certificate_verification(false);
  28996. cli.set_tunnel_hostname_addr_map(
  28997. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  28998. cli.set_proxy("127.0.0.1", proxy.port());
  28999. cli.set_follow_location(true);
  29000. auto res = cli.Get("/x");
  29001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29002. EXPECT_EQ("ok", res->body);
  29003. // The last CONNECT is the redirect client's.
  29004. ASSERT_EQ(2, proxy.connect_hits());
  29005. auto target = "127.0.0.1:" + port;
  29006. auto connect_req = proxy.connect_request();
  29007. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29008. EXPECT_NE(std::string::npos,
  29009. connect_req.find("\r\nHost: " + target + "\r\n"));
  29010. }
  29011. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  29012. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  29013. std::atomic<int> origin_hits{0};
  29014. proxy_tunnel_test::ScopedSSLServer origin;
  29015. origin.svr().Get(".*", [&](const Request &, Response &res) {
  29016. origin_hits++;
  29017. res.set_content("ok", "text/plain");
  29018. });
  29019. origin.listen();
  29020. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29021. ASSERT_NE(0, proxy.port());
  29022. SSLClient cli("127.0.0.1", origin.port());
  29023. cli.enable_server_certificate_verification(false);
  29024. cli.set_proxy("127.0.0.1", proxy.port());
  29025. cli.set_keep_alive(true);
  29026. cli.set_session_verifier(
  29027. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  29028. auto res = cli.Get("/x");
  29029. EXPECT_FALSE(res);
  29030. ASSERT_FALSE(cli.is_socket_open());
  29031. res = cli.Get("/x");
  29032. EXPECT_FALSE(res);
  29033. EXPECT_EQ(2, proxy.connect_hits());
  29034. auto handle = cli.open_stream("GET", "/x");
  29035. EXPECT_FALSE(handle.is_valid());
  29036. EXPECT_EQ(3, proxy.connect_hits());
  29037. EXPECT_EQ(0, origin_hits.load());
  29038. }
  29039. #endif
  29040. namespace proxy_tunnel_test {
  29041. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  29042. // anything else gets a 407 with `challenge`.
  29043. ConnectReply require_proxy_auth(const std::string &expected,
  29044. const std::string &challenge) {
  29045. return [=](const std::string &head) -> std::string {
  29046. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  29047. std::string::npos) {
  29048. return kTunnelEstablished;
  29049. }
  29050. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  29051. "Proxy-Authenticate: " +
  29052. challenge + "\r\nContent-Length: 0\r\n\r\n";
  29053. };
  29054. }
  29055. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  29056. // request, then echoes.
  29057. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  29058. ws.send(
  29059. "authorization:" + req.get_header_value("Authorization") +
  29060. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  29061. std::string msg;
  29062. while (ws.read(msg)) {
  29063. ws.send(msg);
  29064. }
  29065. }
  29066. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  29067. class ScopedWebSocketOrigin {
  29068. public:
  29069. ScopedWebSocketOrigin() {
  29070. server_.svr().WebSocket("/ws", report_auth_then_echo);
  29071. server_.listen();
  29072. }
  29073. int port() const { return server_.port(); }
  29074. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  29075. std::string url() const {
  29076. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  29077. }
  29078. private:
  29079. no_proxy_test::ScopedServer server_;
  29080. };
  29081. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  29082. // passed as a constructor header, and checks that each reaches only its hop.
  29083. void WebSocketCredentialsStayWithTheirHop(
  29084. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  29085. const std::string &proxy_authz, const std::string &origin_authz) {
  29086. ScopedWebSocketOrigin origin;
  29087. ScopedConnectProxy proxy(
  29088. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  29089. ASSERT_NE(0, proxy.port());
  29090. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  29091. client.set_proxy("127.0.0.1", proxy.port());
  29092. set_proxy_credentials(client);
  29093. auto res = client.connect();
  29094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29095. std::string msg;
  29096. ASSERT_TRUE(client.read(msg));
  29097. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  29098. client.close();
  29099. EXPECT_EQ(1, proxy.connect_hits());
  29100. EXPECT_EQ(std::string::npos,
  29101. proxy.connect_request().find("\r\nAuthorization: "))
  29102. << "origin credentials must not be sent to the proxy";
  29103. }
  29104. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  29105. void WebSocketSetterCredentialsStayWithTheirHop(
  29106. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  29107. const std::string &proxy_authz, const std::string &origin_authz) {
  29108. ScopedWebSocketOrigin origin;
  29109. ScopedConnectProxy proxy(
  29110. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  29111. ASSERT_NE(0, proxy.port());
  29112. ws::WebSocketClient client(origin.url());
  29113. client.set_proxy("127.0.0.1", proxy.port());
  29114. set_credentials(client);
  29115. auto res = client.connect();
  29116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29117. std::string msg;
  29118. ASSERT_TRUE(client.read(msg));
  29119. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  29120. client.close();
  29121. EXPECT_EQ(1, proxy.connect_hits());
  29122. EXPECT_EQ(std::string::npos,
  29123. proxy.connect_request().find("\r\nAuthorization: "))
  29124. << "origin credentials must not be sent to the proxy";
  29125. }
  29126. } // namespace proxy_tunnel_test
  29127. namespace {
  29128. // Connects `client` and returns the Authorization header its upgrade
  29129. // request carried, or "<failed>" when the connection could not be opened.
  29130. std::string websocket_authorization(ws::WebSocketClient &client) {
  29131. if (!client.connect()) { return "<failed>"; }
  29132. std::string msg;
  29133. if (!client.read(msg)) { return "<failed>"; }
  29134. client.close();
  29135. auto prefix = std::string("authorization:");
  29136. auto end = msg.find("|proxy-authorization:");
  29137. return msg.substr(prefix.size(), end - prefix.size());
  29138. }
  29139. } // namespace
  29140. TEST(WebSocketClientAuthTest, BasicAuth) {
  29141. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29142. ws::WebSocketClient client(origin.url());
  29143. client.set_basic_auth("user", "pass");
  29144. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  29145. websocket_authorization(client));
  29146. }
  29147. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  29148. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29149. ws::WebSocketClient client(origin.url());
  29150. client.set_basic_auth("user", "");
  29151. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  29152. websocket_authorization(client));
  29153. }
  29154. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  29155. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29156. ws::WebSocketClient client(origin.url());
  29157. client.set_bearer_token_auth("token123");
  29158. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  29159. }
  29160. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  29161. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29162. ws::WebSocketClient client(origin.url());
  29163. client.set_bearer_token_auth("token123");
  29164. client.set_basic_auth("user", "pass");
  29165. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  29166. websocket_authorization(client));
  29167. }
  29168. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  29169. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29170. ws::WebSocketClient client(origin.url(),
  29171. {{"Authorization", "Bearer from-header"}});
  29172. client.set_bearer_token_auth("from-setter");
  29173. client.set_basic_auth("user", "pass");
  29174. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  29175. }
  29176. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  29177. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29178. ws::WebSocketClient client(origin.url());
  29179. EXPECT_EQ("", websocket_authorization(client));
  29180. client.set_bearer_token_auth("first");
  29181. EXPECT_EQ("Bearer first", websocket_authorization(client));
  29182. client.set_bearer_token_auth("second");
  29183. EXPECT_EQ("Bearer second", websocket_authorization(client));
  29184. client.set_bearer_token_auth("");
  29185. EXPECT_EQ("", websocket_authorization(client));
  29186. }
  29187. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  29188. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29189. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29190. ASSERT_NE(0, proxy.port());
  29191. ws::WebSocketClient client(origin.url());
  29192. client.set_proxy("127.0.0.1", proxy.port());
  29193. auto res = client.connect();
  29194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29195. std::string msg;
  29196. ASSERT_TRUE(client.read(msg));
  29197. ASSERT_TRUE(client.send("hello"));
  29198. ASSERT_TRUE(client.read(msg));
  29199. EXPECT_EQ("hello", msg);
  29200. client.close();
  29201. EXPECT_EQ(1, proxy.connect_hits());
  29202. auto target = "127.0.0.1:" + std::to_string(origin.port());
  29203. auto connect_req = proxy.connect_request();
  29204. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29205. EXPECT_NE(std::string::npos,
  29206. connect_req.find("\r\nHost: " + target + "\r\n"));
  29207. }
  29208. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  29209. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  29210. [](ws::WebSocketClient &cli) {
  29211. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  29212. },
  29213. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  29214. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  29215. }
  29216. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  29217. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  29218. [](ws::WebSocketClient &cli) {
  29219. cli.set_proxy_bearer_token_auth("proxy-token");
  29220. },
  29221. "Bearer proxy-token", "Bearer origin-token");
  29222. }
  29223. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  29224. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  29225. [](ws::WebSocketClient &cli) {
  29226. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  29227. cli.set_basic_auth("origin-user", "origin-pass");
  29228. },
  29229. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  29230. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  29231. }
  29232. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  29233. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  29234. [](ws::WebSocketClient &cli) {
  29235. cli.set_proxy_bearer_token_auth("proxy-token");
  29236. cli.set_bearer_token_auth("origin-token");
  29237. },
  29238. "Bearer proxy-token", "Bearer origin-token");
  29239. }
  29240. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  29241. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29242. proxy_tunnel_test::ScopedConnectProxy proxy(
  29243. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29244. "Basic " + detail::base64_encode("proxy-user:"),
  29245. "Basic realm=\"proxy\""));
  29246. ASSERT_NE(0, proxy.port());
  29247. ws::WebSocketClient client(origin.url());
  29248. client.set_proxy("127.0.0.1", proxy.port());
  29249. client.set_proxy_basic_auth("proxy-user", "");
  29250. auto res = client.connect();
  29251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29252. client.close();
  29253. EXPECT_EQ(1, proxy.connect_hits());
  29254. }
  29255. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  29256. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29257. proxy_tunnel_test::ScopedConnectProxy proxy(
  29258. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29259. "Bearer proxy-token", "Basic realm=\"proxy\""));
  29260. ASSERT_NE(0, proxy.port());
  29261. ws::WebSocketClient client(origin.url());
  29262. client.set_proxy("127.0.0.1", proxy.port());
  29263. auto res = client.connect();
  29264. EXPECT_FALSE(res);
  29265. EXPECT_EQ(Error::ProxyConnection, res.error());
  29266. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  29267. EXPECT_EQ("Basic realm=\"proxy\"",
  29268. res.get_header_value("Proxy-Authenticate"));
  29269. EXPECT_FALSE(client.is_open());
  29270. }
  29271. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  29272. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29273. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29274. ASSERT_NE(0, proxy.port());
  29275. ws::WebSocketClient client(origin.url());
  29276. client.set_proxy("127.0.0.1", proxy.port());
  29277. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  29278. client.set_no_proxy({"127.0.0.1"});
  29279. auto res = client.connect();
  29280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29281. std::string msg;
  29282. ASSERT_TRUE(client.read(msg));
  29283. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  29284. << "proxy credentials must not reach a bypassed origin";
  29285. client.close();
  29286. EXPECT_EQ(0, proxy.connect_hits());
  29287. }
  29288. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  29289. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29290. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29291. ASSERT_NE(0, proxy.port());
  29292. ws::WebSocketClient client(origin.url());
  29293. client.set_proxy("127.0.0.1", proxy.port());
  29294. ASSERT_TRUE(client.connect());
  29295. ASSERT_TRUE(client.connect());
  29296. client.close();
  29297. EXPECT_EQ(2, proxy.connect_hits());
  29298. }
  29299. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  29300. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29301. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29302. ASSERT_NE(0, proxy.port());
  29303. auto port = std::to_string(origin.port());
  29304. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  29305. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  29306. client.set_proxy("127.0.0.1", proxy.port());
  29307. auto res = client.connect();
  29308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29309. std::string msg;
  29310. ASSERT_TRUE(client.read(msg));
  29311. client.close();
  29312. EXPECT_EQ(1, proxy.connect_hits());
  29313. auto target = "127.0.0.1:" + port;
  29314. auto connect_req = proxy.connect_request();
  29315. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29316. EXPECT_NE(std::string::npos,
  29317. connect_req.find("\r\nHost: " + target + "\r\n"));
  29318. }
  29319. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  29320. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29321. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29322. ASSERT_NE(0, proxy.port());
  29323. auto port = std::to_string(origin.port());
  29324. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  29325. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  29326. client.set_proxy("127.0.0.1", proxy.port());
  29327. auto res = client.connect();
  29328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29329. client.close();
  29330. auto target = "origin.example:" + port;
  29331. auto connect_req = proxy.connect_request();
  29332. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29333. EXPECT_NE(std::string::npos,
  29334. connect_req.find("\r\nHost: " + target + "\r\n"));
  29335. }
  29336. #ifdef CPPHTTPLIB_SSL_ENABLED
  29337. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  29338. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29339. proxy_tunnel_test::ScopedConnectProxy proxy(
  29340. origin.port(), [](const std::string &head) -> std::string {
  29341. if (head.find(
  29342. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  29343. std::string::npos) {
  29344. return proxy_tunnel_test::kTunnelEstablished;
  29345. }
  29346. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  29347. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  29348. "nonce=\"abc\", algorithm=MD5\r\n"
  29349. "Content-Length: 0\r\n\r\n";
  29350. });
  29351. ASSERT_NE(0, proxy.port());
  29352. ws::WebSocketClient client(origin.url());
  29353. client.set_proxy("127.0.0.1", proxy.port());
  29354. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  29355. auto res = client.connect();
  29356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29357. std::string msg;
  29358. ASSERT_TRUE(client.read(msg));
  29359. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  29360. client.close();
  29361. EXPECT_EQ(2, proxy.connect_hits());
  29362. }
  29363. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  29364. proxy_tunnel_test::ScopedSSLServer origin;
  29365. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  29366. origin.listen();
  29367. proxy_tunnel_test::ScopedConnectProxy proxy(
  29368. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29369. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  29370. ASSERT_NE(0, proxy.port());
  29371. ws::WebSocketClient client(
  29372. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  29373. client.enable_server_certificate_verification(false);
  29374. client.set_proxy("127.0.0.1", proxy.port());
  29375. client.set_proxy_bearer_token_auth("proxy-token");
  29376. auto res = client.connect();
  29377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29378. std::string msg;
  29379. ASSERT_TRUE(client.read(msg));
  29380. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  29381. << "Proxy-Authorization must not be sent inside the tunnel";
  29382. client.close();
  29383. EXPECT_EQ(1, proxy.connect_hits());
  29384. }
  29385. #endif
  29386. // ---------------------------------------------------------------------------
  29387. // Poller
  29388. // ---------------------------------------------------------------------------
  29389. namespace poller_test {
  29390. struct PollerBackend {
  29391. const char *name;
  29392. std::unique_ptr<detail::Poller> (*create)();
  29393. };
  29394. void PrintTo(const PollerBackend &backend, std::ostream *os) {
  29395. *os << backend.name;
  29396. }
  29397. // Every backend runs the same contract tests. A new one is added here only.
  29398. std::vector<PollerBackend> poller_backends() {
  29399. return {
  29400. {"poll", &detail::PollPoller::create},
  29401. #ifdef __linux__
  29402. {"epoll", &detail::EpollPoller::create},
  29403. #endif
  29404. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  29405. {"kqueue", &detail::KqueuePoller::create},
  29406. #endif
  29407. };
  29408. }
  29409. // A descriptor whose readability the test controls.
  29410. struct TestSocketPair {
  29411. socket_t fd[2] = {INVALID_SOCKET, INVALID_SOCKET};
  29412. TestSocketPair() { detail::create_socket_pair(fd); }
  29413. ~TestSocketPair() {
  29414. for (auto s : fd) {
  29415. if (s != INVALID_SOCKET) { detail::close_socket(s); }
  29416. }
  29417. }
  29418. bool ok() const { return fd[0] != INVALID_SOCKET; }
  29419. socket_t reader() const { return fd[0]; }
  29420. void make_readable() {
  29421. const char c = 1;
  29422. detail::send_socket(fd[1], &c, 1, 0);
  29423. }
  29424. void close_writer() {
  29425. detail::close_socket(fd[1]);
  29426. fd[1] = INVALID_SOCKET;
  29427. }
  29428. };
  29429. using Tokens = std::vector<detail::Poller::Token>;
  29430. class PollerTest : public ::testing::TestWithParam<PollerBackend> {
  29431. protected:
  29432. void SetUp() override {
  29433. poller_ = GetParam().create();
  29434. ASSERT_TRUE(poller_ != nullptr);
  29435. }
  29436. Tokens wait_for(int timeout_ms) {
  29437. Tokens ready;
  29438. poller_->wait(timeout_ms, ready);
  29439. std::sort(ready.begin(), ready.end());
  29440. return ready;
  29441. }
  29442. std::unique_ptr<detail::Poller> poller_;
  29443. };
  29444. } // namespace poller_test
  29445. using poller_test::PollerTest;
  29446. using poller_test::TestSocketPair;
  29447. using poller_test::Tokens;
  29448. INSTANTIATE_TEST_SUITE_P(
  29449. Backends, PollerTest, ::testing::ValuesIn(poller_test::poller_backends()),
  29450. [](const ::testing::TestParamInfo<poller_test::PollerBackend> &p) {
  29451. return std::string(p.param.name);
  29452. });
  29453. TEST_P(PollerTest, DeliversOnceThenStaysDisarmedUntilRearmed) {
  29454. TestSocketPair sp;
  29455. ASSERT_TRUE(sp.ok());
  29456. ASSERT_TRUE(poller_->arm(sp.reader(), 7));
  29457. EXPECT_EQ(Tokens{}, wait_for(0));
  29458. sp.make_readable();
  29459. EXPECT_EQ(Tokens{7}, wait_for(1000));
  29460. EXPECT_EQ(Tokens{}, wait_for(0)); // still readable, but disarmed
  29461. ASSERT_TRUE(poller_->arm(sp.reader(), 8));
  29462. EXPECT_EQ(Tokens{8}, wait_for(1000));
  29463. }
  29464. TEST_P(PollerTest, DisarmedDescriptorIsNotDelivered) {
  29465. TestSocketPair sp;
  29466. ASSERT_TRUE(sp.ok());
  29467. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  29468. poller_->disarm(sp.reader());
  29469. poller_->disarm(sp.reader()); // disarming twice is harmless
  29470. sp.make_readable();
  29471. EXPECT_EQ(Tokens{}, wait_for(0));
  29472. }
  29473. TEST_P(PollerTest, WaitHonoursItsTimeout) {
  29474. TestSocketPair sp;
  29475. ASSERT_TRUE(sp.ok());
  29476. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  29477. auto start = std::chrono::steady_clock::now();
  29478. EXPECT_EQ(Tokens{}, wait_for(30));
  29479. auto elapsed = std::chrono::steady_clock::now() - start;
  29480. EXPECT_GE(elapsed, std::chrono::milliseconds(25));
  29481. EXPECT_LT(elapsed, std::chrono::seconds(1));
  29482. }
  29483. TEST_P(PollerTest, OnlyTheReadyDescriptorsAreDelivered) {
  29484. std::vector<std::unique_ptr<TestSocketPair>> sps;
  29485. for (detail::Poller::Token i = 0; i < 8; i++) {
  29486. sps.emplace_back(new TestSocketPair());
  29487. ASSERT_TRUE(sps.back()->ok());
  29488. ASSERT_TRUE(poller_->arm(sps.back()->reader(), i));
  29489. }
  29490. sps[0]->make_readable();
  29491. sps[3]->make_readable();
  29492. sps[7]->make_readable();
  29493. EXPECT_EQ((Tokens{0, 3, 7}), wait_for(1000));
  29494. // The others are still armed, the delivered ones are not.
  29495. sps[1]->make_readable();
  29496. EXPECT_EQ(Tokens{1}, wait_for(1000));
  29497. EXPECT_EQ(Tokens{}, wait_for(0));
  29498. }
  29499. TEST_P(PollerTest, StaysConsistentAfterOtherDescriptorsWereDelivered) {
  29500. TestSocketPair s0, s1, s2;
  29501. ASSERT_TRUE(s0.ok() && s1.ok() && s2.ok());
  29502. ASSERT_TRUE(poller_->arm(s0.reader(), 0));
  29503. ASSERT_TRUE(poller_->arm(s1.reader(), 1));
  29504. ASSERT_TRUE(poller_->arm(s2.reader(), 2));
  29505. // A delivery may move another entry inside the poller.
  29506. s0.make_readable();
  29507. EXPECT_EQ(Tokens{0}, wait_for(1000));
  29508. // The entries left must still be found by descriptor.
  29509. poller_->disarm(s2.reader());
  29510. s1.make_readable();
  29511. s2.make_readable();
  29512. EXPECT_EQ(Tokens{1}, wait_for(1000));
  29513. }
  29514. TEST_P(PollerTest, PeerHangUpCountsAsReadable) {
  29515. TestSocketPair sp;
  29516. ASSERT_TRUE(sp.ok());
  29517. ASSERT_TRUE(poller_->arm(sp.reader(), 5));
  29518. sp.close_writer();
  29519. EXPECT_EQ(Tokens{5}, wait_for(1000));
  29520. char c;
  29521. EXPECT_EQ(0, detail::read_socket(sp.reader(), &c, 1, 0)); // EOF
  29522. }
  29523. TEST_P(PollerTest, WakeEndsABlockedWait) {
  29524. std::thread waker([&] {
  29525. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  29526. poller_->wake();
  29527. });
  29528. Tokens ready;
  29529. auto start = std::chrono::steady_clock::now();
  29530. EXPECT_TRUE(poller_->wait(5000, ready)); // only the waker ends this early
  29531. waker.join();
  29532. EXPECT_TRUE(ready.empty());
  29533. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(1));
  29534. }
  29535. TEST_P(PollerTest, WakeBeforeWaitIsNotLost) {
  29536. poller_->wake(); // e.g. stop() running before the reactor reaches wait()
  29537. Tokens ready;
  29538. EXPECT_TRUE(poller_->wait(1000, ready));
  29539. }
  29540. TEST_P(PollerTest, WakesCoalesceAndAreConsumed) {
  29541. for (int i = 0; i < 1000; i++) {
  29542. poller_->wake();
  29543. }
  29544. Tokens ready;
  29545. EXPECT_TRUE(poller_->wait(0, ready));
  29546. EXPECT_FALSE(poller_->wait(0, ready));
  29547. poller_->wake();
  29548. EXPECT_TRUE(poller_->wait(0, ready));
  29549. }
  29550. TEST_P(PollerTest, ConcurrentWakesAreNeverLost) {
  29551. // Two threads publish changes and wake() after each, as a reactor's workers
  29552. // do. Every change must be seen without a wait() timing out. A lost wake()
  29553. // needs an unlucky interleaving, hence the rounds.
  29554. for (int round = 0; round < 5; round++) {
  29555. SCOPED_TRACE(round);
  29556. const int per_thread = 20000;
  29557. std::atomic<int> posted{0};
  29558. auto post = [&] {
  29559. for (int i = 0; i < per_thread; i++) {
  29560. posted++;
  29561. poller_->wake();
  29562. }
  29563. };
  29564. std::thread t1(post), t2(post);
  29565. auto lost = false;
  29566. Tokens ready;
  29567. for (auto seen = 0; seen < 2 * per_thread; seen = posted) {
  29568. if (!poller_->wait(1000, ready)) {
  29569. lost = true;
  29570. break;
  29571. }
  29572. }
  29573. t1.join();
  29574. t2.join();
  29575. ASSERT_FALSE(lost);
  29576. }
  29577. }
  29578. TEST(PollerFactoryTest, MakePollerWorks) {
  29579. auto poller = detail::make_poller();
  29580. ASSERT_TRUE(poller != nullptr);
  29581. poller->wake();
  29582. std::vector<detail::Poller::Token> ready;
  29583. EXPECT_TRUE(poller->wait(1000, ready));
  29584. }
  29585. // ---------------------------------------------------------------------------
  29586. // Keep-alive parking
  29587. // ---------------------------------------------------------------------------
  29588. namespace parking_test {
  29589. // Runs `svr` on a free port and stops it when it goes away. `before_listen`
  29590. // runs once the port is bound and listening, before the server accepts.
  29591. struct RunningServer {
  29592. explicit RunningServer(
  29593. Server &svr, const std::function<void(int)> &before_listen = nullptr)
  29594. : svr_(svr) {
  29595. port = svr_.bind_to_any_port("127.0.0.1");
  29596. if (before_listen) { before_listen(port); }
  29597. thread = std::thread([this] { svr_.listen_after_bind(); });
  29598. svr_.wait_until_ready();
  29599. }
  29600. ~RunningServer() {
  29601. svr_.stop();
  29602. if (thread.joinable()) { thread.join(); }
  29603. }
  29604. Server &svr_;
  29605. int port = 0;
  29606. std::thread thread;
  29607. };
  29608. struct Sockets {
  29609. std::vector<socket_t> socks;
  29610. ~Sockets() {
  29611. for (auto s : socks) {
  29612. detail::close_socket(s);
  29613. }
  29614. }
  29615. socket_t connect(int port) {
  29616. auto error = Error::Success;
  29617. auto s = detail::create_client_socket("127.0.0.1", "", port, AF_UNSPEC,
  29618. false, false, nullptr, 2, 0, 2, 0, 2,
  29619. 0, std::string(), error);
  29620. if (s != INVALID_SOCKET) { socks.push_back(s); }
  29621. return s;
  29622. }
  29623. };
  29624. std::chrono::steady_clock::time_point in_ms(int ms) {
  29625. return std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  29626. }
  29627. bool readable_by(socket_t sock,
  29628. std::chrono::steady_clock::time_point deadline) {
  29629. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  29630. deadline - std::chrono::steady_clock::now())
  29631. .count();
  29632. return left > 0 && detail::select_read(sock, 0, left) > 0;
  29633. }
  29634. bool send_get(socket_t sock, const std::string &path = "/") {
  29635. auto req = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
  29636. return detail::send_socket(sock, req.data(), req.size(), 0) ==
  29637. static_cast<ssize_t>(req.size());
  29638. }
  29639. // Reads one response whose body is "ok".
  29640. bool receives_ok(socket_t sock, int timeout_ms) {
  29641. auto deadline = in_ms(timeout_ms);
  29642. std::string buf;
  29643. while (readable_by(sock, deadline)) {
  29644. char tmp[1024];
  29645. auto n = detail::read_socket(sock, tmp, sizeof(tmp), 0);
  29646. if (n <= 0) { return false; }
  29647. buf.append(tmp, static_cast<size_t>(n));
  29648. auto end = buf.find("\r\n\r\n");
  29649. if (end != std::string::npos && buf.size() >= end + 4 + 2) {
  29650. return buf.compare(0, 12, "HTTP/1.1 200") == 0 &&
  29651. buf.compare(end + 4, 2, "ok") == 0;
  29652. }
  29653. }
  29654. return false;
  29655. }
  29656. bool get_ok(socket_t sock, int timeout_ms) {
  29657. return send_get(sock) && receives_ok(sock, timeout_ms);
  29658. }
  29659. // Whether the server closes `sock` by `deadline`.
  29660. bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
  29661. char c;
  29662. return readable_by(sock, deadline) &&
  29663. detail::read_socket(sock, &c, 1, 0) <= 0;
  29664. }
  29665. // Whether the server closes `sock` without answering a request.
  29666. bool get_refused(socket_t sock, int timeout_ms) {
  29667. return send_get(sock) && sees_eof(sock, in_ms(timeout_ms));
  29668. }
  29669. bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
  29670. auto deadline = in_ms(timeout_ms);
  29671. while (!cond()) {
  29672. if (std::chrono::steady_clock::now() > deadline) { return false; }
  29673. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  29674. }
  29675. return true;
  29676. }
  29677. void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue) {
  29678. svr.new_task_queue = std::move(new_task_queue);
  29679. svr.set_keep_alive_parking(true);
  29680. svr.Get("/", [](const Request &, Response &res) {
  29681. res.set_content("ok", "text/plain");
  29682. });
  29683. }
  29684. std::function<TaskQueue *(void)> threads(size_t n) {
  29685. return [n] { return new ThreadPool(n); };
  29686. }
  29687. // Counts what the event loop managed to queue, so that a test can wait for it.
  29688. class CountingTaskQueue final : public TaskQueue {
  29689. public:
  29690. CountingTaskQueue(size_t threads, size_t max_queued, std::atomic<int> &ok,
  29691. std::atomic<int> &full)
  29692. : pool_(threads, threads, max_queued), ok_(ok), full_(full) {}
  29693. bool enqueue(std::function<void()> fn) override {
  29694. auto queued = pool_.enqueue([this, fn]() {
  29695. fn();
  29696. // Holds the worker back from taking the next job.
  29697. std::this_thread::sleep_for(std::chrono::milliseconds(pause_after_ms));
  29698. });
  29699. (queued ? ok_ : full_)++;
  29700. return queued;
  29701. }
  29702. void shutdown() override { pool_.shutdown(); }
  29703. std::atomic<int> pause_after_ms{0};
  29704. private:
  29705. ThreadPool pool_;
  29706. std::atomic<int> &ok_;
  29707. std::atomic<int> &full_;
  29708. };
  29709. // Holds handlers until it opens, or for 3 seconds at most.
  29710. class Gate {
  29711. public:
  29712. void wait() {
  29713. std::unique_lock<std::mutex> lock(m_);
  29714. entered_++;
  29715. cv_.notify_all();
  29716. cv_.wait_for(lock, std::chrono::seconds(3), [&] { return open_; });
  29717. }
  29718. void open() {
  29719. std::lock_guard<std::mutex> guard(m_);
  29720. open_ = true;
  29721. cv_.notify_all();
  29722. }
  29723. int entered() {
  29724. std::lock_guard<std::mutex> guard(m_);
  29725. return entered_;
  29726. }
  29727. private:
  29728. std::mutex m_;
  29729. std::condition_variable cv_;
  29730. bool open_ = false;
  29731. int entered_ = 0;
  29732. };
  29733. } // namespace parking_test
  29734. TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
  29735. using namespace parking_test;
  29736. Server svr;
  29737. serve_ok(svr, threads(1));
  29738. RunningServer running(svr);
  29739. Sockets socks;
  29740. // One kept-alive connection that has been served, and many that have not
  29741. // sent anything yet. None of them may keep the only worker.
  29742. auto served = socks.connect(running.port);
  29743. ASSERT_TRUE(get_ok(served, 2000));
  29744. for (int i = 0; i < 49; i++) {
  29745. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29746. }
  29747. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29748. EXPECT_TRUE(get_ok(served, 1000));
  29749. }
  29750. TEST(KeepAliveParkingTest, IdleConnectionsTimeOutTogether) {
  29751. using namespace parking_test;
  29752. Server svr;
  29753. serve_ok(svr, threads(1));
  29754. svr.set_keep_alive_timeout(1);
  29755. RunningServer running(svr);
  29756. Sockets socks;
  29757. for (int i = 0; i < 3; i++) {
  29758. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29759. }
  29760. // One worker waiting on each in turn would take about 3 seconds.
  29761. auto deadline = in_ms(2000);
  29762. for (auto s : socks.socks) {
  29763. EXPECT_TRUE(sees_eof(s, deadline));
  29764. }
  29765. }
  29766. TEST(KeepAliveParkingTest, EstablishedConnectionWaitsForAFullQueue) {
  29767. using namespace parking_test;
  29768. std::atomic<int> queued{0}, full{0};
  29769. Server svr;
  29770. // One worker and room for one queued task.
  29771. serve_ok(svr, [&] { return new CountingTaskQueue(1, 1, queued, full); });
  29772. Gate gate;
  29773. svr.Get("/block", [&](const Request &, Response &res) {
  29774. gate.wait();
  29775. res.set_content("ok", "text/plain");
  29776. });
  29777. RunningServer running(svr);
  29778. // Before the server stops, so that a failed run does not wait for the
  29779. // handler's timeout.
  29780. auto open_gate = detail::scope_exit([&] { gate.open(); });
  29781. Sockets socks;
  29782. auto a = socks.connect(running.port);
  29783. ASSERT_TRUE(get_ok(a, 2000));
  29784. // B keeps the only worker busy.
  29785. auto b = socks.connect(running.port);
  29786. ASSERT_TRUE(send_get(b, "/block"));
  29787. ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
  29788. // A new connection C fills the queue.
  29789. auto c = socks.connect(running.port);
  29790. ASSERT_TRUE(send_get(c));
  29791. ASSERT_TRUE(wait_until([&] { return queued == 3; }, 2000));
  29792. // A's next request finds the queue full, but A has been served before, so it
  29793. // waits instead of being cut off.
  29794. ASSERT_TRUE(send_get(a));
  29795. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29796. gate.open();
  29797. EXPECT_TRUE(receives_ok(b, 2000));
  29798. EXPECT_TRUE(receives_ok(c, 2000));
  29799. EXPECT_TRUE(receives_ok(a, 2000));
  29800. }
  29801. TEST(KeepAliveParkingTest, BacklogIsRetriedOnceTheQueueHasRoom) {
  29802. using namespace parking_test;
  29803. std::atomic<int> queued{0}, full{0};
  29804. CountingTaskQueue *queue = nullptr;
  29805. Server svr;
  29806. // Two workers and room for one queued task.
  29807. serve_ok(svr,
  29808. [&] { return queue = new CountingTaskQueue(2, 1, queued, full); });
  29809. Gate first, second;
  29810. svr.Get("/first", [&](const Request &, Response &res) {
  29811. first.wait();
  29812. res.set_content("ok", "text/plain");
  29813. });
  29814. svr.Get("/second", [&](const Request &, Response &res) {
  29815. second.wait();
  29816. res.set_content("ok", "text/plain");
  29817. });
  29818. RunningServer running(svr);
  29819. auto open_gates = detail::scope_exit([&] {
  29820. first.open();
  29821. second.open();
  29822. });
  29823. Sockets socks;
  29824. auto a = socks.connect(running.port);
  29825. ASSERT_TRUE(get_ok(a, 2000));
  29826. // B and D take both workers, and C fills the queue. One at a time: the
  29827. // queue has room for one job only until a worker takes it.
  29828. ASSERT_TRUE(send_get(socks.connect(running.port), "/first"));
  29829. ASSERT_TRUE(wait_until([&] { return first.entered() == 1; }, 2000));
  29830. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29831. ASSERT_TRUE(wait_until([&] { return second.entered() == 1; }, 2000));
  29832. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29833. ASSERT_TRUE(wait_until([&] { return queued == 4; }, 2000));
  29834. // A's next request waits in the backlog.
  29835. ASSERT_TRUE(send_get(a));
  29836. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29837. // B's worker finishes, then takes C off the queue only later, which makes
  29838. // room for A.
  29839. queue->pause_after_ms = 200;
  29840. first.open();
  29841. EXPECT_TRUE(wait_until([&] { return queued == 5; }, 1000));
  29842. queue->pause_after_ms = 0;
  29843. second.open();
  29844. EXPECT_TRUE(receives_ok(a, 2000));
  29845. }
  29846. TEST(KeepAliveParkingTest, ZeroKeepAliveTimeoutServesTheFirstRequest) {
  29847. using namespace parking_test;
  29848. Server svr;
  29849. serve_ok(svr, threads(1));
  29850. svr.set_keep_alive_timeout(0);
  29851. // The request is on the socket before the server accepts the connection,
  29852. // so it does not race the 10 ms floor. Without the floor the connection is
  29853. // closed unread.
  29854. Sockets socks;
  29855. auto sock = INVALID_SOCKET;
  29856. RunningServer running(svr, [&](int port) {
  29857. sock = socks.connect(port);
  29858. send_get(sock);
  29859. });
  29860. EXPECT_TRUE(receives_ok(sock, 1000));
  29861. }
  29862. TEST(KeepAliveParkingTest, StopClosesParkedConnectionsPromptly) {
  29863. using namespace parking_test;
  29864. for (int round = 0; round < 5; round++) {
  29865. SCOPED_TRACE(round);
  29866. Server svr;
  29867. serve_ok(svr, threads(2));
  29868. RunningServer running(svr);
  29869. Sockets socks;
  29870. for (int i = 0; i < 20; i++) {
  29871. ASSERT_TRUE(get_ok(socks.connect(running.port), 1000));
  29872. }
  29873. auto start = std::chrono::steady_clock::now();
  29874. svr.stop();
  29875. running.thread.join();
  29876. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29877. std::chrono::milliseconds(500));
  29878. auto deadline = in_ms(1000);
  29879. for (auto s : socks.socks) {
  29880. EXPECT_TRUE(sees_eof(s, deadline));
  29881. }
  29882. }
  29883. }
  29884. #ifdef CPPHTTPLIB_SSL_ENABLED
  29885. namespace parking_test {
  29886. // Completes a TLS handshake on `sock` and sends nothing more, like a browser
  29887. // that has opened a connection ahead of time. Freeing the session sends no
  29888. // close_notify, so the connection stays quiet.
  29889. bool handshake_only(socket_t sock) {
  29890. auto ctx = tls::create_client_context();
  29891. tls::set_verify_client(ctx, false);
  29892. auto session = tls::create_session(ctx, sock);
  29893. auto se = detail::scope_exit([&] {
  29894. tls::free_session(session);
  29895. tls::free_context(ctx);
  29896. });
  29897. tls::TlsError err;
  29898. return session &&
  29899. tls::connect_nonblocking(session, sock, 2, 0, &err, nullptr);
  29900. }
  29901. Client tls_client(int port) {
  29902. Client cli("https://127.0.0.1:" + std::to_string(port));
  29903. cli.enable_server_certificate_verification(false);
  29904. cli.set_keep_alive(true);
  29905. cli.set_connection_timeout(1);
  29906. cli.set_read_timeout(1);
  29907. return cli;
  29908. }
  29909. bool tls_get_ok(Client &cli) {
  29910. auto res = cli.Get("/");
  29911. return res && res->body == "ok";
  29912. }
  29913. } // namespace parking_test
  29914. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  29915. TEST(KeepAliveParkingTest, SslFreeBuffersOnlyWhereTheCveIsFixed) {
  29916. struct {
  29917. unsigned long version;
  29918. bool safe;
  29919. } cases[] = {
  29920. {0x30000020UL, false}, {0x300000d0UL, false}, {0x300000e0UL, true},
  29921. {0x300000f0UL, true}, {0x30100050UL, false}, {0x30100060UL, true},
  29922. {0x30200010UL, false}, {0x30200020UL, true}, {0x30300000UL, false},
  29923. {0x30300010UL, true}, {0x30400000UL, true}, {0x40000000UL, true},
  29924. };
  29925. for (const auto &c : cases) {
  29926. EXPECT_EQ(c.safe, detail::ssl_free_buffers_is_safe(c.version))
  29927. << std::hex << c.version;
  29928. }
  29929. }
  29930. #endif
  29931. TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
  29932. using namespace parking_test;
  29933. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29934. ASSERT_TRUE(svr.is_valid());
  29935. serve_ok(svr, threads(1));
  29936. svr.set_read_timeout(1); // so that a failing run does not take long
  29937. RunningServer running(svr);
  29938. Sockets socks;
  29939. // One served connection, some that have not started their handshake, and
  29940. // one that has finished it and gone quiet. None may keep the only worker.
  29941. auto served = tls_client(running.port);
  29942. ASSERT_TRUE(tls_get_ok(served));
  29943. for (int i = 0; i < 10; i++) {
  29944. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29945. }
  29946. EXPECT_TRUE(handshake_only(socks.connect(running.port)));
  29947. auto other = tls_client(running.port);
  29948. EXPECT_TRUE(tls_get_ok(other));
  29949. EXPECT_TRUE(tls_get_ok(served));
  29950. }
  29951. TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
  29952. using namespace parking_test;
  29953. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29954. ASSERT_TRUE(svr.is_valid());
  29955. serve_ok(svr, threads(1));
  29956. RunningServer running(svr);
  29957. Sockets socks;
  29958. auto plain = socks.connect(running.port);
  29959. ASSERT_TRUE(send_get(plain));
  29960. EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
  29961. EXPECT_NE(0, svr.ssl_last_error());
  29962. }
  29963. TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
  29964. using namespace parking_test;
  29965. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29966. ASSERT_TRUE(svr.is_valid());
  29967. serve_ok(svr, threads(2));
  29968. RunningServer running(svr);
  29969. std::vector<Client> clients;
  29970. for (int i = 0; i < 5; i++) {
  29971. clients.push_back(tls_client(running.port));
  29972. ASSERT_TRUE(tls_get_ok(clients.back()));
  29973. }
  29974. auto start = std::chrono::steady_clock::now();
  29975. svr.stop();
  29976. running.thread.join();
  29977. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29978. std::chrono::milliseconds(500));
  29979. }
  29980. #endif
  29981. TEST(AcceptHandlerTest, RefusedConnectionIsClosedUnread) {
  29982. using namespace parking_test;
  29983. for (auto parking : {false, true}) {
  29984. SCOPED_TRACE(parking);
  29985. Server svr;
  29986. serve_ok(svr, threads(2));
  29987. svr.set_keep_alive_parking(parking);
  29988. std::atomic<int> served{0};
  29989. svr.set_pre_routing_handler([&](const Request &, Response &) {
  29990. served++;
  29991. return Server::HandlerResponse::Unhandled;
  29992. });
  29993. std::atomic<bool> allow{false};
  29994. std::atomic<bool> peer_seen{false};
  29995. svr.set_accept_handler([&](socket_t sock) {
  29996. sockaddr_in addr{};
  29997. socklen_t len = sizeof(addr);
  29998. peer_seen =
  29999. getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &len) == 0 &&
  30000. addr.sin_family == AF_INET &&
  30001. ntohl(addr.sin_addr.s_addr) == INADDR_LOOPBACK;
  30002. return allow.load();
  30003. });
  30004. RunningServer running(svr);
  30005. Sockets socks;
  30006. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  30007. EXPECT_TRUE(peer_seen);
  30008. EXPECT_EQ(0, served);
  30009. allow = true;
  30010. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  30011. EXPECT_EQ(1, served);
  30012. }
  30013. }
  30014. TEST(AcceptHandlerTest, HandlerSeesTheReadTimeout) {
  30015. using namespace parking_test;
  30016. Server svr;
  30017. serve_ok(svr, threads(1));
  30018. svr.set_read_timeout(std::chrono::milliseconds(50));
  30019. std::atomic<bool> timed_out{false};
  30020. svr.set_accept_handler([&](socket_t sock) {
  30021. char c;
  30022. timed_out = detail::read_socket(sock, &c, 1, 0) < 0;
  30023. return true;
  30024. });
  30025. RunningServer running(svr);
  30026. Sockets socks;
  30027. auto sock = socks.connect(running.port);
  30028. EXPECT_TRUE(wait_until([&] { return timed_out.load(); }, 1000));
  30029. EXPECT_TRUE(get_ok(sock, 1000));
  30030. }
  30031. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  30032. TEST(AcceptHandlerTest, ThrowingHandlerRefusesTheConnection) {
  30033. using namespace parking_test;
  30034. Server svr;
  30035. serve_ok(svr, threads(1));
  30036. std::atomic<bool> throws{true};
  30037. svr.set_accept_handler([&](socket_t) -> bool {
  30038. if (throws) { throw std::runtime_error("refused"); }
  30039. return true;
  30040. });
  30041. std::atomic<int> logged{0};
  30042. svr.set_error_logger([&](const Error &err, const Request *) {
  30043. if (err == Error::UserCallbackException) { logged++; }
  30044. });
  30045. RunningServer running(svr);
  30046. Sockets socks;
  30047. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  30048. EXPECT_EQ(1, logged);
  30049. throws = false;
  30050. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  30051. }
  30052. #endif
  30053. #ifdef CPPHTTPLIB_SSL_ENABLED
  30054. TEST(AcceptHandlerTest, RefusedTlsConnectionSkipsTheHandshake) {
  30055. using namespace parking_test;
  30056. for (auto parking : {false, true}) {
  30057. SCOPED_TRACE(parking);
  30058. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  30059. ASSERT_TRUE(svr.is_valid());
  30060. serve_ok(svr, threads(1));
  30061. svr.set_keep_alive_parking(parking);
  30062. svr.set_accept_handler([](socket_t) { return false; });
  30063. RunningServer running(svr);
  30064. Sockets socks;
  30065. // A handshake on a plain request would fail and set ssl_last_error().
  30066. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  30067. EXPECT_EQ(0, svr.ssl_last_error());
  30068. }
  30069. }
  30070. #endif